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

The following examples show how to use org.openide.filesystems.FileObject#getNameExt() . 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: CordovaPerformer.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static String getConfigPath(Project project) {
    final FileObject siteRoot = ClientProjectUtilities.getSiteRoot(project);
    String configPath = (siteRoot==null?WWW_NB_TEMP:siteRoot.getNameExt()) + "/" + NAME_CONFIG_XML; // NOI18N
    boolean configExists = project.getProjectDirectory().getFileObject(configPath) != null;

    if (CordovaPlatform.getDefault().getVersion().getApiVersion().compareTo(new CordovaPlatform.Version.SubVersion("3.4.0")) >= 0) {
        String newConfigPath = "/" + NAME_CONFIG_XML;
        boolean newConfigPathExists = project.getProjectDirectory().getFileObject(newConfigPath) !=null;
        if (newConfigPathExists) {
            return newConfigPath;
        } else {
            if (configExists) {
                return configPath;
            } else {
                return newConfigPath;
            }
        }
    } else {
        return configPath;
    }
}
 
Example 2
Source File: ExternalReferenceDataNode.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected Node[] createNodes(Node n) {
    DataObject dobj = (DataObject) n.getLookup().lookup(DataObject.class);
    if (dobj != null) {
        FileObject fobj = dobj.getPrimaryFile();
        if (fobj.isFolder() && fobj.getNameExt().equals("nbproject") &&
                fobj.getFileObject("project.xml") != null) {
            // It is the NetBeans project folder, ignore it.
            return new Node[0];
        }
        String fname = fobj.getNameExt();
        String ext = decorator.getDocumentType();
        if (fobj.isFolder() || fname.endsWith(ext)) {
            return super.createNodes(n);
        }
    }
    return new Node[0];
}
 
Example 3
Source File: ElementFilter.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static ElementFilter forFiles(final FileObject... files) {
    return new ElementFilter() {

        @Override
        public boolean isAccepted(PhpElement element) {
            boolean retval = true;
            for (FileObject fileObject : files) {
                //if file is deleted
                if (fileObject == null) {
                    continue;
                }
                String nameExt = fileObject.getNameExt();
                String elementURL = element.getFilenameUrl();
                if ((elementURL != null && elementURL.indexOf(nameExt) < 0) || element.getFileObject() != fileObject) {
                    retval = false;
                    break;
                }
            }
            return retval;
        }
    };
}
 
Example 4
Source File: PHPCodeCompletion.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Documentation documentElement(ParserResult info, ElementHandle element, Callable<Boolean> cancel) {
    Documentation result;
    if (element instanceof ModelElement) {
        ModelElement mElem = (ModelElement) element;
        ModelElement parentElem = mElem.getInScope();
        FileObject fileObject = mElem.getFileObject();
        String fName = fileObject == null ? "?" : fileObject.getNameExt(); //NOI18N
        String tooltip;
        if (parentElem instanceof TypeScope) {
            tooltip = mElem.getPhpElementKind() + ": " + parentElem.getName() + "<b> " + mElem.getName() + " </b>" + "(" + fName + ")"; //NOI18N
        } else {
            tooltip = mElem.getPhpElementKind() + ":<b> " + mElem.getName() + " </b>" + "(" + fName + ")"; //NOI18N
        }
        result = Documentation.create(String.format("<div align=\"right\"><font size=-1>%s</font></div>", tooltip)); //NOI18N
    } else {
        result = ((element instanceof MethodElement) && ((MethodElement) element).isMagic()) ? null : DocRenderer.document(info, element);
    }
    return result;
}
 
Example 5
Source File: LayerUtilsTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testMasks() throws Exception {
        NbModuleProject project = TestBase.generateStandaloneModule(getWorkDir(), "module");
        FileSystem fs = LayerUtils.getEffectiveSystemFilesystem(project);
        Set<String> optionInstanceNames = new HashSet<String>();
        FileObject toolsMenu = fs.findResource("Menu/Tools");
        assertNotNull(toolsMenu);
        for (FileObject kid : toolsMenu.getChildren()) {
            String name = kid.getNameExt();
            if (name.contains("Options") && !name.contains("separator")) {
                optionInstanceNames.add(name);
            }
        }
        assertEquals("#63295: masks work",
                new HashSet<String>(Arrays.asList(
            "org-netbeans-modules-options-OptionsWindowAction.shadow"
            // org-netbeans-core-actions-OptionsAction.instance should be masked
        )), optionInstanceNames);
// catalogs registered by annotation
//        assertNotNull("system FS has xml/catalog", fs.findResource("Services/Hidden/CatalogProvider/org-netbeans-modules-xml-catalog-impl-XCatalogProvider.instance"));
        assertNull("but one entry hidden by apisupport/project", fs.findResource("Services/Hidden/org-netbeans-modules-xml-catalog-impl-SystemCatalogProvider.instance"));
    }
 
