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

The following are Jave code examples for showing how to use getNameExt() 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.
Example 1
Project: incubator-netbeans   File: ToDoCustomizer.java   Source Code and License Vote up 6 votes
private Collection<String> readMimeTypes() {
    List<String> mimeTypes = new ArrayList<String>();
    FileObject[] children = FileUtil.getConfigFile("Loaders").getChildren();  //NOI18N
    for (int i = 0; i < children.length; i++) {
        FileObject child = children[i];
        String mime1 = child.getNameExt();
        FileObject[] subchildren = child.getChildren();
        for (int j = 0; j < subchildren.length; j++) {
            FileObject subchild = subchildren[j];
            FileObject factoriesFO = subchild.getFileObject("Factories");  //NOI18N
            if (factoriesFO != null && factoriesFO.getChildren().length > 0) {
                // add only MIME types where some loader exists
                mimeTypes.add(mime1 + "/" + subchild.getNameExt()); //NOI18N
            }
        }
    }
    mimeTypes.remove("content/unknown"); //NOI18N
    return mimeTypes;
}
 
Example 2
Project: incubator-netbeans   File: ApisupportAntUtils.java   Source Code and License Vote up 6 votes
/**
 * Copies given JAR file into <tt>release/modules/ext</tt> folder under <tt>projectDir</tt>.
 * <tt>release/modules/ext</tt> will be created if necessary.
 *
 * @param projectDir Project folder
 * @param jar JAR file to be copied
 * @return If JAR copied successfully, returns string array <tt>{&lt;runtime-relative path&gt, &lt;binary origin path&gt;}</tt>,
 * otherwise <tt>null</tt>.
 * @throws IOException When <tt>release/modules/ext</tt> folder cannot be created.
 */
public static String[] copyClassPathExtensionJar(File projectDir, File jar) throws IOException {
    String[] ret = null;

    File releaseDir = new File(projectDir, CPEXT_BINARY_PATH); //NOI18N
    if (! releaseDir.isDirectory() && !releaseDir.mkdirs()) {
        throw new IOException("cannot create release directory '" + releaseDir + "'.");    // NOI18N
    }
    
    FileObject relDirFo = FileUtil.toFileObject(releaseDir);
    FileObject orig = FileUtil.toFileObject(FileUtil.normalizeFile(jar));
    if (orig != null) {
        FileObject existing = relDirFo.getFileObject(orig.getName(), orig.getExt());
        if (existing != null)
            existing.delete();
        FileUtil.copyFile(orig, relDirFo, orig.getName());
        ret = new String[2];
        ret[0] = CPEXT_RUNTIME_RELATIVE_PATH + orig.getNameExt();    // NOI18N
        ret[1] = CPEXT_BINARY_PATH + orig.getNameExt(); // NOI18N
    }
    return ret;
}
 
Example 3
Project: incubator-netbeans   File: FolderNameTabDecorator.java   Source Code and License 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 4
Project: incubator-netbeans   File: CurrentFileScopeProvider.java   Source Code and License Vote up 6 votes
@Override
public boolean initialize(Lookup context, AtomicBoolean cancel) {
    FileObject file = context.lookup(FileObject.class);
    if (file == null || file.isFolder()) {
        return false;
    }

    DataObject currentFileDo = null;
    try {
        currentFileDo = DataObject.find(file);
    } catch (DataObjectNotFoundException ex) {
    } // Not important, only for Icon.
    icon = currentFileDo != null ? new ImageIcon(currentFileDo.getNodeDelegate().getIcon(BeanInfo.ICON_COLOR_16x16)) : null;
    detail = file.getNameExt();
    scope = Scope.create(null, null, Arrays.asList(file));

    return true;
}
 
Example 5
Project: incubator-netbeans   File: JavaFxDefaultJavadocImpl.java   Source Code and License Vote up 6 votes
@NonNull
Collection<? extends URI> accept(@NonNull final FileObject fo) {
    if (fo.canRead() && fo.isData()) {
        final String nameExt = fo.getNameExt();
        if (DOCS_FILE_PATTERN.matcher(nameExt).matches() && JAVAFX_FILE_PATTERN.matcher(nameExt).matches()) {
            final FileObject root = FileUtil.getArchiveRoot(fo);
            if (root != null) {
                final List<URI> roots = new ArrayList<>(DOCS_PATHS.size());
                for (String path : DOCS_PATHS) {
                    final FileObject docRoot = root.getFileObject(path);
                    if (docRoot != null) {
                        roots.add(docRoot.toURI());
                    }
                }
                return Collections.unmodifiableCollection(roots);
            }
        }
    }
    return Collections.emptySet();
}
 
