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

The following examples show how to use org.openide.filesystems.FileObject#canWrite() . 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: SourceGroups.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whether the folder identified by the given <code>packageName</code> is
 * writable or is in a writable parent directory but does not exist yet.
 * 
 * @param sourceGroup the source group of the folder; must not be null.
 * @param packageName the package to check; must not be null.
 * @return true if the folder is writable or can be created (i.e. the parent 
 * folder, or the root folder of the given <code>sourceGroup</code> if there is no other 
 * parent for the folder, is writable), false otherwise.
 */ 
public static boolean isFolderWritable(SourceGroup sourceGroup, String packageName) {
    Parameters.notNull("sourceGroup", sourceGroup); //NOI18N
    Parameters.notNull("packageName", packageName); //NOI18N
    try {
        FileObject fo = getFolderForPackage(sourceGroup, packageName, false);

        while ((fo == null) && (packageName.lastIndexOf('.') != -1)) {
            packageName = packageName.substring(0, packageName.lastIndexOf('.'));
            fo = getFolderForPackage(sourceGroup, packageName, false);
        }
        return fo == null ? sourceGroup.getRootFolder().canWrite() : fo.canWrite();
    } catch (IOException ex) {
        LOGGER.log(Level.INFO, null, ex);
        return false;
    }
}
 
