Java Code Examples for org.openide.filesystems.FileUtil#normalizeFile()

The following examples show how to use org.openide.filesystems.FileUtil#normalizeFile() . 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: LocalServerController.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Validate given local server instance, its source root.
 * @param localServer local server to validate.
 * @param type the type for error messages.
 * @param allowNonEmpty <code>true</code> if the folder can exist and can be non empty.
 * @param allowInRoot  <code>true</code> if the folder can exist and can be a root directory "/" (on *NIX only).
 * @return error message or <code>null</code> if source root is ok.
 * @see Utils#validateProjectDirectory(java.lang.String, java.lang.String, boolean)
 */
public static String validateLocalServer(final LocalServer localServer, String type, boolean allowNonEmpty,
        boolean allowInRoot) {
    if (!localServer.isEditable()) {
        return null;
    }
    String err = null;
    String sourcesLocation = localServer.getSrcRoot();
    File sources = FileUtil.normalizeFile(new File(sourcesLocation));
    if (sourcesLocation.trim().length() == 0
            || !Utils.isValidFileName(sources)) {
        err = NbBundle.getMessage(LocalServerController.class, "MSG_Illegal" + type + "Name");
    } else {
        err = Utils.validateProjectDirectory(sourcesLocation, type, allowNonEmpty, allowInRoot);
    }
    return err;
}
 
Example 2
Source File: MuxClassPathImplementationTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testPropagatesFlags() throws IOException {
    final File wd = FileUtil.normalizeFile(getWorkDir());
    final URL cp1r1 = FileUtil.urlForArchiveOrDir(new File(wd, "cp1_root1"));   //NOI18N
    final URL cp2r1 = FileUtil.urlForArchiveOrDir(new File(wd, "cp2_root1"));   //NOI18N
    final MutableClassPathImpl cpImpl1 = new MutableClassPathImpl(cp1r1);
    final MutableClassPathImpl cpImpl2 = new MutableClassPathImpl(cp2r1)
            .add(ClassPath.Flag.INCOMPLETE);
    final SelectorImpl selector = new SelectorImpl(
                ClassPathFactory.createClassPath(cpImpl1),
                ClassPathFactory.createClassPath(cpImpl2));
    final ClassPath cp = ClassPathSupport.createMultiplexClassPath(selector);
    assertEquals(0, cp.getFlags().size());
    selector.select(1);
    assertEquals(1, cp.getFlags().size());
    selector.select(0);
    assertEquals(0, cp.getFlags().size());
    cpImpl1.add(ClassPath.Flag.INCOMPLETE);
    assertEquals(1, cp.getFlags().size());
    cpImpl1.remove(ClassPath.Flag.INCOMPLETE);
    assertEquals(0, cp.getFlags().size());
    selector.select(1);
    assertEquals(1, cp.getFlags().size());
}
 
Example 3
Source File: StreamSource.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private File createReaderSource(Reader r) throws IOException {
    File tmp = null;
    tmp = FileUtil.normalizeFile(File.createTempFile("sss", "tmp"));
    tmp.deleteOnExit();
    tmp.createNewFile();
    InputStream in = null;
    OutputStream out = null;
    try {
        if (encoding == null) {
            in = new ReaderInputStream(r);
        } else {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            copyStreamsCloseAll(new OutputStreamWriter(baos, encoding), r);
            in = new ByteArrayInputStream(baos.toByteArray());
        }
        org.openide.filesystems.FileUtil.copy(in, out = new FileOutputStream(tmp));
    } finally {
        if (in != null) in.close();
        if (out != null) out.close();
    }
    return tmp;
}
 
Example 4
Source File: J2SESourcesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected @Override void setUp() throws Exception {
        super.setUp();
        MockLookup.setLayersAndInstances(
            new org.netbeans.modules.projectapi.SimpleFileOwnerQueryImplementation()
        );
        scratch = TestUtil.makeScratchDir(this);
        projdir = scratch.createFolder("proj");
        J2SEProjectGenerator.setDefaultSourceLevel(new SpecificationVersion ("1.6"));   //NOI18N
        helper = J2SEProjectGenerator.createProject(FileUtil.toFile(projdir),"proj",null,null,null, false); //NOI18N
        J2SEProjectGenerator.setDefaultSourceLevel(null);
        sources = getFileObject(projdir, "src");
        build = getFileObject (scratch, "build");
        classes = getFileObject(build,"classes");
        File f = FileUtil.normalizeFile (FileUtil.toFile(build));
        String path = f.getAbsolutePath ();
//#47657: SourcesHelper.remarkExternalRoots () does not work on deleted folders
// To reproduce it uncomment following line
//        build.delete();
        EditableProperties props = helper.getProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH);
        props.setProperty(ProjectProperties.BUILD_DIR, path);
        helper.putProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH, props);
        pm = ProjectManager.getDefault();
        project = pm.findProject(projdir);
        assertTrue("Invalid project type", project instanceof J2SEProject);
    }
 
