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

The following examples show how to use org.openide.filesystems.FileObject#getParent() . 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: FolderObjTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Test of getFileObject method, of class org.netbeans.modules.masterfs.filebasedfs.fileobjects.FolderObj.
 */
public void testGetFileObject() {
    File f = testFile;
    FileSystem fs = FileBasedFileSystem.getInstance();
    assertNotNull(fs);
    
    while (f != null && f.exists()) {
        FileObject fo = FileBasedFileSystem.getFileObject(f);
        assertNotNull(f.getAbsolutePath(),fo);
        FileObject parent = fo.getParent();
        while (parent != null && parent != fo) {                
            assertNotNull(parent);
            assertNotNull(fo);
            String relativePath = FileUtil.getRelativePath(parent, fo);
            assertNotNull(relativePath);
            FileObject fo2 = parent.getFileObject(relativePath);
            assertNotNull((relativePath + " not found in " + parent.toString()), fo2);
            assertSame (fo, fo2);
            parent = parent.getParent();
        }

        assertNotNull(fs.getRoot().getFileObject(fo.getPath()));           
        f = f.getParentFile();            
    }        
}
 
Example 2
Source File: RequireJsPanel.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private String findRelativePath(FileObject from, FileObject to) {
    String path = FileUtil.getRelativePath(from, to);
    StringBuilder result = new StringBuilder();
    FileObject parent = from.getParent();
    while (path == null && parent != null) {
        result.append("../");
        path = FileUtil.getRelativePath(parent, to);
        parent = parent.getParent();
    }
    if (path != null) {
        result.append(path);
    } else {
        result.append(to.getPath());
    }
    return result.toString();
}
 
Example 3
Source File: DefaultProjectOperationsImplementationTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testMainProjectFlagMovedForMainProject() throws Exception {
    OpenProjects.getDefault().open(new Project[] {prj}, false);
    OpenProjects.getDefault().setMainProject(prj);
    assertEquals(prj, OpenProjects.getDefault().getMainProject());
    ProgressHandle handle = ProgressHandleFactory.createHandle("test-handle");
    handle.start(DefaultProjectOperationsImplementation.MAX_WORK);
    FileObject oldProject = prj.getProjectDirectory();
    File       oldProjectFile = FileUtil.toFile(oldProject);
    FileObject newTarget = oldProject.getParent();
    
    DefaultProjectOperationsImplementation.doMoveProject(handle, prj, "projMove", "projMove", newTarget, "ERR_Cannot_Move");
    
    Project newProject = ProjectManager.getDefault().findProject(newTarget.getFileObject("projMove"));
    
    assertEquals(OpenProjects.getDefault().getMainProject(), newProject);
}
 
Example 4
Source File: ClassPathFileChooser.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void checkNameField() {
    if (selectedFolder != null) {
        selectedFile = null;
        String fileName = fileNameTextField.getText();
        Node[] nodes = explorerManager.getSelectedNodes();
        if (nodes.length == 1) {
            FileObject fo = fileFromNode(nodes[0]);
            if (fo != null) {
                if (!fo.isFolder())
                    fo = fo.getParent();
                selectedFile = fo.getFileObject(fileName);
                selectedFolder = fo;
            }
        }
        if (okButton != null)
            okButton.setEnabled(selectedFile != null && (!selectedFile.isFolder() || choosingFolder));
        if (newButton != null) {
            newButton.setEnabled(selectedFile == null && choosingFolder
                                 && Utilities.isJavaIdentifier(fileName));
        }
    }
}
 