Example 2
Source File: GrailsPluginSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private boolean uninstallPlugins10(Collection<GrailsPlugin> selectedPlugins) {
    if (selectedPlugins != null && selectedPlugins.size() > 0) {
        final FileObject pluginsDir = project.getProjectDirectory().getFileObject("plugins"); //NO I18N
        if (pluginsDir != null && pluginsDir.isFolder() && pluginsDir.canWrite()) {
            pluginsDir.refresh();
            try {
                for (GrailsPlugin plugin : selectedPlugins) {
                    FileObject pluginDir = pluginsDir.getFileObject(plugin.getDirName());
                    if (pluginDir != null && pluginDir.isValid()) {
                        pluginDir.delete();
                    }
                    FileObject pluginZipFile = pluginsDir.getFileObject(plugin.getZipName());
                    if (pluginZipFile != null && pluginZipFile.isValid()) {
                        pluginZipFile.delete();
                    }
                }
            } catch (Exception ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }
    return true;
}
 
Example 3
Source File: SharabilityFilter.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 */
@Override
public boolean searchFile(FileObject file)
        throws IllegalArgumentException {
    if (file.isFolder()) {
        throw new java.lang.IllegalArgumentException(
                "file (not folder) expected");                      //NOI18N
    }
    File f = FileUtil.toFile(file);
    if (f == null && !file.canWrite()) {
        // non-standard file objects, e.g. ZIP archive items.
        return true;
    } else {
        return SharabilityQuery.getSharability(file)
                != Sharability.NOT_SHARABLE;
    }
}
 
Example 4
Source File: SharabilityFilter.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 */
@Override
public boolean searchFile(FileObject file)
        throws IllegalArgumentException {
    if (file.isFolder()) {
        throw new java.lang.IllegalArgumentException(
                "file (not folder) expected");                      //NOI18N
    }
    File f = FileUtil.toFile(file);
    if (f == null && !file.canWrite()) {
        // non-standard file objects, e.g. ZIP archive items.
        return true;
    } else {
        return SharabilityQuery.getSharability(FileUtil.toFile(file))
                != SharabilityQuery.NOT_SHARABLE;
    }
}
 
Example 5
Source File: SharabilityFilter.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 */
@Override
public int traverseFolder(FileObject folder)
        throws IllegalArgumentException {
    if (!folder.isFolder()) {
        throw new java.lang.IllegalArgumentException(
                "folder expected");                                 //NOI18N
    }
    File f = FileUtil.toFile(folder);
    if (f == null && !folder.canWrite()) {
        // non-standard file objects, e.g. ZIP archive items.
        return TRAVERSE;
    } else {
        final int sharability = SharabilityQuery.getSharability(f);
        switch (sharability) {
            case SharabilityQuery.NOT_SHARABLE:
                return DO_NOT_TRAVERSE;
            case SharabilityQuery.SHARABLE:
                return TRAVERSE_ALL_SUBFOLDERS;
            default:
                return TRAVERSE;
        }
    }
}
 
Example 6
Source File: DiffStreamSource.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean isBaseFileWritable () {
    if (canWriteBaseFile == null) {
        FileObject fo = FileUtil.toFileObject(baseFile);
        canWriteBaseFile = fo != null && fo.canWrite();
    }
    return canWriteBaseFile;
}
 
Example 7
Source File: SQLCloneableEditor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Messages({
     "MSG_SaveModified=File {0} is modified. Save?"
 })
 @Override
 public CloseOperationState canCloseElement() {
     if (sqlEditorSupport().isConsole()) {
         return CloseOperationState.STATE_OK;
     } else {
         DataObject sqlDO = sqlEditorSupport().getDataObject();
         FileObject sqlFO = sqlEditorSupport().getDataObject().getPrimaryFile();
         if (sqlDO.isModified()) {
             if (sqlFO.canWrite()) {
                 Savable sav = sqlDO.getLookup().lookup(Savable.class);
                 if (sav != null) {
                     AbstractAction save = new AbstractAction() {
                         @Override
                         public void actionPerformed(ActionEvent e) {
                             try {
                                 sqlEditorSupport().saveDocument();
                             } catch (IOException ex) {
                                 Exceptions.printStackTrace(ex);
                             }
                         }
                     };
                     save.putValue(Action.LONG_DESCRIPTION, Bundle.MSG_SaveModified(sqlFO.getNameExt()));
                     return MultiViewFactory.createUnsafeCloseState("editor", save, null);
                 }
             }
         }
     }
     return CloseOperationState.STATE_OK;
}
 
Example 8
Source File: FixDescription.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void implement() throws Exception {
    final FileObject file = err.getFile();
    if (!file.canWrite()) {
        NotifyDescriptor d = new NotifyDescriptor.Message(
                NbBundle.getMessage(FixDescription.class, "CTL_File_Not_Writable", file.getNameExt()), //NOI18N
                NotifyDescriptor.ERROR_MESSAGE);
        DialogDisplayer.getDefault().notify(d);
        return ;
    }

    fix.implement();
    fixed.set(true);
    cs.fireChange();
}
 
Example 9
Source File: DiffStreamSource.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean isBaseFileWritable () {
    if (canWriteBaseFile == null) {
        FileObject fo = FileUtil.toFileObject(baseFile);
        canWriteBaseFile = fo != null && fo.canWrite();
    }
    return canWriteBaseFile;
}
 
Example 10
Source File: SourceGroupSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static boolean isFolderWritable(SourceGroup sourceGroup, String packageName) {
    try {
        FileObject fo = getFolderForPackage(sourceGroup, packageName, false);

        while ((fo == null) && (packageName.lastIndexOf('.') != -1)) {
            packageName = packageName.substring(0, packageName.lastIndexOf('.'));
            fo = getFolderForPackage(sourceGroup, packageName, false);
        }
        return ((fo == null) || fo.canWrite());
    } catch (IOException ex) {
        return false;
    }
}
 
Example 11
Source File: IntroduceSuggestion.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static IntroduceClassFix getInstance(String className, Model model, ClassInstanceCreation instanceCreation) {
    FileObject currentFile = model.getFileScope().getFileObject();
    FileObject folder = currentFile == null ? null : currentFile.getParent();
    String templatePath = "Templates/Scripting/PHPClass.php"; //NOI18N
    FileObject template = FileUtil.getConfigFile(templatePath);
    return (template != null && folder != null && folder.canWrite())
            ? new IntroduceClassFix(className, template, folder, instanceCreation) : null;
}
 
Example 12
Source File: DiffStreamSource.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean isBaseFileWritable () {
    if (canWriteBaseFile == null) {
        FileObject fo = FileUtil.toFileObject(baseFile);
        canWriteBaseFile = fo != null && fo.canWrite();
    }
    return canWriteBaseFile;
}
 
Example 13
Source File: SourceGroupSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static boolean isFolderWritable(SourceGroup sourceGroup, String packageName) {
    try {
        FileObject fo = getFolderForPackage(sourceGroup, packageName, false);

        while ((fo == null) && (packageName.lastIndexOf('.') != -1)) {
            packageName = packageName.substring(0, packageName.lastIndexOf('.'));
            fo = getFolderForPackage(sourceGroup, packageName, false);
        }
        return ((fo == null) || fo.canWrite());
    } catch (IOException ex) {
        return false;
    }
}
 
Example 14
Source File: Richfaces4Implementation.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void updateIndexPage(WebModule webModule) throws DataObjectNotFoundException {
    FileObject documentBase = webModule.getDocumentBase();
    if (documentBase != null) {
        FileObject indexFO = documentBase.getFileObject("index.xhtml"); //NOI18N
        if (indexFO != null) {
            DataObject indexDO = DataObject.find(indexFO);
            JsfComponentUtils.enhanceFileBody(indexDO, "</h:body>", "<br />\n<h:link outcome=\"welcomeRichfaces\" value=\"Richfaces welcome page\" />"); //NOI18N
            if (indexFO.isValid() && indexFO.canWrite()) {
                JsfComponentUtils.reformat(indexDO);
            }
        }
    }
}
 
Example 15
Source File: ResourceLibraryIteratorPanel.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Messages({
    "ResourceLibraryIteratorPanel.err.contract.name.empty=Contract name is empty",
    "ResourceLibraryIteratorPanel.err.contract.name.not.valid=Contract name is not valid folder name",
    "ResourceLibraryIteratorPanel.err.template.name.empty=Template name is empty",
    "ResourceLibraryIteratorPanel.err.template.name.not.valid=Template name is not valid file name",
    "ResourceLibraryIteratorPanel.err.contracts.parent.not.extists=Contracts parent folder doesn't exist",
    "ResourceLibraryIteratorPanel.err.contracts.parent.not.writeable=Contracts parent folder is not writeable",
    "ResourceLibraryIteratorPanel.err.contracts.folder.not.writeable=Contracts folder is not writeable",
    "ResourceLibraryIteratorPanel.err.contract.already.exists=Such contract folder already exists",
})
@Override
public boolean isValid() {
    getComponent();
    descriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, " "); //NOI18N

    // folders permissions
    if (!contractsParent.isValid() || !contractsParent.isFolder()) {
        descriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, Bundle.ResourceLibraryIteratorPanel_err_contracts_parent_not_extists());
        return false;
    }
    FileObject contractsFolder = contractsParent.getFileObject(ResourceLibraryIterator.CONTRACTS);
    if (contractsFolder == null) {
        if (!contractsParent.canWrite()) {
            descriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, Bundle.ResourceLibraryIteratorPanel_err_contracts_parent_not_writeable());
            return false;
        }
    } else {
        if (!contractsFolder.canWrite()) {
            descriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, Bundle.ResourceLibraryIteratorPanel_err_contracts_folder_not_writeable());
            return false;
        }
        if (contractsFolder.getFileObject(gui.getContractName()) != null) {
            descriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, Bundle.ResourceLibraryIteratorPanel_err_contract_already_exists());
            return false;
        }
    }

    // contact naming
    if (gui.getContractName().isEmpty()) {
        descriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, Bundle.ResourceLibraryIteratorPanel_err_contract_name_empty());
        return false;
    }
    if (!isValidFileName(gui.getContractName())) {
        descriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, Bundle.ResourceLibraryIteratorPanel_err_contract_name_not_valid());
        return false;
    }

    // initial template naming
    if (gui.isCreateInitialTemplate()) {
        if (gui.getTemplateName().isEmpty()) {
            descriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, Bundle.ResourceLibraryIteratorPanel_err_template_name_empty());
            return false;
        }
        if (!isValidFileName(gui.getTemplateName())) {
            descriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, Bundle.ResourceLibraryIteratorPanel_err_template_name_not_valid());
            return false;
        }
    }
    return true;
}
 