Example 5
Source File: BaseFileObjectTestHid.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
public void testFileUtilFromFile () throws Exception {        
    assertNotNull(root);
    
    File f = FileUtil.normalizeFile(getWorkDir());
    IgnoreDirFileSystem ifs = new IgnoreDirFileSystem();
    ifs.setRootDirectory(f);
    
    Repository.getDefault().addFileSystem(ifs);
    Repository.getDefault().addFileSystem(testedFS);
    
    FileObject[] fos = FileUtil.fromFile(f);
    assertTrue(fos.length > 0);
    assertEquals(fos[0].getFileSystem(), testedFS );
    
}
 
Example 6
Source File: ConfigureProjectPanel.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void storeSettings(WizardDescriptor settings) {
    // project - we have to save it as it is because one can navigate back and forward
    //  => the project folder equals to sources
    File projectDir = getProjectFolderFile();
    if (projectDir != null) {
        projectDir = FileUtil.normalizeFile(projectDir);
    }
    settings.putProperty(IS_PROJECT_DIR_USED, configureProjectPanelVisual.isProjectFolderUsed());
    settings.putProperty(PROJECT_DIR, projectDir);
    settings.putProperty(PROJECT_NAME, configureProjectPanelVisual.getProjectName());

    // sources
    settings.putProperty(SOURCES_FOLDER, configureProjectPanelVisual.getSourcesLocation());
    settings.putProperty(LOCAL_SERVERS, configureProjectPanelVisual.getLocalServerModel());

    // php version
    settings.putProperty(PHP_VERSION, configureProjectPanelVisual.getPhpVersion());

    // encoding
    settings.putProperty(ENCODING, configureProjectPanelVisual.getEncoding());
}
 
Example 7
Source File: FileBasedURLMapper.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public final FileObject[] getFileObjects(final URL url) {
    if (!"file".equals(url.getProtocol())) {  //NOI18N
        return null;
    }
    // return null for UNC root
    if(url.getPath().equals("//") || url.getPath().equals("////")) {  //NOI18N
        return null;
    }
    //TODO: review and simplify         
    FileObject retVal = null;
    File file;
    try {
        file = FileUtil.normalizeFile(BaseUtilities.toFile(url.toURI()));
    } catch (URISyntaxException e) {
        LOG.log(Level.INFO, "URL=" + url, e); // NOI18N
        return null;
    } catch (IllegalArgumentException iax) {
        LOG.log(Level.INFO, "URL=" + url, iax); // NOI18N
        return null;
    }
    
    retVal = FileBasedFileSystem.getFileObject(file, FileObjectFactory.Caller.ToFileObject);
    return new FileObject[]{retVal};
}
 
Example 8
Source File: BasicProjectWizardIterator.java    From nb-springboot with Apache License 2.0 5 votes vote down vote up
@Override
public Set<FileObject> instantiate(ProgressHandle handle) throws IOException {
    handle.start(4);
    Set<FileObject> resultSet = new LinkedHashSet<>();
    File fDir = FileUtil.normalizeFile((File) wiz.getProperty("projdir"));
    fDir.mkdirs();
    handle.progress(1);
    FileObject foDir = FileUtil.toFileObject(fDir);
    FileObject template = URLMapper.findFileObject(getClass().getResource("BasicSpringbootProject.zip"));
    unZipFile(template.getInputStream(), foDir);
    handle.progress(2);
    // create nbactions.xml file
    createNbActions(foDir);
    // clear non project cache
    ProjectManager.getDefault().clearNonProjectCache();
    // Always open top dir as a project:
    resultSet.add(foDir);
    // open pom.xml file
    final FileObject foPom = foDir.getFileObject("pom.xml");
    if (foPom != null) {
        resultSet.add(foPom);
    }
    handle.progress(3);
    // trigger download of dependencies
    Project prj = ProjectManager.getDefault().findProject(foDir);
    if (prj != null) {
        final NbMavenProject mvn = prj.getLookup().lookup(NbMavenProject.class);
        if (mvn != null) {
            mvn.downloadDependencyAndJavadocSource(false);
        }
    }
    // remember folder for creation of new projects
    File parent = fDir.getParentFile();
    if (parent != null && parent.exists()) {
        ProjectChooser.setProjectsFolder(parent);
    }
    handle.finish();
    return resultSet;
}
 