Example 6
Source File: JSUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static String getFileName(JSLineBreakpoint b) {
    FileObject fo = b.getFileObject();
    if (fo != null) {
        return fo.getNameExt();
    } else {
        URL url = b.getURL();
        String fileName = url.getPath();
        int i = fileName.lastIndexOf('/');
        if (i < 0) {
            i = fileName.lastIndexOf(File.separatorChar);
        }
        if (i >= 0) {
            fileName = fileName.substring(i + 1);
        }
        return fileName;
    }
}
 
Example 7
Source File: SelectFilePanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String getRelativePath(List<FileObject> folders, FileObject file) {
    for (FileObject folder : folders) {
        String relativePath = FileUtil.getRelativePath(folder, file);
        if (relativePath != null) {
            return folder.getNameExt() + "/" + relativePath; // NOI18N
        }
    }
    return null;
}
 
Example 8
Source File: GlobalVisibilityQueryImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public boolean isVisible(FileObject file) {
    String name = file.getNameExt();
    if (isIgnoreHiddenInHome() && isHidden(name) && isInHomeFolder(file)) {
        return false;
    } else {
        return isVisible(name);
    }
}
 
Example 9
Source File: CreatedModifiedFilesProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * 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 10
Source File: ProjectEar.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private IT(ProjectEar pe, FileObject f) {
    J2eeModule mods[] = pe.getModules();
    // build filter
    Set<String> filter = new HashSet<String>(mods.length);
    for (int i = 0; i < mods.length; i++) {
        FileObject modArchive = null;
        try {
            modArchive = mods[i].getArchive();
        } catch (java.io.IOException ioe) {
            Logger.getLogger(ProjectEar.class.getName()).log(Level.FINER,
                    null,ioe);
            continue;
        }
        if (modArchive != null) {
            String modName = modArchive.getNameExt();
            long modSize = modArchive.getSize();
            filter.add(modName+"."+modSize);        // NOI18N
        }
    }
    
    ArrayList<FileObject> filteredContent = new ArrayList<FileObject>(5);
    Enumeration ch = f.getChildren(true);
    while (ch.hasMoreElements()) {
        FileObject fo = (FileObject) ch.nextElement();
        String fileName = fo.getNameExt();
        long fileSize = fo.getSize();
        if (filter.contains(fileName+"."+fileSize)) {   // NOI18N
            continue;
        }
        filteredContent.add(fo);
    }
    this.root = f;
    it = filteredContent.iterator();
}
 
Example 11
Source File: TemplateIterator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String getResourceRelativePath(FileObject fromFO, FileObject toFO) {
    String relativePath = JSFUtils.getRelativePath(fromFO, toFO);
    if (relativePath.contains("resources")) {   //NOI18N
        // web resource in the resources folder (common Facelet Template)
        return "./css/" + toFO.getNameExt();    //NOI18N
    } else {
        // web resource in the subdir of the Resource Library Contract
        return relativePath;
    }
}
 
Example 12
Source File: IntroduceSuggestion.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
@Messages({
    "# {0} - Method name",
    "# {1} - Type kind",
    "# {2} - Type name",
    "# {3} - File name",
    "IntroduceHintStaticMethodDesc=Create Method \"{0}\" in {1} \"{2}\" ({3})"
})
public String getDescription() {
    String typeName = type.getName();
    FileObject fileObject = type.getFileObject();
    String fileName = fileObject == null ? UNKNOWN_FILE_NAME : fileObject.getNameExt();
    String typeKindName = getTypeKindName(type);
    return Bundle.IntroduceHintStaticMethodDesc(item.getMethod().asString(PrintAs.NameAndParamsDeclaration), typeKindName, typeName, fileName);
}
 
Example 13
Source File: IntroduceSuggestion.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
@Messages({
    "# {0} - Field name",
    "# {1} - Type kind",
    "# {2} - Type name",
    "# {3} - File name",
    "IntroduceHintFieldDesc=Create Field \"{0}\" in {1} \"{2}\" ({3})"
})
public String getDescription() {
    String typeName = type.getName();
    FileObject fileObject = type.getFileObject();
    String fileName = fileObject == null ? UNKNOWN_FILE_NAME : fileObject.getNameExt();
    String typeKindName = getTypeKindName(type);
    return Bundle.IntroduceHintFieldDesc(templ, typeKindName, typeName, fileName);
}
 
Example 14
Source File: WhereUsedBinaryElement.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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 15
Source File: BasicWizardIterator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Conditionally adds an operation to the given {@link
 * CreatedModifiedFiles}. Result of the operation, after given
 * CreatedModifiedFiles are run, is copied (into the package) icon
 * representing given <code>origIconPath</code>. If the origIconPath is
 * already inside the project's source directory nothing happens.
 *
 * @return path of the icon relative to the project's source directory
 */