Example 5
Source File: WSUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static FileObject backupAndGenerateJaxWs(FileObject projectDir, FileObject oldJaxWs, RuntimeException reason) throws IOException {
    DialogDisplayer.getDefault().notify(
            new NotifyDescriptor.Message(NbBundle.getMessage(WSUtils.class,"ERR_corruptedJaxWs",oldJaxWs.getPath(),reason.getMessage()),NotifyDescriptor.ERROR_MESSAGE));
    FileObject parent = oldJaxWs.getParent();
    FileObject oldBackup = parent.getFileObject("jax-ws.xml.old"); //NOI18N
    FileLock lock = null;
    if (oldBackup!=null) {
        // remove old backup
        try {
            lock = oldBackup.lock();
            oldBackup.delete(lock);
        } finally {
            if (lock!=null) lock.releaseLock();
        }
    }
    // renaming old jax-ws.xml;
    try {
        lock = oldJaxWs.lock();
        oldJaxWs.rename(lock, "jax-ws.xml","old"); //NOI18N
    } finally {
        if (lock!=null) lock.releaseLock();
    }
    retrieveJaxWsFromResource(projectDir);
    return projectDir.getFileObject(JAX_WS_XML_PATH);
}
 
Example 6
Source File: ExtractInterfaceRefactoringPlugin.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Problem fastCheckParameters() {
    Problem result = null;
    
    String newName = refactoring.getInterfaceName();
    
    if (!Utilities.isJavaIdentifier(newName)) {
        result = createProblem(result, true, NbBundle.getMessage(ExtractInterfaceRefactoringPlugin.class, "ERR_InvalidIdentifier", newName)); // NOI18N
        return result;
    }
    
    FileObject primFile = refactoring.getSourceType().getFileObject();
    FileObject folder = primFile.getParent();
    FileObject[] children = folder.getChildren();
    for (FileObject child: children) {
        if (!child.isVirtual() && child.getName().equalsIgnoreCase(newName) && "java".equalsIgnoreCase(child.getExt())) { // NOI18N
            result = createProblem(result, true, NbBundle.getMessage(ExtractInterfaceRefactoringPlugin.class, "ERR_ClassClash", newName, pkgName)); // NOI18N
            return result;
        }
    }

    return super.fastCheckParameters();
}
 
Example 7
Source File: NodeJsUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static FileObject findNodeModule(final FileObject fromModule, final String module) {
    FileObject runtimeModule = getRuntimeModuleFile(fromModule, module);
    if (runtimeModule != null) {
        // the runtime modules has the biggest priority 
        return runtimeModule;
    }
    FileObject parentFolder = fromModule.isFolder() ? fromModule : fromModule.getParent();
    // we have to go through parent/node_modules/modulePath
    while (parentFolder != null) {
        FileObject nodeModulesFO = parentFolder.getFileObject(NODE_MODULES_NAME);
        if (nodeModulesFO != null) {
            FileObject resultFO = findModuleAsFile(nodeModulesFO, module); //NOI18N
            if (resultFO == null) {
                resultFO = findModuleAsFolder(nodeModulesFO, module); //NOI18N
            }
            if (resultFO != null) {
                return resultFO;
            }
        }
        parentFolder = parentFolder.getParent();
    }
    return null;
}
 
Example 8
Source File: CreateFromTemplateTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testNoTemplateFlagUnset() throws Exception {
    String folderName = "/Templates/";
    FileObject data = org.openide.filesystems.FileUtil.createData (
        FileUtil.getConfigRoot(), 
        folderName + "/" + "X.prima"
    );
    data.setAttribute ("template", Boolean.TRUE);
    FileObject fo = data.getParent ();
    assertNotNull ("FileObject " + folderName + " found on DefaultFileSystem.", fo);
    DataFolder f = DataFolder.findFolder (fo);
    DataObject templ = DataObject.find(data);
    
    DataObject res = templ.createFromTemplate(f);
    
    assertFalse("Not marked as template", res.isTemplate());
    assertEquals(SimpleLoader.class, res.getLoader().getClass());
}
 