Example 9
Source File: PanelSourceFolders.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void jButtonLibrariesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLibrariesActionPerformed
    JFileChooser chooser = new JFileChooser();
    FileUtil.preventFileChooserSymlinkTraversal(chooser, null);
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    if (jTextFieldLibraries.getText().length() > 0 && getLibraries().exists()) {
        chooser.setSelectedFile(getLibraries());
    } else {
        chooser.setCurrentDirectory((File) wizardDescriptor.getProperty(ProjectLocationWizardPanel.PROJECT_DIR));
    }
    if ( JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(this)) {
        File configFilesDir = FileUtil.normalizeFile(chooser.getSelectedFile());
        jTextFieldLibraries.setText(configFilesDir.getAbsolutePath());
    }
}
 
Example 10
Source File: PhpProjectGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * @param copySourcesTarget target for source copying, can be <code>null</code>
 */
public ProjectProperties setCopySourcesTarget(File copySourcesTarget) {
    if (copySourcesTarget != null) {
        copySourcesTarget = FileUtil.normalizeFile(copySourcesTarget);
    }
    this.copySourcesTarget = copySourcesTarget;
    return this;
}
 
Example 11
Source File: PhpProjectSupport.java    From nb-ci-plugin with GNU General Public License v2.0 5 votes vote down vote up
private static String createForeignFileReference(final Project project, final String path) {
    File projectDirectory = FileUtil.toFile(project.getProjectDirectory());
    File normalizedFile = FileUtil.normalizeFile(PropertyUtils.resolveFile(projectDirectory, path));

    String property = normalizedFile.getName();

    if (normalizedFile.isDirectory() && normalizedFile.getParentFile() != null) {
        property = normalizedFile.getParentFile().getName() + "-" + property;
    }

    return REFERENCE_ID_PREFIX + property;
}
 
Example 12
Source File: NBProjectGeneratorsWizardIterator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public Set/*<FileObject>*/ instantiate(/*ProgressHandle handle*/) throws IOException {
    Set<FileObject> resultSet = new LinkedHashSet<FileObject>();
    File dirF = FileUtil.normalizeFile((File) wiz.getProperty("projdir"));
    dirF.mkdirs();

    FileObject template = Templates.getTemplate(wiz);
    FileObject dir = FileUtil.toFileObject(dirF);
    unZipFile(template.getInputStream(), dir);

    // Always open top dir as a project:
    resultSet.add(dir);
    // Look for nested projects to open as well:
    Enumeration<? extends FileObject> e = dir.getFolders(true);
    while (e.hasMoreElements()) {
        FileObject subfolder = e.nextElement();
        if (ProjectManager.getDefault().isProject(subfolder)) {
            resultSet.add(subfolder);
        }
    }

    File parent = dirF.getParentFile();
    if (parent != null && parent.exists()) {
        ProjectChooser.setProjectsFolder(parent);
    }

    return resultSet;
}
 
Example 13
Source File: SampleVisualPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String validateProjectLocation() {
    File projectLocation = FileUtil.normalizeFile(new File(getProjectLocation()).getAbsoluteFile());
    if (!projectLocation.isDirectory()) {
        return NbBundle.getMessage(SampleVisualPanel.class, "ERR_LocationInvalid"); // NOI18N
    }
    final File destFolder = getProjectDirectory();
    try {
        destFolder.getCanonicalPath();
    } catch (IOException e) {
        return NbBundle.getMessage(SampleVisualPanel.class, "ERR_LocationNotWritable"); // NOI18N
    }

    File projLoc = destFolder;
    while (projLoc != null && !projLoc.exists()) {
        projLoc = projLoc.getParentFile();
    }
    if (projLoc == null || !projLoc.canWrite()) {
        return NbBundle.getMessage(SampleVisualPanel.class, "ERR_LocationNotWritable"); // NOI18N
    }

    if (FileUtil.toFileObject(projLoc) == null) {
        return NbBundle.getMessage(SampleVisualPanel.class, "ERR_LocationInvalid"); // NOI18N
    }

    File[] kids = destFolder.listFiles();
    if (destFolder.exists() && kids != null && kids.length > 0) {
        return NbBundle.getMessage(SampleVisualPanel.class, "ERR_LocationNotEmpty"); // NOI18N
    }
    return null;
}
 