Example 16
Source File: FormDataObject.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public boolean isReadOnly() {
    FileObject javaFO = getPrimaryFile();
    FileObject formFO = formEntry.getFile();
    return !javaFO.canWrite() || !formFO.canWrite();
}
 
Example 17
Source File: Utilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Checks if the given file name can be created in the target folder.
 *
 * @param dir target directory
 * @param newObjectName name of created file
 * @param extension extension of created file
 * @return localized error message or null if all right
 */
public static String canUseFileName (java.io.File dir, String relativePath, String objectName, String extension) {
    String newObjectName=objectName;
    if (extension != null && extension.length () > 0) {
        StringBuffer sb = new StringBuffer ();
        sb.append (objectName);
        sb.append ('.'); // NOI18N
        sb.append (extension);
        newObjectName = sb.toString ();
    }
    
    // check file name
    
    if (!checkFileName(objectName)) {
        return NbBundle.getMessage (Utilities.class, "MSG_invalid_filename", newObjectName); // NOI18N
    }
    // test if the directory is correctly specified
    FileObject folder = null;
    if (dir!=null) {
        try {
             folder = org.openide.filesystems.FileUtil.toFileObject(dir);
        } catch(java.lang.IllegalArgumentException ex) {
             return NbBundle.getMessage (Utilities.class, "MSG_invalid_path", relativePath); // NOI18N
        }
    }
        
    // test whether the selected folder on selected filesystem is read-only or exists
    if (folder!=  null) {
        // target filesystem should be writable
        if (!folder.canWrite ()) {
            return NbBundle.getMessage (Utilities.class, "MSG_fs_is_readonly"); // NOI18N
        }

        if (folder.getFileObject (newObjectName) != null) {
            return NbBundle.getMessage (Utilities.class, "MSG_file_already_exist", newObjectName); // NOI18N
        }

        if (org.openide.util.Utilities.isWindows ()) {
            if (checkCaseInsensitiveName (folder, newObjectName)) {
                return NbBundle.getMessage (Utilities.class, "MSG_file_already_exist", newObjectName); // NOI18N
            }
        }
    }

    // all ok
    return null;
}
 
