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

The following are Jave code examples for showing how to use getPath() 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: HibernateUtil.java   View Source Code Vote up 6 votes
public static String getRelativeSourcePath(FileObject file, FileObject sourceRoot) {
    String relativePath = "";
    try {
        String absolutePath = file.getPath();
        String sourceRootPath = sourceRoot.getPath();
        int index = absolutePath.indexOf(sourceRootPath);
        if (index == -1) {
            // file is not under the source root - constructing relativePath
            relativePath = constructRelativePath(absolutePath, sourceRootPath);
            if (relativePath==null) {
                return "";
            }
            return relativePath;
        }
        relativePath = absolutePath.substring(index + sourceRootPath.length() + 1);
    } catch (Exception e) {
        logger.info("exception while parsing relative path");
        Exceptions.printStackTrace(e);
    }
    return relativePath;
}
 
Example 2
Project: incubator-netbeans   File: Accessor.java   View Source Code Vote up 6 votes
public static String getLocation( Task t ) {
    URL url = getURL(t);
    if( null != url ) {
        return url.toString();
    }
    FileObject fo = getFile(t);
    String location = fo.getPath();
    int line = getLine(t);
    if( line >= 0 )
        location += ":" + line;
    return location;
}
 
Example 3
Project: incubator-netbeans   File: VCSKenaiAccessor.java   View Source Code Vote up 6 votes
public static String getChatLink(FileObject fo, int line) {
    ClassPath cp = ClassPath.getClassPath(fo, ClassPath.SOURCE);
    String ret = "";       // NOI18N
    if (cp != null) {
        ret = cp.getResourceName(fo);
    } else {
        Project p = FileOwnerQuery.getOwner(fo);
        if (p != null) {
            ret = "{$" +   // NOI18N
                    ProjectUtils.getInformation(p).getName() +
                   "}/" +  // NOI18N 
                   FileUtil.getRelativePath(p.getProjectDirectory(), fo);
            } else {
            ret = fo.getPath();
        }
    }
    ret += ":" + line;      // NOI18N
    ret =  "FILE:" + ret;   // NOI18N
    return ret;
}
 
Example 4
Project: incubator-netbeans   File: JDKSetupTest.java   View Source Code Vote up 5 votes
/**
 * Tests whether JavaScript code can be executed from Ant build script.
 * FX Project build scripts rely on JavaScript to pass parameters to
 * <fx:jar> and <fx:deploy> tasks in FX SDK.
 */
public void testAntJavaScriptSupport() {
    if(!DISABLE_ALL_TESTS) {
        checkJDKVersion();
        assertTrue("JDK version could not be determined.", versionChecked);
        try {
            FileObject buildScript = createAntTestScript();
            assertTrue(buildScript.isData());
            String commandLine = (JDKOSType == OSType.WINDOWS ? "cmd /c " : "")
                    + "ant -buildfile " + buildScript.getPath();
            System.out.println("Executing " + commandLine);
            Process proc = Runtime.getRuntime().exec(commandLine);
            BufferedReader bri = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            BufferedReader bre = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
            boolean scriptExecuted = false;
            String line;
            while ((line = bri.readLine()) != null) {
                System.out.println("Log: " + line);
                if(line.contains(JS_MESSAGE)) {
                    scriptExecuted = true;
                }
            }
            bri.close();
            while ((line = bre.readLine()) != null) {
                System.out.println("Log: " + line);
                if(line.contains(JS_MESSAGE)) {
                    scriptExecuted = true;
                }
            }
            bre.close();
            proc.waitFor();
            assertTrue("JavaScript execution from Ant failed.", scriptExecuted);
            System.out.println(TEST_RESULT + "JavaScript is callable from Ant script.");
        }
        catch (Exception err) {
            fail("Exception thrown while creating or executing Ant build script; " + err.getMessage());
        }
    }
}
 