Example 14
Source File: NameIconLocationPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void iconButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_iconButtonActionPerformed
    JFileChooser chooser = WizardUtils.getIconFileChooser(icon.getText());
    int ret = chooser.showDialog(this, getMessage("LBL_Select"));
    if (ret == JFileChooser.APPROVE_OPTION) {
        File iconFile =  FileUtil.normalizeFile(chooser.getSelectedFile());
            icon.setText(iconFile.getAbsolutePath());
            Set<File> allFiles = getPossibleIcons(getIconPath());
            if (!allFiles.remove(iconFile)) {
                return; // #186459: user somehow selected a directory
            }
            boolean isIconSmall = WizardUtils.isValidIcon(iconFile, 16, 16);
 
            File secondIcon = null;
            boolean isSecondIconSmall = false;
            for (Iterator<File> it = allFiles.iterator(); it.hasNext() && !isSecondIconSmall;) {
                File f = it.next();
                isSecondIconSmall = (isIconSmall) ? 
                    WizardUtils.isValidIcon(f, 24, 24) : WizardUtils.isValidIcon(f, 16, 16);
                if (isSecondIconSmall) {
                    secondIcon = f;
                    break;
                }
            }
            
            if (secondIcon != null) {
                smallIconPath = (isIconSmall) ? iconFile : secondIcon;
                largeIconPath = (isIconSmall) ? secondIcon : iconFile;
            } else {
                smallIconPath = iconFile;
                largeIconPath = null;
            }
            
        updateData();
    }
}
 
Example 15
Source File: Hk2PluginProperties.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param file
 * @return
 * @throws java.net.MalformedURLException
 */
public static URL fileToUrl(File file) throws MalformedURLException {
    File nfile = FileUtil.normalizeFile(file);
    URL url = nfile.toURI().toURL();
    if (FileUtil.isArchiveFile(url)) {
        url = FileUtil.getArchiveRoot(url);
    }
    return url;
}
 
Example 16
Source File: BuildConfig.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private synchronized void loadGlobalPluginsDirDefault() {
    if (GrailsPlatform.Version.VERSION_1_1.compareTo(GrailsProjectConfig.forProject(project).getGrailsPlatform().getVersion()) <= 0) {
        GrailsProjectConfig config = GrailsProjectConfig.forProject(project);
        File cached = config.getGlobalPluginsDir();
        if (cached != null && isBuildConfigPresent()) {
            globalPluginsDir = FileUtil.normalizeFile(cached);
        } else {
            globalPluginsDir = getGlobalPluginsDirDefault11();
        }
    } else {
        globalPluginsDir = getGlobalPluginsDir10();
    }
}
 
Example 17
Source File: DiffSidebarManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
synchronized File getMainTempDir () {
    if (tempDir == null) {
        File tmpDir = new File(System.getProperty("java.io.tmpdir"));   // NOI18N
        for (;;) {
            File dir = new File(tmpDir, "vcs-" + Long.toString(System.currentTimeMillis())); // NOI18N
            if (!dir.exists() && dir.mkdirs()) {
                tempDir = FileUtil.normalizeFile(dir);
                tempDir.deleteOnExit();
                break;
            }
        }
    }
    return tempDir;
}
 
