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

The following are Jave code examples for showing how to use getParent() of the org.openide.filesystems.FileObject class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: incubator-netbeans   File: DBSchemaManager.java   View Source Code Vote up 6 votes
/**
 * Overwrites <code>dbschemaFile</code> with the contents of
 * <code>schemaElement</code>.
 */
private static void overwriteDBSchema(SchemaElement schemaElement, FileObject dbschemaFile, DBIdentifier dbschemaName) throws IOException {
    try {
        schemaElement.setName(dbschemaName);
    } catch (DBException e) {
        IOException ioe = new IOException(e);
        throw ioe;
    }

    // cannot just overwrite the file, DBSchemaDataObject would not
    // notice the file has changed.
    FileObject parent = dbschemaFile.getParent();
    String fileName = dbschemaFile.getName();
    String fileExt = dbschemaFile.getExt();
    dbschemaFile.delete();
    FileObject newDBSchemaFile = parent.createData(fileName, fileExt);

    writeSchemaElement(schemaElement, newDBSchemaFile);
}
 
Example 2
Project: incubator-netbeans   File: DBSchemaManager.java   View Source Code Vote up 6 votes
/**
 * Overwrites <code>dbschemaFile</code> with the contents of
 * <code>schemaElement</code>.
 */
private static void overwriteDBSchema(SchemaElement schemaElement, FileObject dbschemaFile, DBIdentifier dbschemaName) throws IOException {
    try {
        schemaElement.setName(dbschemaName);
    } catch (DBException e) {
        IOException ioe = new IOException(e.getMessage());
        ioe.initCause(e);
        throw ioe;
    }

    // cannot just overwrite the file, DBSchemaDataObject would not
    // notice the file has changed.
    FileObject parent = dbschemaFile.getParent();
    String fileName = dbschemaFile.getName();
    String fileExt = dbschemaFile.getExt();
    dbschemaFile.delete();
    FileObject newDBSchemaFile = parent.createData(fileName, fileExt);

    writeSchemaElement(schemaElement, newDBSchemaFile);
}
 
Example 3
Project: incubator-netbeans   File: CopyResourcesOnSave.java   View Source Code Vote up 6 votes
private void fileRenamedImpl(final FileRenameEvent fe) {
    try {
        FileObject fo = fe.getFile();
        Project owning = getOwningMavenProject(fo);
        if (owning == null) {
            return;
        }
        Tuple base = findAppropriateResourceRoots(fo, owning);
        if (base != null) {
            handleCopyFileToDestDir(base, fo, owning);
            FileObject parent = fo.getParent();
            String path;
            if (FileUtil.isParentOf(base.root, parent)) {
                path = FileUtil.getRelativePath(base.root, fo.getParent()) +
                        "/" + fe.getName() + "." + fe.getExt(); //NOI18N
            } else {
                path = fe.getName() + "." + fe.getExt(); //NOI18N
            }
            handleDeleteFileInDestDir(fo, path, base, owning);
        }
    } catch (IOException e) {
        LOG.log(Level.INFO, null, e);
    }
}
 
Example 4
Project: incubator-netbeans   File: SourcesImpl.java   View Source Code Vote up 6 votes
private FileObject getSharedLibraryFolderLocation() {
    String libLoc = helper.getLibrariesLocation();
    if (libLoc != null) {
        String libLocEval = evaluator.evaluate(libLoc);
        if (libLocEval != null) {
            final File file = helper.resolveFile(libLocEval);
            FileObject libLocFO = FileUtil.toFileObject(file);
            if (libLocFO != null) {
                //#126366 this can happen when people checkout the project but not the libraries description
                //that is located outside the project
                FileObject libLocParent = libLocFO.getParent();
                return libLocParent;
            }
        }
    }
    return null;
}
 
Example 5
Project: incubator-netbeans   File: FolderNameTabDecorator.java   View Source Code Vote up 6 votes
@Override
public String getText( TabData tab ) {
    if( !settings.isShowFolderName() )
        return null;
    if( tab.getComponent() instanceof TopComponent ) {
        TopComponent tc = ( TopComponent ) tab.getComponent();
        DataObject dob = tc.getLookup().lookup( DataObject.class );
        if( null != dob ) {
            FileObject fo = dob.getPrimaryFile();
            if( fo.isData() ) {
                FileObject folder = fo.getParent();
                if( null != folder ) {
                    String folderName = folder.getNameExt() + pathSeparator;
                    String defaultText = tab.getText();

                    return merge( folderName, defaultText );
                }
            }
        }
    }
    return null;
}
 