Example 5
Project: incubator-netbeans   File: BookmarkInfo.java   View Source Code Vote up 5 votes
public String getDescription(boolean fullPath, boolean useName, boolean useKey) {
    String fileDescription;
    if (this != BOOKMARKS_WINDOW) {
        FileObject fo = getFileBookmarks().getFileObject();
        if (fo != null) {
            fileDescription = fullPath ? fo.getPath() : fo.getNameExt();
        } else {
            fileDescription = NbBundle.getMessage(BookmarkInfo.class, "LBL_NonExistentFile");
        }
    } else {
        fileDescription = null;
    }
    return getDescription(fileDescription, useName, useKey, false);
}
 
Example 6
Project: incubator-netbeans   File: Util.java   View Source Code Vote up 5 votes
public static Document getDocument(FileObject f) throws IOException {
    try {
        DataObject d = DataObject.find(f);
        EditorCookie ec = d.getCookie(EditorCookie.class);
        Document doc = ec.openDocument();
        if (doc == null) {
            throw new IOException("Document cannot be opened for : " + f.getPath());
        }
        return doc;
    } catch (DataObjectNotFoundException ex) {
        throw new IOException("DataObject does not exist for : " + f.getPath());
    }
}
 
Example 7
Project: incubator-netbeans   File: MimeTypesTracker.java   View Source Code Vote up 5 votes
private void notifyRebuild(FileObject f) {
    String path = f.getPath();
    if (path.startsWith(basePath)) {
        if (synchronous) rebuild();
        else task.schedule(1000);
    }
}
 