Example 18
Source File: CustomizerSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void addPathElement () {
    JFileChooser chooser = new JFileChooser();
    FileUtil.preventFileChooserSymlinkTraversal(chooser, null);
    chooser.setMultiSelectionEnabled (true);
    String title = null;
    String message = null;
    String approveButtonName = null;
    String approveButtonNameMne = null;
    if (SOURCES.equals(this.type)) {
        title = NbBundle.getMessage (CustomizerSupport.class,"TXT_OpenSources");
        message = NbBundle.getMessage (CustomizerSupport.class,"TXT_FilterSources");
        approveButtonName = NbBundle.getMessage (CustomizerSupport.class,"TXT_OpenSources");
        approveButtonNameMne = NbBundle.getMessage (CustomizerSupport.class,"MNE_OpenSources");
    } else if (JAVADOC.equals(this.type)) {
        title = NbBundle.getMessage (CustomizerSupport.class,"TXT_OpenJavadoc");
        message = NbBundle.getMessage (CustomizerSupport.class,"TXT_FilterJavadoc");
        approveButtonName = NbBundle.getMessage (CustomizerSupport.class,"TXT_OpenJavadoc");
        approveButtonNameMne = NbBundle.getMessage (CustomizerSupport.class,"MNE_OpenJavadoc");
    } else {
        throw new IllegalStateException("Can't add element for classpath"); // NOI18N
    }
    chooser.setDialogTitle(title);
    chooser.setApproveButtonText(approveButtonName);
    chooser.setApproveButtonMnemonic (approveButtonNameMne.charAt(0));
    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    //#61789 on old macosx (jdk 1.4.1) these two method need to be called in this order.
    chooser.setAcceptAllFileFilterUsed( false );
    chooser.setFileFilter (new SimpleFileFilter(message,new String[] {"ZIP","JAR"}));   //NOI18N
    if (this.currentDir != null && currentDir.exists()) {
        chooser.setCurrentDirectory(this.currentDir);
    }
    if (chooser.showOpenDialog(this)==JFileChooser.APPROVE_OPTION) {
        File[] fs = chooser.getSelectedFiles();
        PathModel model = (PathModel) this.resources.getModel();
        boolean addingFailed = false;
        int firstIndex = this.resources.getModel().getSize();
        for (int i = 0; i < fs.length; i++) {
            File f = fs[i];
            //XXX: JFileChooser workaround (JDK bug #5075580), double click on folder returns wrong file
            // E.g. for /foo/src it returns /foo/src/src
            // Try to convert it back by removing last invalid name component
            if (!f.exists()) {
                File parent = f.getParentFile();
                if (parent != null && f.getName().equals(parent.getName()) && parent.exists()) {
                    f = parent;
                }
            }
            addingFailed|=!model.addPath (f);
        }
        if (addingFailed) {
            new NotifyDescriptor.Message (NbBundle.getMessage(CustomizerSupport.class,"TXT_CanNotAddResolve"),
                    NotifyDescriptor.ERROR_MESSAGE);
        }
        int lastIndex = this.resources.getModel().getSize()-1;
        if (firstIndex<=lastIndex) {
            int[] toSelect = new int[lastIndex-firstIndex+1];
            for (int i = 0; i < toSelect.length; i++) {
                toSelect[i] = firstIndex+i;
            }
            this.resources.setSelectedIndices(toSelect);
        }
        this.currentDir = FileUtil.normalizeFile(chooser.getCurrentDirectory());
    }
}
 
Example 19
Source File: DiffResultsViewForLine.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public LocalFileDiffStreamSource (File file, boolean isRight) {
    this.file = FileUtil.normalizeFile(file);
    this.fileObject = FileUtil.toFileObject(this.file);
    this.isRight = isRight;
}
 
Example 20
Source File: BinaryUsagesTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private FileObject[] findFileObjectsInRepository(File f) {
    if (!f.equals(FileUtil.normalizeFile(f))) {
        throw new IllegalArgumentException(
            "Parameter file was not " + // NOI18N
            "normalized. Was " + f + " instead of " + FileUtil.normalizeFile(f)
        ); // NOI18N
    }

    @SuppressWarnings("deprecation") // keep for backward compatibility w/ NB 3.x
    Enumeration<? extends FileSystem> en = Repository.getDefault().getFileSystems();
    List<FileObject> list = new LinkedList<FileObject>();
    String fileName = f.getAbsolutePath();

    while (en.hasMoreElements()) {
        FileSystem fs = en.nextElement();
        String rootName = null;
        FileObject fsRoot = fs.getRoot();
        File root = findFileInRepository(fsRoot);

        if (root == null) {
            Object rootPath = fsRoot.getAttribute("FileSystem.rootPath"); //NOI18N

            if ((rootPath != null) && (rootPath instanceof String)) {
                rootName = (String) rootPath;
            } else {
                continue;
            }
        }

        if (rootName == null) {
            rootName = root.getAbsolutePath();
        }

        /**root is parent of file*/
        if (fileName.indexOf(rootName) == 0) {
            String res = fileName.substring(rootName.length()).replace(File.separatorChar, '/');
            FileObject fo = fs.findResource(res);
            File file2Fo = (fo != null) ? findFileInRepository(fo) : null;
            if ((fo != null) && (file2Fo != null) && f.equals(file2Fo)) {
                list.add(fo);
            }
        }
    }
    FileObject[] results = new FileObject[list.size()];
    list.toArray(results);
    return results;
}