Example 6
Project: incubator-netbeans   File: MavenSourcesImpl.java   Source Code and License Vote up 6 votes
private boolean checkOtherGroup(File rootFile, Set<File> resourceRoots, boolean test) {
    FileObject root = FileUtil.toFileObject(rootFile);
    if (root != null && !root.isFolder()) {
        root = null;
    }
    Map<File, OtherGroup> map = test ? otherTestGroups : otherMainGroups;
    OtherGroup grp = map.get(rootFile);
    boolean isResourceNow = resourceRoots.contains(rootFile);
    boolean wasResourceBefore = grp != null && grp.getResource() != null;
    if ((root == null && grp != null) ||  (root != null && grp != null && wasResourceBefore && !isResourceNow)) {
        map.remove(rootFile);
        return true;
    }
    if (root == null) {
        return false;
    }
    boolean changed = false;
    if (grp == null || !grp.getRootFolder().isValid() || !grp.getRootFolder().equals(root) ||
            isResourceNow != wasResourceBefore) {
        grp = new OtherGroup(project(), root, "Resource" + (test ? "Test":"Main") + root.getNameExt(), root.getName(), test); //NOI18N
        map.put(rootFile, grp);
        changed = true;
    }
    return changed;
}
 
Example 7
Project: incubator-netbeans   File: EditorLocatorFactory.java   Source Code and License Vote up 6 votes
private void addFiles(
    FileObject mimeFolder,
    String profileId,
    boolean fullScan,
    String [] filePaths,
    Map<String, List<Object []>> files,
    boolean moduleFiles
) {
    if (profileId == null) {
        FileObject [] profileHomes = mimeFolder.getChildren();
        for(FileObject f : profileHomes) {
            if (!f.isFolder()) {
                continue;
            }
            
            String id = f.getNameExt();
            addFiles(f, filePaths, fullScan, files, id, f, moduleFiles); //NOI18N
        }
    } else {
        FileObject profileHome = mimeFolder.getFileObject(profileId);
        if (profileHome != null && profileHome.isFolder()) {
            addFiles(profileHome, filePaths, fullScan, files, profileId, profileHome, moduleFiles);
        }
    }
}
 
Example 8
Project: incubator-netbeans   File: WhereUsedBinaryElement.java   Source Code and License Vote up 5 votes
private WhereUsedBinaryElement(FileObject fo, boolean inTest, boolean inPlatform) {
    final String name = fo.getNameExt(); //NOI18N
    this.htmlText = "<b>" + name + "</b>"; //NOI18N
    this.elementText = name;
    this.fromTest = inTest;
    this.fromPlatform = inPlatform;
    this.fo = fo;
}
 
Example 9
Project: incubator-netbeans   File: HtmlPrintContainer.java   Source Code and License Vote up 5 votes
final void begin (FileObject fo, Font font, Color fgColor, Color bgColor, Color hfgColor, Color hbgColor, MimePath mimePath, String charset) {
    styles = new Styles ();
    buffer = new StringBuffer();
    fileName = FileUtil.getFileDisplayName(fo);
    shortFileName = fo.getNameExt();
    boolHolder = new boolean [1];
    this.defaultForegroundColor = fgColor;
    this.defaultBackgroundColor = bgColor;
    this.defaultFont = font;
    this.headerForegroundColor = hfgColor;
    this.headerBackgroundColor = hbgColor;
    this.syntaxColoring = ColoringMap.get(mimePath.getPath()).getMap();
    this.charset = charset;
}
 
Example 10
Project: incubator-netbeans   File: KitsTrackerImpl.java   Source Code and License Vote up 5 votes
private static boolean isValidType(FileObject typeFile) {
    if (!typeFile.isFolder()) {
        return false;
    }

    String typeName = typeFile.getNameExt();
    return MimePath.validate(typeName, null);
}
 
Example 11
Project: incubator-netbeans   File: CreatedModifiedFilesProvider.java   Source Code and License Vote up 5 votes
/**
 * returns archive name or temporarily null cause there is no zip support
 * for file protocol
 */