Example 8
Project: incubator-netbeans   File: DocTreePathHandle.java   View Source Code Vote up 5 votes
private static Position createPositionRef(FileObject file, int position, Position.Bias bias) {
    try {
        PositionRefProvider prp = PositionRefProvider.get(file);
        Position positionRef = prp != null ? prp.createPosition(position, bias) : null;
        if (positionRef != null) {
            return positionRef;
        }
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
    throw new IllegalStateException("Cannot create PositionRef for file " + file.getPath() + ". CloneableEditorSupport not found");
}
 
Example 9
Project: incubator-netbeans   File: TreePathHandle.java   View Source Code Vote up 5 votes
private static Position createPositionRef(FileObject file, int position, Position.Bias bias) {
    try {
        PositionRefProvider prp = PositionRefProvider.get(file);
        Position positionRef = prp != null ? prp.createPosition(position, bias) : null;
        if (positionRef != null) {
            return positionRef;
        }
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
    throw new IllegalStateException("Cannot create PositionRef for file " + file.getPath() + ". CloneableEditorSupport not found");
}
 
Example 10
Project: incubator-netbeans   File: LibrariesStorage.java   View Source Code Vote up 5 votes
public void fileChanged(FileEvent fe) {
    FileObject definitionFile = fe.getFile();
    String fileName = definitionFile.getPath();
    final Libs data = this.initStorage(false);
    final LibraryImplementation impl = data.get(fileName);
    if (impl != null) {
        try {
            readLibrary (definitionFile, impl);
            LibraryTypeProvider provider = ltRegistry.getLibraryTypeProvider (impl.getType());
            if (provider == null) {
                LOG.warning("LibrariesStorage: Can not invoke LibraryTypeProvider.libraryCreated(), the library type provider is unknown.");  //NOI18N
            }
            try {
                //TODO: LibraryTypeProvider should be extended by libraryUpdated method
                provider.libraryCreated (impl);
                updateTimeStamp(definitionFile);
                saveTimeStamps();
            } catch (RuntimeException e) {
                String message = NbBundle.getMessage(LibrariesStorage.class,"MSG_libraryCreatedError");
                Exceptions.printStackTrace(Exceptions.attachMessage(e,message));
            }
        } catch (SAXException se) {
            //The library is broken, probably edited by user, log as warning
            logBrokenLibraryDescripor(definitionFile, se);
        } catch (ParserConfigurationException pce) {
            Exceptions.printStackTrace(pce);
        } catch (IOException ioe) {
            Exceptions.printStackTrace(ioe);
        }
    }
}
 
Example 11
Project: incubator-netbeans   File: NbWhereUsedRefactoringPlugin.java   View Source Code Vote up 5 votes
public LayerWhereUsedRefactoringElement(FileObject fo, FileObject layerFo, String attribute) {
    super(fo);
    attr = attribute;
    this.path = layerFo.getPath();
    if (attr != null) {
        Object vl = layerFo.getAttribute("literal:" + attr); //NOI18N
        if (vl instanceof String) {
            attrValue = ((String) vl).replaceFirst("^(new|method):", ""); // NOI18N
        }
    }
}
 
Example 12
Project: incubator-netbeans   File: FileStateManager.java   View Source Code Vote up 5 votes
/**
 * @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 13
Project: incubator-netbeans   File: AnalyzerImpl.java   View Source Code Vote up 5 votes
static String getFileObjectLocalizedName( FileObject fo ) {
    Object o = fo.getAttribute("SystemFileSystem.localizingBundle"); // NOI18N
    if ( o instanceof String ) {
        String bundleName = (String)o;
        try {
            ResourceBundle rb = NbBundle.getBundle(bundleName);
            String localizedName = rb.getString(fo.getPath());
            return localizedName;
        }
        catch(MissingResourceException ex ) {
            // Do nothing return file path;
        }
    }
    return fo.getPath();
}
 
Example 14
Project: incubator-netbeans   File: ValidateLayerConsistencyTest.java   View Source Code Vote up 5 votes
private boolean skipFile(FileObject fo) {
    String s = fo.getPath();

    if (s.startsWith ("Templates/") && !s.startsWith ("Templates/Services")) {
        if (s.endsWith (".shadow") || s.endsWith (".java")) {
            return true;
        }
    }

    for (String skipped : SKIPPED) {
        if (s.startsWith(skipped)) {
            return true;
        }
    }
    
    String iof = (String) fo.getAttribute("instanceOf");
    if (iof != null) {
        for (String clz : iof.split("[, ]+")) {
            try {
                Class<?> c = Lookup.getDefault().lookup(ClassLoader.class).loadClass(clz);
            } catch (ClassNotFoundException x) {
                // E.g. Services/Hidden/org-netbeans-lib-jsch-antlibrary.instance in ide cluster
                // cannot be loaded (and would just be ignored) if running without java cluster
                System.err.println("Warning: skipping " + fo.getPath() + " due to inaccessible interface " + clz);
                return true;
            }
        }
    }

    return false;
}
 
Example 15
Project: incubator-netbeans   File: HintsPanel.java   View Source Code Vote up 5 votes
private String getFileObjectLocalizedName( FileObject fo ) {
    Object o = fo.getAttribute("SystemFileSystem.localizingBundle"); // NOI18N
    if ( o instanceof String ) {
        String bundleName = (String)o;
        try {
            ResourceBundle rb = NbBundle.getBundle(bundleName);            
            String localizedName = rb.getString(fo.getPath());                
            return localizedName;
        }
        catch(MissingResourceException ex ) {
            // Do nothing return file path;
        }
    }
    return fo.getPath();
}
 
Example 16
Project: incubator-netbeans   File: VCSContext.java   View Source Code Vote up 4 votes
private static void addProjectFiles (Collection<VCSFileProxy> rootFiles,
        Map<FileObject, VCSFileProxy> rootFilesExclusions, Project project,
        Set<SourceGroup> srcGroups) {
    Sources sources = ProjectUtils.getSources(project);
    SourceGroup[] sourceGroups = sources.getSourceGroups(Sources.TYPE_GENERIC);
    srcGroups.addAll(Arrays.asList(sourceGroups));
    for (int j = 0; j < sourceGroups.length; j++) {
        SourceGroup sourceGroup = sourceGroups[j];
        FileObject srcRootFo = sourceGroup.getRootFolder();
        VCSFileProxy rootFile = VCSFileProxy.createFileProxy(srcRootFo);
        if (rootFile == null) continue;
        if (!srcRootFo.isValid()) {
            LOG.log(Level.WARNING, "addProjectFiles: invalid source root {0}", srcRootFo); //NOI18N
            continue;
        }
        rootFiles.add(rootFile);
        FileObject [] rootChildren = srcRootFo.getChildren();
        for (int i = 0; i < rootChildren.length; i++) {
            FileObject rootChildFo = rootChildren[i];
            VCSFileProxy child = VCSFileProxy.createFileProxy(rootChildFo);
            // TODO: #60516 deep scan is required here but not performed due to performace reasons
            try {
                if (!srcRootFo.isValid()) {
                    LOG.log(Level.WARNING, "addProjectFiles: source root {0} changed from valid to invalid", srcRootFo); //NOI18N
                    break;
                }
                if (rootChildFo != null && 
                    rootChildFo.isValid() && 
                    !sourceGroup.contains(rootChildFo)) 
                {
                    child = child.normalizeFile();
                    rootChildFo = child.toFileObject();
                    if(rootChildFo != null && 
                       SharabilityQuery.getSharability(rootChildFo) != Sharability.NOT_SHARABLE) 
                    {
                        rootFilesExclusions.put(rootChildFo, child);
                    }
                }
            } catch (IllegalArgumentException ex) {
                // #161904
                Logger logger = LOG;
                logger.log(Level.WARNING, "addProjectFiles: IAE");
                logger.log(Level.WARNING, "rootFO: {0}", srcRootFo);
                if (srcRootFo != sourceGroup.getRootFolder()) {
                    logger.log(Level.WARNING, "root FO has changed");
                }
                String children = "[";
                for (FileObject fo : rootChildren) {
                    children += "\"" + fo.getPath() + "\", ";
                }
                children += "]";
                logger.log(Level.WARNING, "srcRootFo.getChildren(): {0}", children);
                if(rootChildFo != null) {
                    if (!rootChildFo.isValid()) {
                        logger.log(Level.WARNING, "{0} does not exist ", rootChildFo);
                    }
                    if (!FileUtil.isParentOf(srcRootFo, rootChildFo)) {
                        logger.log(Level.WARNING, "{0} is not under {1}", new Object[]{rootChildFo, srcRootFo});
                    }
                }
                logger.log(Level.WARNING, null, ex);
            }
        }
    }
}
 
Example 17
Project: incubator-netbeans   File: NbModuleAntProjectSupportProvider.java   View Source Code Vote up 4 votes
private static String getTestType(FileObject testFile) {
    String testPath = testFile.getPath();
    if (testPath.contains(TEST_TYPE_QA_FUNCTIONAL)) return TEST_TYPE_QA_FUNCTIONAL;
    else return TEST_TYPE_UNIT;
}
 
Example 18
Project: incubator-netbeans   File: SourceFS.java   View Source Code Vote up 4 votes
public FileObject createFile(String path, SourceContent content) {
    while (path.startsWith("/")) {
        path = path.substring(1);
    }
    int pl;
    do {
        pl = path.length();
        path = path.replace("//", "/");
    } while (path.length() < pl);
    int i = path.lastIndexOf('/');
    String name = (i >= 0) ? path.substring(i + 1) : path;
    Item item = new Item(name, content);
    FileObject parent;
    synchronized (items) {
        items.put(path, item);
        parent = getExistingParent(path);
    }
    parent.refresh(true);
    FileObject fo = findResource(path);
    if (fo == null && i > 0) {
        // check refreshes of intermediate folders
        String pp = parent.getPath();
        String parentPath = path.substring(0, i);
        while (parentPath.startsWith(pp) && pp.length() < parentPath.length()) {
            i = path.indexOf('/', pp.length() + 1);
            if (i < 0) {
                break;
            }
            pp = path.substring(0, i);
            parent = findResource(pp);
            if (parent != null) {
                parent.refresh();
            } else {
                break;
            }
        }
        fo = findResource(path);
    }
    if (fo == null) {
        throw new IllegalStateException("Can not create file '"+path+"' parent = "+parent);
    }
    return fo;
}
 
Example 19
Project: incubator-netbeans   File: HtmlPaletteUtilities.java   View Source Code Vote up 4 votes
public static String getRelativePath(FileObject base, FileObject target) {
    
    final String DELIM = "/";
    final String PARENT = ".." + DELIM;
    
    String targetPath = target.getPath();
    String basePath = base.getPath();

    //paths begin either with '/' or with '<letter>:/' - ensure that in the latter case the <letter>s equal
    String baseDisc = basePath.substring(0, basePath.indexOf(DELIM));
    String targetDisc = targetPath.substring(0, targetPath.indexOf(DELIM));
    if (!baseDisc.equals(targetDisc))
        return ""; //different disc letters, thus returning an empty string to signalize this fact

    //cut a filename at the end taking last index for case of the same dir name as file name, really obscure but possible ;)
    basePath = basePath.substring(0, basePath.lastIndexOf(base.getNameExt()));
    targetPath = targetPath.substring(0, targetPath.lastIndexOf(target.getNameExt()));

    //iterate through prefix dirs until difference occurres
    StringTokenizer baseST = new StringTokenizer(basePath, DELIM);
    StringTokenizer targetST = new StringTokenizer(targetPath, DELIM);
    String baseDir = "";
    String targetDir = "";
    while (baseST.hasMoreTokens() && targetST.hasMoreTokens() && baseDir.equals(targetDir)) {
        baseDir = baseST.nextToken();
        targetDir = targetST.nextToken();
    }
    //create prefix consisting of parent dirs ("..")
    StringBuffer parentPrefix = new StringBuffer(!baseDir.equals(targetDir) ? PARENT : "");
    while (baseST.hasMoreTokens()) {
        parentPrefix.append(PARENT);
        baseST.nextToken();
    }
    //append remaining dirs with delimiter ("/")
    StringBuffer targetSB = new StringBuffer(!baseDir.equals(targetDir) ? targetDir + DELIM : "");
    while (targetST.hasMoreTokens())
        targetSB.append(targetST.nextToken() + DELIM);

    //resulting path
    targetPath = parentPrefix.toString() + targetSB.toString() + target.getNameExt();
    
    return targetPath;
}
 
Example 20
Project: incubator-netbeans   File: CssParser.java   View Source Code Vote up 4 votes
@Override
public void parse(Snapshot snapshot, Task task, SourceModificationEvent event) throws ParseException {
    cancelled.set(false);
    if (snapshot == null) {
        return;
    }
    
    this.snapshot = snapshot;
    FileObject fo = snapshot.getSource().getFileObject();
    String fileName = fo == null ? "no file" : fo.getPath(); //NOI18N
    String mimeType = topLevelSnapshotMimetype != null ? topLevelSnapshotMimetype : (fo == null ? null : fo.getMIMEType());
    LOG.log(Level.FINE, "Parsing {0} ", fileName); //NOI18N
    long start = System.currentTimeMillis();
    try {
        boolean tooLargeSnapshot = snapshot.getText().length() > MAX_SNAPSHOT_SIZE;
        
        //parse just an empty string in case of an oversize snapshot
        CharSequence source = tooLargeSnapshot ? "" : snapshot.getText();
        
        ExtCss3Lexer lexer = new ExtCss3Lexer(source, mimeType);
        TokenStream tokenstream = new CommonTokenStream(lexer);
        NbParseTreeBuilder builder = new NbParseTreeBuilder(source);
        ExtCss3Parser parser = new ExtCss3Parser(tokenstream, builder, mimeType);

        if (cancelled.get()) {
            return;
        }
        parser.styleSheet();

        if (cancelled.get()) {
            return;
        }

        AbstractParseTreeNode tree_local = builder.getTree();
        List<ProblemDescription> problems_local = new ArrayList<>();
        //add lexer issues
        problems_local.addAll(lexer.getProblems());
        //add parser issues
        problems_local.addAll(builder.getProblems());

        filterProblemsInVirtualCode(snapshot, problems_local);
        filterTemplatingProblems(snapshot, problems_local);

        if(tooLargeSnapshot) {
            //add a problem description informing the user there's something 'wrong' with the file
            problems_local.add(new ProblemDescription(0, 0, 
                    Bundle.too_large_snapshot(), ProblemDescription.Keys.PARSING.name(), ProblemDescription.Type.WARNING ));
        }
        
        if (cancelled.get()) {
            return;
        }

        this.tree = tree_local;
        this.problems = problems_local;

    } catch (RecognitionException ex) {
        throw new ParseException(String.format("Error parsing %s snapshot.", snapshot), ex); //NOI18N
    } finally {
        long end = System.currentTimeMillis();
        LOG.log(Level.FINE, "Parsing of {0} took {1} ms.", new Object[]{fileName, (end - start)}); //NOI18N
    }

}