Example 6
Project: incubator-netbeans   File: TreePathHandle.java   View Source Code Vote up 5 votes
public FileObject getFileObject() {
    //source does not exist
    FileObject file = SourceUtils.getFile(el, cpInfo);
    //tzezula: Very strange and probably useless
    if (file == null && source != null) {
        FileObject fo = URLMapper.findFileObject(source);
        if (fo == null) {
            log.log(Level.INFO, "There is no fileobject for source: " +source + ". Was this file removed?");
            return file;
        }
        file = fo;
        if (fo.getNameExt().endsWith(FileObjects.SIG)) {
            //NOI18N
            //conversion sig -> class
            String pkgName = FileObjects.convertPackage2Folder(qualName);
            StringTokenizer tk = new StringTokenizer(pkgName, "/"); //NOI18N
            for (int i = 0; fo != null && i <= tk.countTokens(); i++) {
                fo = fo.getParent();
            }
            if (fo != null) {
                try {
                    URL url = fo.getURL();
                    URL sourceRoot = null;//XXX: Index.getSourceRootForClassFolder(url);
                    if (sourceRoot != null) {
                        FileObject root = URLMapper.findFileObject(sourceRoot);
                        String resourceName = FileUtil.getRelativePath(fo, URLMapper.findFileObject(source));
                        file = root.getFileObject(resourceName.replace('.'+FileObjects.SIG, '.'+FileObjects.CLASS)); //NOI18N
                    } else {
                        Logger.getLogger(TreePathHandle.class.getName()).fine("Index.getSourceRootForClassFolder(url) returned null for url=" + url); //NOI18N
                    }
                } catch (FileStateInvalidException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        }
    }
    
    return file;
}
 
Example 7
Project: incubator-netbeans   File: Watcher.java   View Source Code Vote up 5 votes
public static boolean isWatched(FileObject fo) {
    Ext<?> ext = ext();
    if (ext == null) {
        return false;
    }
    if (fo.isData()) {
        fo = fo.getParent();
    }
    return ext.isWatched(fo);
}
 
Example 8
Project: incubator-netbeans   File: TreeRootNode.java   View Source Code Vote up 5 votes
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 9
Project: incubator-netbeans   File: RulesManager.java   View Source Code Vote up 5 votes
private static void categorizeErrorRules( List<Pair<Rule,FileObject>> rules,
                                         Map<String, Map<String,List<ErrorRule>>> dest,
                                         FileObject rootFolder) {
    dest.clear();

    for( Pair<Rule,FileObject> pair : rules ) {
        Rule rule = pair.getA();
        FileObject fo = pair.getB();
        String mime = FileUtil.getRelativePath(rootFolder, fo.getParent());

        if (mime.length() == 0) {
            mime = "text/x-java"; //TODO: use a predefined constant
        }

        if ( rule instanceof ErrorRule ) {
            Map<String, List<ErrorRule>> map = dest.get(mime);

            if (map == null) {
                dest.put(mime, map = new HashMap<String, List<ErrorRule>>());
                // first encounter the MIME type; read the 'inherit' rule from
                // the rule folder. Further definitions 
                FileObject mimeFolder = fo.getParent();
                Object o = mimeFolder.getAttribute("inherit.rules");
                if (Boolean.TRUE == o) {
                    Map<String, List<ErrorRule>> inheritMap = dest.get("text/x-java");
                    for (String c : inheritMap.keySet()) {
                        map.put(c, new ArrayList<ErrorRule>(inheritMap.get(c)));
                    }
                }
            }

            addRule( (ErrorRule)rule, map );
        }
        else {
            LOG.log( Level.WARNING, "The rule defined in " + fo.getPath() + "is not instance of ErrorRule" );
        }
    }
}
 
Example 10
Project: incubator-netbeans   File: PackageViewChildren.java   View Source Code Vote up 5 votes
@Override
public void destroy() throws IOException {
    FileObject parent = dataFolder.getPrimaryFile().getParent();
    // First; delete all files except packages
    DataObject ch[] = dataFolder.getChildren();
    boolean empty = true;
    for( int i = 0; ch != null && i < ch.length; i++ ) {
        if ( !ch[i].getPrimaryFile().isFolder() ) {
            ch[i].delete();
        }
        else {
            empty = false;
        }
    }
    
    // If empty delete itself
    if ( empty ) {
        super.destroy();
    }
    
    
    // Second; delete empty super packages
    while( !parent.equals( root ) && parent.getChildren().length == 0  ) {
        FileObject newParent = parent.getParent();
        parent.delete();
        parent = newParent;
    }
}
 
Example 11
Project: incubator-netbeans   File: RepositoryUpdaterTest.java   View Source Code Vote up 5 votes
public void testFilesScannedAfterRenameOfFolder193243() throws Exception {
    final TestHandler handler = new TestHandler();
    final Logger logger = Logger.getLogger(RepositoryUpdater.class.getName()+".tests");
    logger.setLevel (Level.FINEST);
    logger.addHandler(handler);
    final FileObject testFo = FileUtil.createData(this.srcRootWithFiles1, "rename/A.foo");
    final MutableClassPathImplementation mcpi1 = new MutableClassPathImplementation ();
    mcpi1.addResource(this.srcRootWithFiles1);
    final ClassPath cp1 = ClassPathFactory.createClassPath(mcpi1);
    globalPathRegistry_register(SOURCES,new ClassPath[]{cp1});
    assertTrue (handler.await());
    indexerFactory.indexer.setExpectedFile(new URL[]{new URL(this.srcRootWithFiles1.toURL()+"renamed/A.foo")}, new URL[]{testFo.toURL()}, new URL[0]);
    eindexerFactory.indexer.setExpectedFile(new URL[0], new URL[]{testFo.toURL()}, new URL[0]);
    final FileObject parent = testFo.getParent();
    final FileLock lock = parent.lock();
    try {
        parent.rename(lock, "renamed", null);
    } finally {
        lock.releaseLock();
    }
    assertTrue(indexerFactory.indexer.awaitDeleted(TIME));
    assertTrue(eindexerFactory.indexer.awaitDeleted());
    assertTrue(indexerFactory.indexer.awaitIndex(TIME));
    assertTrue(eindexerFactory.indexer.awaitIndex());
    assertEquals(0, eindexerFactory.indexer.getIndexCount());
    assertEquals(1, eindexerFactory.indexer.getDeletedCount());
    assertEquals(0, eindexerFactory.indexer.getDirtyCount());
    assertEquals(1, indexerFactory.indexer.getIndexCount());
    assertEquals(1, indexerFactory.indexer.getDeletedCount());
    assertEquals(0, indexerFactory.indexer.getDirtyCount());
}
 
Example 12
Project: incubator-netbeans   File: ActionPasteType.java   View Source Code Vote up 5 votes
private static boolean canBePasted(final DataObject[] dataObjects, final DataFolder targetFolder, final int operation) throws FileStateInvalidException {
    final Set<DataObject> pasteableDataObjects = new HashSet<DataObject> ();
    final FileObject folder = targetFolder.getPrimaryFile();
    
    DataObject[] folderChildren = targetFolder.getChildren();
    
    for (int j = 0; j < dataObjects.length; j++) {
        final DataObject dataObject = dataObjects[j];
        final FileObject fo = dataObject.getPrimaryFile ();
        
        if (!isAction(dataObject) || !fo.getFileSystem().isDefault()) {
            break;    
        }

        final boolean isCopyPaste = operation == LoaderTransfer.CLIPBOARD_COPY && dataObject.isCopyAllowed();
        final boolean isCutPaste = operation == LoaderTransfer.CLIPBOARD_CUT && dataObject.isMoveAllowed() && 
                !(fo.getParent() == folder);//prevents from cutting into the same folder where it was 
                        
        if (isCopyPaste || isCutPaste) {
            
            boolean isDuplicate = false;
            for( int i=0; i<folderChildren.length; i++ ) {
                if( 0 == folderChildren[i].getName().compareTo( dataObject.getName() ) ) {
                    isDuplicate = true;
                    break;
                }
            }
            if( !isDuplicate )
                pasteableDataObjects.add(dataObject);                        
        }
    }
    return (pasteableDataObjects.size() == dataObjects.length);
}
 
Example 13
Project: incubator-netbeans   File: ProjectUtilities.java   View Source Code Vote up 5 votes
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 14
Project: incubator-netbeans   File: ParsingErrorsFilter.java   View Source Code Vote up 5 votes
/**
 * Checks if the parsing errors are filtered for this file or any of its
 * parent folders.
 *
 * @param file
 * @return
 */
private static SetFilterAction getDisableFilterAction(@NonNull FileObject file) {
    FileObject source = file;
    for (; file != null && FileOwnerQuery.getOwner(file) != null; file = file.getParent()) {
        if (file.getAttribute(DISABLE_ERROR_CHECKS_KEY) != null) {
            return new SetFileFilterAction(source, file, false);
        }
    }
    return null;
}
 
Example 15
Project: incubator-netbeans   File: ProjectRunnerImplTest.java   View Source Code Vote up 5 votes
@Test public void testStartupExtender() throws Exception {
    File wd = workDir;
    FileObject fo = FileUtil.toFileObject(wd);
    FileObject java = FileUtil.createData(fo, "prj/A.java");
    FileObject prj = java.getParent();
    String prjPath = FileUtil.toFile(prj).getAbsolutePath();
    Lookup.getDefault().lookup(MockProjectFactory.class).prjDir = prj;
    checkProperties(JavaRunner.QUICK_RUN, Arrays.asList("execute.file", java, "platform.java", "J", JavaRunner.PROP_RUN_JVMARGS, Collections.singleton("-ea")),
                    Arrays.asList("classname", "A", "platform.java", "J", "classpath", prjPath + File.separatorChar, "encoding", "UTF-8", "work.dir", FileUtil.toFile(prj).getAbsolutePath(), JavaRunner.PROP_RUN_JVMARGS, "-ea -Ddir=prj -Dvm=j2se", "platform.bootcp", JavaPlatformManager.getDefault().getDefaultPlatform().getBootstrapLibraries().toString()));
    checkProperties(JavaRunner.QUICK_DEBUG, Arrays.asList("execute.file", java, "platform.java", "J", JavaRunner.PROP_RUN_JVMARGS, Collections.singleton("-ea")),
                    Arrays.asList("classname", "A", "platform.java", "J", "classpath", prjPath + File.separatorChar, "encoding", "UTF-8", "work.dir", FileUtil.toFile(prj).getAbsolutePath(), JavaRunner.PROP_RUN_JVMARGS, "-ea", "platform.bootcp", JavaPlatformManager.getDefault().getDefaultPlatform().getBootstrapLibraries().toString()));
    checkProperties(JavaRunner.QUICK_RUN, Arrays.asList(JavaRunner.PROP_WORK_DIR, prj, JavaRunner.PROP_CLASSNAME, "A", JavaRunner.PROP_EXECUTE_CLASSPATH, ClassPath.EMPTY, "platform.java", "J", JavaRunner.PROP_RUN_JVMARGS, Collections.singleton("-ea")),
                    Arrays.asList("classname", "A", "platform.java", "J", "classpath", "", "encoding", "UTF-8", "work.dir", FileUtil.toFile(prj).getAbsolutePath(), JavaRunner.PROP_APPLICATION_ARGS, "", JavaRunner.PROP_RUN_JVMARGS, "-ea -Ddir=prj -Dvm=j2se", "platform.bootcp", JavaPlatformManager.getDefault().getDefaultPlatform().getBootstrapLibraries().toString()));
}
 
Example 16
Project: incubator-netbeans   File: FileReference.java   View Source Code Vote up 5 votes
private List<FileObject> getPathMembersToBase(FileObject file) {
    if(baseFolder() == null) {
        return Collections.emptyList();
    }
    List<FileObject> members = new LinkedList<FileObject>();
    FileObject member = file;
    while((member = member.getParent()) != null && !member.equals(baseFolder())) {
        members.add(0, member);
    }
    return members;
}
 
Example 17
Project: incubator-netbeans   File: FreeformSources.java   View Source Code Vote up 5 votes
private void resetIfNeeded(final FileObject fo) {
    final FileObject parent = fo.getParent();
    if (parent != null) {
        final File parentFile = FileUtil.toFile(parent);
        if (parentFile != null) {
            if (listenOnFiles.containsKey(parentFile)) {
                return;
            }
        }
    }
    reset();
}
 
Example 18
Project: incubator-netbeans   File: StatFilesTest.java   View Source Code Vote up 5 votes
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 19
Project: incubator-netbeans   File: NavigatorControllerTest.java   View Source Code Vote up 4 votes
/**
 * Tests correct retrieving ans instantiating of NavigatorPanel instances 
 * for various scenarios.
 * 
 * @throws java.lang.Exception 
 */
@RandomlyFails
public void testObtainProviders() throws Exception {
    System.out.println("Testing NavigatorController.obtainProviders");

    InstanceContent ic = new InstanceContent();
    
    GlobalLookup4TestImpl nodesLkp = new GlobalLookup4TestImpl(ic);
    UnitTestUtils.prepareTest(new String [] { 
        "/org/netbeans/modules/navigator/resources/NavigatorControllerTestProvider.xml" }, 
        Lookups.singleton(nodesLkp)
    );
    
    URL url = NavigatorControllerTest.class.getResource("resources/sample_folder/subfolder1/subfolder2");
    assertNotNull("url not found.", url);

    FileObject fo = URLMapper.findFileObject(url);
    FileObject[] fos = fo.getChildren();
    fo = fo.getFileObject("Nic.my_extension");
    assertNotNull("fo not found.", fo);
    
    FileObject foSubFolder1 = fo.getParent().getParent();
    FileObject foSampleFolder = foSubFolder1.getParent();
    DataObject dObj = DataObject.find(fo);
    DataFolder subFolder1 = (DataFolder)DataObject.find(foSubFolder1);
    DataFolder sampleFolder = (DataFolder)DataObject.find(foSampleFolder);
    DataShadow shadow1 = DataShadow.create(subFolder1, dObj);
    DataShadow shadow2 = DataShadow.create(sampleFolder, shadow1);
    
    System.out.println("Testing DataShadow resolvement...");
    // not really valid, uses impl fact that during obtainProviders,
    // NavigatorTC parameter will not be needed.
    NavigatorController nc = NavigatorTC.getInstance().getController();
    ArrayList<Node> shadow1Node = new ArrayList<Node>(1);
    shadow1Node.add(shadow1.getNodeDelegate());
    List result = nc.obtainProviders(shadow1Node);
    assertNotNull("provider not found", result);
    assertEquals(1, result.size());
    assertTrue(result.get(0) instanceof TestJavaNavigatorPanel);
    
    ArrayList<Node> shadow2Node = new ArrayList<Node>(1);
    shadow2Node.add(shadow2.getNodeDelegate());
    result = nc.obtainProviders(shadow2Node);
    assertNotNull("provider not found", result);
    assertEquals(1, result.size());
    assertTrue(result.get(0) instanceof TestJavaNavigatorPanel);
    
    TestLookupHint lookupHint = new TestLookupHint("contentType/tester");
    ic.add(lookupHint);
    TestLookupPanelsPolicy lookupContentType = new TestLookupPanelsPolicy();
    ic.add(lookupContentType);

    System.out.println("Testing LookupContentType functionality...");
    result = nc.obtainProviders(shadow1Node);
    assertNotNull("provider not found", result);
    assertEquals("Expected 1 item, got " + result.size(), 1, result.size());
    assertTrue("Expected provider class TestContentTypeNavigatorPanel, but got " 
            + result.get(0).getClass().getName(), result.get(0) instanceof TestContentTypeNavigatorPanel);
    
}
 
Example 20
Project: incubator-netbeans   File: ResourcePathCompleter.java   View Source Code Vote up 4 votes
/**
 * Completes from the current folder
 */
private void completeFromCurrent() {
    String folderName;
    String fileMatch = valPrefix;
    
    FileObject fo = context.getSource().getFileObject();
    if (fo == null) {
        return;
    }
    String classpathDir = null;
    FileObject dir = fo.getParent();
    
    ClassPath srcPath = context.getClasspathInfo().getClassPath(ClasspathInfo.PathKind.SOURCE);
    ClassPath compilePath = context.getClasspathInfo().getClassPath(ClasspathInfo.PathKind.COMPILE);
    if (dir == null) {
        classpathDir = ""; // NOI18N
    } else {
        if (srcPath != null) {
            classpathDir = srcPath.getResourceName(dir);
        }
        if (srcPath == null && compilePath != null) {
            classpathDir = srcPath.getResourceName(dir);
        }
        if (classpathDir == null) {
            return;
        }
    }

    int slash = valPrefix.indexOf('/');
    if (slash != -1) {
        folderName = valPrefix.substring(0, slash);
        fileMatch = valPrefix.substring(slash + 1);
        classpathDir = "".equals(classpathDir) ? folderName : classpathDir + "/" + folderName;
    } else {
        folderName = null;
    }
    
    Set<String> names = new HashSet<String>();
    List<FileObject> files = new ArrayList<FileObject>();
    
    collectFromClasspath(context.getClasspathInfo().getClassPath(ClasspathInfo.PathKind.SOURCE), 
            classpathDir, files, names, fileMatch, extMatch);
    collectFromClasspath(context.getClasspathInfo().getClassPath(ClasspathInfo.PathKind.COMPILE), 
            classpathDir, files, names, fileMatch, extMatch);
    
    // exclude self:
    files.remove(fo);
    
    toCompletionItems(folderName, files);
}