private static String addArchiveToCopy(CreatedModifiedFiles fileSupport, NewLibraryDescriptor.DataModel data, URL originalURL, String pathPrefix) {
    String retval = null;

    URL archivURL = FileUtil.getArchiveFile(originalURL);
    if (archivURL != null && FileUtil.isArchiveFile(archivURL)) {
        FileObject archiv = URLMapper.findFileObject(archivURL);
        if (archiv == null) {
            // #129617: broken library entry, just skip it.
            return null;
        }
        retval = archiv.getNameExt();
        fileSupport.add(fileSupport.createFile(pathPrefix + retval, archiv));
    } else {
        if ("file".equals(originalURL.getProtocol())) {//NOI18N
            FileObject folderToZip;
            folderToZip = URLMapper.findFileObject(originalURL);
            if (folderToZip != null) {
                retval = data.getLibraryName() + "-" + folderToZip.getName() + ".zip"; // NOI18N
                pathPrefix += retval;
                fileSupport.add(new ZipAndCopyOperation(data.getProject(),
                        folderToZip, pathPrefix));
            }
        }
    }
    return retval;
}
 
Example 12
Project: incubator-netbeans   File: FileElement.java   Source Code and License Vote up 5 votes
public boolean match(FileObject fo) {
    String nameAndExt = fo.getNameExt();
    if (ignoreCase) {
        nameAndExt = nameAndExt.toLowerCase();
    }
    if (substring) {
        return nameAndExt.contains(name);
    } else {
        return nameAndExt.equals(name);
    }
}
 
Example 13
Project: incubator-netbeans   File: CssCompletion.java   Source Code and License Vote up 5 votes
@Override
public CssCompletionItem createFileItem(FileObject file, int anchor) {
    String name = file.getNameExt();
    Color color = file.isFolder() ? Color.BLUE : null;
    ImageIcon icon = FileReferenceCompletion.getIcon(file);

    return CssCompletionItem.createFileCompletionItem(new CssElement(file, name), name, anchor, color, icon, addQuotes, addSemicolon);
}
 
Example 14
Project: incubator-netbeans   File: LineBreakpoint.java   Source Code and License Vote up 5 votes
/**
 * Returns a string representation of this object.
 *
 * @return  a string representation of the object
 */
@Override
public String toString () {
    String fileName = null;
    try {
        FileObject fo = URLMapper.findFileObject(new URL(url));
        if (fo != null) {
            fileName = fo.getNameExt();
        }
    } catch (MalformedURLException ex) {}
    if (fileName == null) {
        fileName = url;
    }
    return "LineBreakpoint " + fileName + " : " + lineNumber;
}
 
Example 15
Project: incubator-netbeans   File: ProjectFilesNode.java   Source Code and License Vote up 5 votes
@Override protected boolean createKeys(List<FileObject> keys) {
    FileObject d = project.getProjectDirectory();
    keys.add(d.getFileObject("pom.xml")); // NOI18N
    keys.add(d.getFileObject(M2Configuration.FILENAME));
    for (FileObject kid : d.getChildren()) {
        String n = kid.getNameExt();
        if (n.startsWith(M2Configuration.FILENAME_PREFIX) && n.endsWith(M2Configuration.FILENAME_SUFFIX)) {
            keys.add(kid);
        }
    }
    keys.add(d.getFileObject(M2AuxilaryConfigImpl.CONFIG_FILE_NAME));
    keys.add(FileUtil.toFileObject(MavenCli.DEFAULT_USER_SETTINGS_FILE));
    keys.removeAll(Collections.singleton(null));
    return true;
}
 
Example 16
Project: incubator-netbeans   File: LanguageRegistry.java   Source Code and License Vote up 5 votes
private static boolean isValidType(FileObject typeFile) {
    if (!typeFile.isFolder()) {
        return false;
    }

    String typeName = typeFile.getNameExt();
    return MimePath.validate(typeName, null);
}
 