Example 18
Source File: J2SEProject.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@NonNull
private Runnable newUpdateCopyLibsAction() {
    return new Runnable() {
        private final String LIB_COPY_LIBS = "CopyLibs"; //NOI18N
        private final String PROP_VERSION = "version";   //NOI18N
        private final String VOL_CP = "classpath";       //NOI18N

        @Override
        public void run() {
            final LibraryManager projLibManager = refHelper.getProjectLibraryManager();
            if (projLibManager == null) {
                return;
            }
            final Library globalCopyLibs = LibraryManager.getDefault().getLibrary(LIB_COPY_LIBS);
            final Library projectCopyLibs = projLibManager.getLibrary(LIB_COPY_LIBS);
            if (globalCopyLibs == null || projectCopyLibs == null) {
                return;
            }
            final String globalStr = globalCopyLibs.getProperties().get(PROP_VERSION);
            if (globalStr == null) {
                return;
            }
            try {
                final SpecificationVersion globalVersion = new SpecificationVersion(globalStr);
                final String projectStr = projectCopyLibs.getProperties().get(PROP_VERSION);
                if (projectStr != null && globalVersion.compareTo(new SpecificationVersion(projectStr)) <= 0) {
                    return;
                }

                final List<URL> content = projectCopyLibs.getContent(VOL_CP);
                projLibManager.removeLibrary(projectCopyLibs);
                final FileObject projLibLoc = URLMapper.findFileObject(projLibManager.getLocation());
                if (projLibLoc != null) {
                    final FileObject libFolder = projLibLoc.getParent();
                    boolean canDelete = libFolder.canWrite();
                    FileObject container = null;
                    for (URL u : content) {
                        FileObject fo = toFile(u);
                        if (fo != null) {
                            canDelete &= fo.canWrite();
                            if (container == null) {
                                container = fo.getParent();
                                canDelete &= container.canWrite();
                                canDelete &= LIB_COPY_LIBS.equals(container.getName());
                                canDelete &= libFolder.equals(container.getParent());
                            } else {
                                canDelete &= container.equals(fo.getParent());
                            }
                        }
                    }
                    if (canDelete && container != null) {
                        container.delete();
                    }
                }
                refHelper.copyLibrary(globalCopyLibs);

            } catch (IllegalArgumentException iae) {
                LOG.log(
                        Level.WARNING,
                        "Cannot update {0} due to invalid version.", //NOI18N
                        projectCopyLibs.getDisplayName());
            } catch (IOException ioe) {
                Exceptions.printStackTrace(ioe);
            }
        }

        @CheckForNull
        private FileObject toFile(@NonNull final URL url) {
            final URL file = FileUtil.getArchiveFile(url);
            return URLMapper.findFileObject(file != null ? file : url);
        }
    };
}
 