Example 9
Source File: CakePHP3TemplateAttributesProvider.java    From cakephp3-netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, ?> attributesFor(CreateDescriptor desc) {
    // target
    FileObject targetDirectory = desc.getTarget();
    PhpModule phpModule = PhpModule.Factory.forFileObject(targetDirectory);
    if (phpModule == null) {
        return Collections.emptyMap();
    }
    if (!CakePHP3Module.isCakePHP(phpModule)) {
        return Collections.emptyMap();
    }

    // template
    Map<String, String> attributes = new HashMap<>();
    FileObject template = desc.getTemplate();
    FileObject parent = template.getParent();
    if (parent == null) {
        return Collections.emptyMap();
    }

    // set attributes
    if (parent.isFolder() && parent.getNameExt().equals(CakePHP3Constants.CAKEPHP3_FRAMEWORK)) {
        CakePHP3Module cakeModule = CakePHP3Module.forPhpModule(phpModule);
        String namespace = cakeModule.getNamespace(targetDirectory);
        attributes.put(NAMESPACE, namespace);
    }

    return attributes;
}
 
Example 10
Source File: Watcher.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static void register(FileObject fo) {
    Ext<?> ext = ext();
    if (ext == null) {
        return;
    }
    if (fo.isData()) {
        fo = fo.getParent();
    }
    ext.register(fo);
}
 
Example 11
Source File: SourceMapsScanner.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static FileObject findCompiledFile(FileObject sourceMapFile) {
    String name = sourceMapFile.getName();
    FileObject parent = sourceMapFile.getParent();
    FileObject compiledFO = parent.getFileObject(name);
    if (compiledFO != null) {
        return compiledFO;
    }
    compiledFO = parent.getFileObject(name, "js");
    if (compiledFO != null) {
        return compiledFO;
    }
    return null;
}
 
Example 12
Source File: FolderObjTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testFolderToFileWithParentRefresh() throws Exception {
    File f = new File(getWorkDir(), "classes");
    f.createNewFile();
    assertTrue("File created", f.isFile());
    
    FileObject fo = FileUtil.toFileObject(f);
    assertTrue("Is data", fo.isData());
    FileObject parent = fo.getParent();
    List<FileObject> arr = Arrays.asList(parent.getChildren());
    
    assertTrue("Contains " + fo + ": " +arr, arr.contains(fo));
    
    f.delete();
    f.mkdirs();
    assertTrue("Is dir", f.isDirectory());
    
    
    parent.refresh();
    
    assertFalse("No longer valid", fo.isValid());
    FileObject folder = FileUtil.toFileObject(f);
   
    if (fo == folder) {
        fail("Should not be the same: " + folder);
    }
    assertTrue("Is folder", folder.isFolder());
}
 
Example 13
Source File: JavaIndex.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static URL getSourceRootForClassFolder(URL binaryRoot) {
    FileObject folder = URLMapper.findFileObject(binaryRoot);
    if (folder == null || !CLASSES.equals(folder.getName()))
        return null;
    folder = folder.getParent();
    if (folder == null || !String.valueOf(VERSION).equals(folder.getName()))
        return null;
    folder = folder.getParent();
    if (folder == null || !NAME.equals(folder.getName()))
        return null;
    folder = folder.getParent();
    if (folder == null)
        return null;
    return CacheFolder.getSourceRootForDataFolder(folder);
}
 
Example 14
Source File: StatFilesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testGetFileObject() throws IOException {
    FileObject fobj = getFileObject(testFile);
    FileObject parent = fobj.getParent();
    parent = parent.createFolder("parent");
    assertTrue(new File(getFile(parent), "child").createNewFile());
    monitor.reset();
    FileObject ch = parent.getFileObject("child");
    monitor.getResults().assertResult(2, StatFiles.ALL);
    monitor.getResults().assertResult(2, StatFiles.READ);
    //second time
    monitor.reset();
    ch = parent.getFileObject("child");
    monitor.getResults().assertResult(0, StatFiles.ALL);
}
 