Example 17
Project: incubator-netbeans   File: CssWhereUsedQueryPlugin.java   Source Code and License Vote up 5 votes
private void refactorFile(FileObject base, RefactoringElementsBag elements) {
    CssProjectSupport sup = CssProjectSupport.findFor(base);
    if (sup == null) {
        return;
    }

    CssIndex index = sup.getIndex();
    DependenciesGraph deps = index.getDependencies(base);

    //find only files directly importing the base file
    String baseFileName = base.getNameExt();
    for (org.netbeans.modules.web.common.api.DependenciesGraph.Node referingNode : deps.getSourceNode().getReferingNodes()) {
        try {
            FileObject file = referingNode.getFile();
            CssFileModel model = CssFileModel.create(Source.create(file));
            Collection<Entry> imports = model.getImports();
            //find the import of the base file
            for (Entry e : imports) {
                if (e.isValidInSourceDocument() && e.getName().indexOf(baseFileName) != -1) {
                    //found
                    WhereUsedElement elem = WhereUsedElement.create(file, e, ElementKind.FILE);
                    elements.add(refactoring, elem);
                }
            }
        } catch (ParseException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
}
 
Example 18
Project: incubator-netbeans   File: ResourcePathCompleter.java   Source Code and License Vote up 5 votes
private Collection<FileObject> collectFromClasspath(ClassPath cp, String parentDir, 
        Collection<FileObject> result,
        Set<String> names, 
        String filesMatch,
        String extMatch) {
    if (cp == null) {
        return result;
    }
    if (extMatch != null) {
        extMatch = extMatch.toLowerCase();
    }
    if (filesMatch != null) {
        filesMatch = filesMatch.toLowerCase();
    }
    for (ClassPath.Entry en : cp.entries()) {
        FileObject root = en.getRoot();
        FileObject dir = root.getFileObject(parentDir);
        if (dir == null) {
            continue;
        }
        for (FileObject f : dir.getChildren()) {
            if (filesMatch != null && !filesMatch.isEmpty() && 
                !f.getNameExt().toLowerCase().startsWith(filesMatch)) {
                continue;
            }
            if (f.isFolder() || extMatch == null || extMatch.equals(f.getExt().toLowerCase())) {
                String k = f.getNameExt();
                if (names.add(k)) {
                    result.add(f);
                }
            }
        }
    }
    return result;
}
 
Example 19
Project: incubator-netbeans   File: DefaultOpenFileImpl.java   Source Code and License Vote up 4 votes
private void openInEDT(FileObject fileObject, DataObject dataObject, int line) {
    Class<? extends Node.Cookie> cookieClass;        
    Node.Cookie cookie;
    
    if ((line != -1)
        && (   ((cookie = dataObject.getCookie(cookieClass = EditorCookie.Observable.class)) != null)
            || ((cookie = dataObject.getCookie(cookieClass = EditorCookie.class)) != null) )) {
        boolean ret = openByCookie(cookie, cookieClass, line);
        if (!ret) {
            showNotPlainFileWarning(fileObject);
        }
        return;
    } 
                        
    /* try to open the object using the default action */
    Node dataNode = dataObject.getNodeDelegate();        
    Action action = dataNode.getPreferredAction();
    if ((action != null)
            && !(action instanceof FileSystemAction)
            && !(action instanceof ToolsAction)) {
        if (log.isLoggable(FINEST)) {
            log.log(FINEST, " - using preferred action "            //NOI18N
                    + "(\"{0}\" - {1}) for opening the file",       //NOI18N
                    new Object[]{action.getValue(Action.NAME),
                        action.getClass().getName()});
        }

        if (action instanceof ContextAwareAction) {
            action = ((ContextAwareAction) action)
              .createContextAwareInstance(dataNode.getLookup());
            if (log.isLoggable(FINEST)) {
                log.finest("    - it is a ContextAwareAction");     //NOI18N
                log.log(FINEST, "    - using a context-aware "      //NOI18N
                        + "instance instead (\"{0}\" - {1})",       //NOI18N
                        new Object[]{action.getValue(Action.NAME),
                            action.getClass().getName()});
            }
        }

        log.finest("   - will call action.actionPerformed(...)");   //NOI18N
        final Action a = action;
        final Node n = dataNode;
        WindowManager.getDefault().invokeWhenUIReady(new Runnable() {

            @Override
            public void run() {
                a.actionPerformed(new ActionEvent(n, 0, ""));
            }
        });
        return;
    }             
    String fileName = fileObject.getNameExt();
    /* Try to grab an editor/open/edit/view cookie and open the object: */
    StatusDisplayer.getDefault().setStatusText(
            NbBundle.getMessage(DefaultOpenFileImpl.class,
                                "MSG_opening",                      //NOI18N
                                fileName));
    boolean success = openDataObjectByCookie(dataObject, line);
    if (success) {
        return;
    }        
    if (fileObject.isFolder() || FileUtil.isArchiveFile(fileObject)) {
        // select it in explorer:
        final Node node = dataObject.getNodeDelegate();
        if (node != null) {
            WindowManager.getDefault().invokeWhenUIReady(new Runnable() {

                @Override
                public void run() {
                    NodeOperation.getDefault().explore(node);
                }
            });
            return;
        }
    }
    showNotPlainFileWarning(fileObject);
}
 
Example 20
Project: incubator-netbeans   File: HtmlPaletteUtilities.java   Source Code and License 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;
}