Example 19
Source File: JAXBRefreshAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
protected void performAction(Node[] nodes) {
    Node node = nodes[ 0 ];
    FileObject fo = node.getLookup().lookup( FileObject.class );
    Project proj = node.getLookup().lookup(Project.class);
    String origLoc = (String) node.getValue(
            JAXBWizModuleConstants.ORIG_LOCATION);
    Boolean origLocIsURL = (Boolean) node.getValue(
            JAXBWizModuleConstants.ORIG_LOCATION_TYPE);
    FileObject locSchemaRoot = (FileObject) node.getValue(
            JAXBWizModuleConstants.LOC_SCHEMA_ROOT);
    
    if ( ( fo != null ) && ( origLoc != null ) ) {
        // XXX TODO run in separate non-awt thread.
         try {
             if (fo.canWrite()){
                 if (origLocIsURL){
                    URL url = new URL(origLoc);
                     ProjectHelper.retrieveResource(locSchemaRoot, 
                             url.toURI());                        
                 } else {
                     File projDir = FileUtil.toFile(
                             proj.getProjectDirectory());
                     //File srcFile = new File(origLoc);
                     File srcFile = FileSysUtil.Relative2AbsolutePath(
                             projDir, origLoc);
                     ProjectHelper.retrieveResource(fo.getParent(), 
                             srcFile.toURI());
                 }
             } else {
                 String msg = NbBundle.getMessage(this.getClass(),
                         "MSG_CanNotRefreshFile"); //NOI18N
                 NotifyDescriptor d = new NotifyDescriptor.Message(
                         msg, NotifyDescriptor.INFORMATION_MESSAGE);
                 d.setTitle(NbBundle.getMessage(this.getClass(), 
                         "LBL_RefreshFile")); //NOI18N
                 DialogDisplayer.getDefault().notify(d);
             }
         } catch (Exception ex){
             log(ex);
         } 
    }
}
 
Example 20
Source File: JavaRefactoringUtils.java    From netbeans with Apache License 2.0 2 votes vote down vote up
/**
 * returns true if file's mime type is text/x-java and file is on know source path
 * @param file 
 * @return 
 */
@SuppressWarnings("deprecation")
public static boolean isRefactorable(FileObject file) {
    return RefactoringUtils.isRefactorable(file) && file.canWrite() && file.canRead();
}