Example 15
Source File: ProjectUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Project getProjectForBuildScript(String fileName) {
    FileObject projectFO = FileUtil.toFileObject(new File(fileName));

    while (projectFO != null) {
        try {
            if (projectFO.isFolder()) {
                if (LOGGER.isLoggable(Level.FINEST)) {
                    LOGGER.log(Level.FINEST, "Trying: {0}", projectFO); //NOI18N
                }

                Project p = ProjectManager.getDefault().findProject(projectFO);

                if (LOGGER.isLoggable(Level.FINEST)) {
                    LOGGER.log(Level.FINEST, "Got: {0}", ((p != null) ? getProjectName(p) : null)); //NOI18N
                }

                if (p != null) {
                    return p;
                }
            }

            projectFO = projectFO.getParent();
        } catch (IOException e) {
            ProfilerLogger.severe("Got: IOException : " + e.getMessage()); //NOI18N
        }
    }

    return null;
}
 
Example 16
Source File: StatFilesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testGetParent() {
    FileObject fobj = getFileObject(testFile);
    monitor.reset();
    FileObject parent = fobj.getParent();
    monitor.getResults().assertResult(0, StatFiles.ALL);
    monitor.reset();
    parent = fobj.getParent();
    monitor.getResults().assertResult(0, StatFiles.ALL);

    //second time
    monitor.reset();
    parent = fobj.getParent();
    monitor.getResults().assertResult(0, StatFiles.ALL);
}
 
Example 17
Source File: HyperlinkProviderImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private FileObject getPath(FileObject parent, String path) {
    // TODO more substitutions necessary probably..
    if (path.startsWith("${basedir}/")) { //NOI18N
        path = path.substring("${basedir}/".length()); //NOI18N
    }
    while (path.startsWith("../") && parent.getParent() != null) { //NOI18N
        path = path.substring("../".length()); //NOI18N
        parent = parent.getParent();
    }
    return parent.getFileObject(path);
}
 