public String addCreateIconOperation(CreatedModifiedFiles cmf, @NonNull FileObject originalIcon) {
    String relativeIconPath = null;
    if (!FileUtil.isParentOf(Util.getResourceDirectory(getProject()), originalIcon)) {
        String iconPath = getDefaultPackagePath(originalIcon.getNameExt(), true);
        cmf.add(cmf.createFile(iconPath, originalIcon));
        relativeIconPath = getPackageName().replace('.', '/') + '/' + originalIcon.getNameExt();
    } else {
        relativeIconPath = FileUtil.getRelativePath(Util.getResourceDirectory(getProject()), originalIcon);
    }
    return relativeIconPath;
}
 
Example 16
Source File: OperationsImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void checkParentProject(FileObject projectDir, final boolean delete, final String newName, final String oldName) throws IOException {
    final String prjLoc = projectDir.getNameExt();
    FileObject fo = projectDir.getParent();
    Project possibleParent = ProjectManager.getDefault().findProject(fo);
    if (possibleParent != null) {
        final NbMavenProjectImpl par = possibleParent.getLookup().lookup(NbMavenProjectImpl.class);
        if (par != null) {
            FileObject pomFO = par.getProjectDirectory().getFileObject("pom.xml"); //NOI18N                
            if(pomFO != null) {
                ModelOperation<POMModel> operation = new ModelOperation<POMModel>() {

                    @Override
                    public void performOperation(POMModel model) {
                        MavenProject prj = par.getOriginalMavenProject();
                        if ((prj.getModules() != null && prj.getModules().contains(prjLoc)) == delete) {
                            //delete/add module from/to parent..
                            if (delete) {
                                model.getProject().removeModule(prjLoc);
                            } else {
                                model.getProject().addModule(prjLoc);
                            }
                        }
                        if (newName != null && oldName != null) {
                            if (oldName.equals(model.getProject().getArtifactId())) {
                                // is this condition necessary.. why not just overwrite the artifactID always..
                                model.getProject().setArtifactId(newName);
                            }
                        }
                    }
                };
                Utilities.performPOMModelOperations(pomFO, Collections.singletonList(operation));
            } else {
                Logger.getLogger(OperationsImpl.class.getName()).log(Level.WARNING, "no pom found for a supposed project in {0}", par.getProjectDirectory());
            }
        }
    }
    
}
 
Example 17
Source File: HtmlPrintContainer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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 18
Source File: LexUtilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static BaseDocument getDocument(FileObject fileObject, boolean forceOpen) {
    DataObject dobj;

    try {
        dobj = DataObject.find(fileObject);

        EditorCookie ec = dobj.getLookup().lookup(EditorCookie.class);

        if (ec == null) {
            throw new IOException("Can't open " + fileObject.getNameExt());
        }

        Document document;

        if (forceOpen) {
            document = ec.openDocument();
        } else {
            document = ec.getDocument();
        }

        if (document instanceof BaseDocument) {
            return ((BaseDocument) document);
        } else {
            // Must be testsuite execution
            try {
                Class c = Class.forName("org.netbeans.modules.groovy.editor.test.GroovyTestBase");
                if (c != null) {
                    @SuppressWarnings("unchecked")
                    Method m = c.getMethod("getDocumentFor", new Class[] {FileObject.class});
                    return (BaseDocument) m.invoke(null, (Object[]) new FileObject[] {fileObject});
                }
            } catch (Exception ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    } catch (IOException ioe) {
        Exceptions.printStackTrace(ioe);
    }

    return null;
}
 
Example 19
Source File: HtmlPaletteUtilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
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
Source File: J2SEPlatformDefaultJavadocImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@NonNull
Collection<? extends URI> accept(@NonNull FileObject fo) {
    if (fo.canRead()) {
        if (fo.isFolder()) {
            if ("docs".equals(fo.getName())) {  //NOI18N
                return Collections.singleton(fo.toURI());
            }
        } else if (fo.isData()) {
            final String nameExt = fo.getNameExt();
            final String vendorPath = VENDOR_DOCS.get(nameExt);
            if (vendorPath != null) {
                if (FileUtil.isArchiveFile(fo)) {
                    try {
                        return Collections.singleton(
                            new URL (FileUtil.getArchiveRoot(fo.toURL()).toExternalForm() + vendorPath).toURI());
                    } catch (MalformedURLException | URISyntaxException e) {
                        LOG.log(
                            Level.INFO,
                            "Invalid Javadoc URI for file : {0}, reason: {1}",
                            new Object[]{
                                FileUtil.getFileDisplayName(fo),
                                e.getMessage()
                        });
                        //pass
                    }
                }
            } else 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();
}