Example 18
Source File: LogicalViewProviderImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Node findPathPlain(FileObject fo, FileObject groupRoot, Node rootNode) {
    FileObject folder = fo.isFolder() ? fo : fo.getParent();
    String relPath = FileUtil.getRelativePath(groupRoot, folder);
    List<String> path = new ArrayList<String>();
    StringTokenizer strtok = new StringTokenizer(relPath, "/"); // NOI18N
    while (strtok.hasMoreTokens()) {
        String token = strtok.nextToken();
       path.add(token);
    }
    try {
        Node folderNode =  folder.equals(groupRoot) ? rootNode : NodeOp.findPath(rootNode, Collections.enumeration(path));
        if (fo.isFolder()) {
            return folderNode;
        } else {
            Node[] childs = folderNode.getChildren().getNodes(true);
            for (int i = 0; i < childs.length; i++) {
               DataObject dobj = childs[i].getLookup().lookup(DataObject.class);
               if (dobj != null && dobj.getPrimaryFile().getNameExt().equals(fo.getNameExt())) {
                   return childs[i];
               }
            }
        }
    } catch (NodeNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 19
Source File: I18nPanel.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void setDefaultResource(DataObject dataObject) {
        if (dataObject != null) {
            // look for peer Bundle.properties
            FileObject fo = dataObject.getPrimaryFile();
            ClassPath cp = ClassPath.getClassPath(fo, ClassPath.SOURCE);

            if (cp != null) {
                FileObject folder = cp.findResource(cp.getResourceName(fo.getParent()));

                while (folder != null && cp.contains(folder)) {
                
                    String rn = cp.getResourceName(folder) + "/Bundle.properties"; // NOI18N
                
                    FileObject peer = cp.findResource(rn);
                    if (peer == null) {
                        //Try to find any properties file
                        Enumeration<? extends FileObject> data = Enumerations.filter(folder.getData(false), new Enumerations.Processor(){
                            public Object process(Object obj, Collection alwaysNull) {
                                if (obj instanceof FileObject &&
                                        "properties".equals( ((FileObject)obj).getExt())){ //NOI18N
                                    return obj;
                                } else {
                                    return null;
                                }
                            }
                        });
                        if (data.hasMoreElements()) {
                            peer = data.nextElement();
                        }
                    }
                    if (peer != null) {
                        try {
                            DataObject peerDataObject = DataObject.find(peer);
//                          ((ResourcePanel)resourcePanel).setResource(peerDataObject);
                            propertyPanel.setResource(peerDataObject);
                            return;
                        } catch (IOException ex) {
                            // no default resource
                        }
                    }
                    folder = folder.getParent();
                }
            }
        }
    }
 
Example 20
Source File: AntArtifactChooser.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Shows dialog with the artifact chooser 
 * @return null if canceled selected jars if some jars selected
 */
static AntArtifactItem[] showDialog( String[] artifactTypes, Project master, Component parent ) {
    
    JFileChooser chooser = ProjectChooser.projectChooser();
    chooser.setDialogTitle( NbBundle.getMessage( AntArtifactChooser.class, "LBL_AACH_Title" ) ); // NOI18N
    chooser.setApproveButtonText( NbBundle.getMessage( AntArtifactChooser.class, "LBL_AACH_SelectProject" ) ); // NOI18N
    chooser.getAccessibleContext().setAccessibleDescription(NbBundle.getMessage (AntArtifactChooser.class,"AD_AACH_SelectProject"));
    AntArtifactChooser accessory = new AntArtifactChooser( artifactTypes, chooser );
    chooser.setAccessory( accessory );
    chooser.setPreferredSize( new Dimension( 650, 380 ) );        
    File defaultFolder = null;
    FileObject defFo = master.getProjectDirectory();
    if (defFo != null) {
        defFo = defFo.getParent();
        if (defFo != null) {
            defaultFolder = FileUtil.toFile(defFo);
        }
    }
    chooser.setCurrentDirectory (getLastUsedArtifactFolder(defaultFolder));

    int option = chooser.showOpenDialog( parent ); // Show the chooser
          
    if ( option == JFileChooser.APPROVE_OPTION ) {

        File dir = chooser.getSelectedFile();
        dir = FileUtil.normalizeFile (dir);
        Project selectedProject = accessory.getProject( dir );

        if ( selectedProject == null ) {
            return null;
        }
        
        if ( selectedProject.getProjectDirectory().equals( master.getProjectDirectory() ) ) {
            DialogDisplayer.getDefault().notify( new NotifyDescriptor.Message( 
                NbBundle.getMessage( AntArtifactChooser.class, "MSG_AACH_RefToItself" ),
                NotifyDescriptor.INFORMATION_MESSAGE ) );
            return null;
        }
        
        if ( ProjectUtils.hasSubprojectCycles( master, selectedProject ) ) {
            DialogDisplayer.getDefault().notify( new NotifyDescriptor.Message( 
                NbBundle.getMessage( AntArtifactChooser.class, "MSG_AACH_Cycles" ),
                NotifyDescriptor.INFORMATION_MESSAGE ) );
            return null;
        }

        boolean noSuitableOutput = true;
        for (String type : artifactTypes) {
            if (AntArtifactQuery.findArtifactsByType(selectedProject, type).length > 0) {
                noSuitableOutput = false;
                break;
            }
        }
        if (noSuitableOutput) {
            DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
                    NbBundle.getMessage (AntArtifactChooser.class,"MSG_NO_JAR_OUTPUT")));
            return null;
        }
        
        setLastUsedArtifactFolder (FileUtil.normalizeFile(chooser.getCurrentDirectory()));
        
        Object[] tmp = new Object[accessory.jListArtifacts.getModel().getSize()];
        int count = 0;
        for(int i = 0; i < tmp.length; i++) {
            if (accessory.jListArtifacts.isSelectedIndex(i)) {
                tmp[count] = accessory.jListArtifacts.getModel().getElementAt(i);
                count++;
            }
        }
        AntArtifactItem artifactItems[] = new AntArtifactItem[count];
        System.arraycopy(tmp, 0, artifactItems, 0, count);
        return artifactItems;
    }
    else {
        return null; 
    }
            
}