Example usage for org.apache.commons.vfs FileObject isWriteable

List of usage examples for org.apache.commons.vfs FileObject isWriteable

Introduction

In this page you can find the example usage for org.apache.commons.vfs FileObject isWriteable.

Prototype

public boolean isWriteable() throws FileSystemException;

Source Link

Document

Determines if this file can be written to.

Usage

From source file:com.newatlanta.appengine.junit.vfs.gae.GaeVfsTestCase.java

public static void assertEquals(File file, FileObject fileObject) throws Exception {
    assertEqualPaths(file, fileObject);//from  w  ww  .  j a  va 2 s . c  o  m
    assertEquals(file.canRead(), fileObject.isReadable());
    assertEquals(file.canWrite(), fileObject.isWriteable());
    assertEquals(file.exists(), fileObject.exists());
    if (file.getParentFile() == null) {
        assertNull(fileObject.getParent());
    } else {
        assertEqualPaths(file.getParentFile(), fileObject.getParent());
    }
    assertEquals(file.isDirectory(), fileObject.getType().hasChildren());
    assertEquals(file.isFile(), fileObject.getType().hasContent());
    assertEquals(file.isHidden(), fileObject.isHidden());
    if (file.isFile()) {
        assertEquals(file.length(), fileObject.getContent().getSize());
    }
    if (file.isDirectory()) { // same children
        File[] childFiles = file.listFiles();
        FileObject[] childObjects = fileObject.getChildren();
        assertEquals(childFiles.length, childObjects.length);
        for (int i = 0; i < childFiles.length; i++) {
            assertEqualPaths(childFiles[i], childObjects[i]);
        }
    }
}

From source file:com.newatlanta.appengine.junit.vfs.gae.GaeFolderTestCase.java

private static void assertFolder(FileObject folder) throws Exception {
    assertTrue(folder.exists());//from w  ww. j a  v a 2s .  c o  m
    assertTrue(folder.isAttached()); // exists() causes attach
    assertTrue(folder.isReadable());
    assertTrue(folder.isWriteable());
    assertFalse(folder.isHidden());
    assertTrue(folder.getType().hasChildren());
    assertFalse(folder.getType().hasContent());

    // TODO: with combined local option, local children of GAE folder will
    // have a different parent; maybe we can compare paths when GaeFileName
    // is modified to store abspath like LocalFileName
    //      FileObject[] children = folder.getChildren();
    //      for ( FileObject child : children ) {
    //         assertEquals( folder, child.getParent() );
    //         FileObject childObject = folder.getChild( child.getName().getURI() );
    //         assertEquals( child, childObject );
    //         assertEquals( folder, childObject.getParent() );
    //      }

    // TODO: use folder.findFiles( Selectors.SELECT_ALL) to get all
    // descendants, then test FileName.isDescendant() and isAncestor()
}

From source file:net.sf.vfsjfilechooser.utils.VFSUtils.java

/**
 * Tells whether a file is writable/*from   ww w .  j  av a  2s .  c o  m*/
 * @param fileObject
 * @return whether a file is writable
 */
public static boolean canWrite(FileObject fileObject) {
    try {
        return fileObject.isWriteable();
    } catch (FileSystemException ex) {
        return false;
    }
}

From source file:org.apache.commons.vfs.example.ShowProperties.java

public static void main(String[] args) {
    if (args.length == 0) {
        System.err.println("Please pass the name of a file as parameter.");
        System.err.println("e.g. java org.apache.commons.vfs.example.ShowProperties LICENSE.txt");
        return;//from   w ww.j av  a 2 s.  c o  m
    }
    for (int i = 0; i < args.length; i++) {
        try {
            FileSystemManager mgr = VFS.getManager();
            System.out.println();
            System.out.println("Parsing: " + args[i]);
            FileObject file = mgr.resolveFile(args[i]);
            System.out.println("URL: " + file.getURL());
            System.out.println("getName(): " + file.getName());
            System.out.println("BaseName: " + file.getName().getBaseName());
            System.out.println("Extension: " + file.getName().getExtension());
            System.out.println("Path: " + file.getName().getPath());
            System.out.println("Scheme: " + file.getName().getScheme());
            System.out.println("URI: " + file.getName().getURI());
            System.out.println("Root URI: " + file.getName().getRootURI());
            System.out.println("Parent: " + file.getName().getParent());
            System.out.println("Type: " + file.getType());
            System.out.println("Exists: " + file.exists());
            System.out.println("Readable: " + file.isReadable());
            System.out.println("Writeable: " + file.isWriteable());
            System.out.println("Root path: " + file.getFileSystem().getRoot().getName().getPath());
            if (file.exists()) {
                if (file.getType().equals(FileType.FILE)) {
                    System.out.println("Size: " + file.getContent().getSize() + " bytes");
                } else if (file.getType().equals(FileType.FOLDER) && file.isReadable()) {
                    FileObject[] children = file.getChildren();
                    System.out.println("Directory with " + children.length + " files");
                    for (int iterChildren = 0; iterChildren < children.length; iterChildren++) {
                        System.out.println("#" + iterChildren + ": " + children[iterChildren].getName());
                        if (iterChildren > 5) {
                            break;
                        }
                    }
                }
                System.out.println("Last modified: "
                        + DateFormat.getInstance().format(new Date(file.getContent().getLastModifiedTime())));
            } else {
                System.out.println("The file does not exist");
            }
            file.close();
        } catch (FileSystemException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:org.docx4all.ui.menu.FileMenu.java

private RETURN_TYPE saveAsFile(String callerActionName, ActionEvent actionEvent, String fileType) {
    Preferences prefs = Preferences.userNodeForPackage(getClass());
    WordMLEditor editor = WordMLEditor.getInstance(WordMLEditor.class);
    ResourceMap rm = editor.getContext().getResourceMap(getClass());

    JInternalFrame iframe = editor.getCurrentInternalFrame();
    String oldFilePath = (String) iframe.getClientProperty(WordMLDocument.FILE_PATH_PROPERTY);

    VFSJFileChooser chooser = createFileChooser(rm, callerActionName, iframe, fileType);

    RETURN_TYPE returnVal = chooser.showSaveDialog((Component) actionEvent.getSource());
    if (returnVal == RETURN_TYPE.APPROVE) {
        FileObject selectedFile = getSelectedFile(chooser, fileType);

        boolean error = false;
        boolean newlyCreatedFile = false;

        if (selectedFile == null) {

            // Should never happen, whether the file exists or not

        } else {// w  ww .  ja  v  a  2 s  .c  o m

            //Check selectedFile's existence and ask user confirmation when needed.
            try {
                boolean selectedFileExists = selectedFile.exists();
                if (!selectedFileExists) {
                    FileObject parent = selectedFile.getParent();
                    String uri = UriParser.decode(parent.getName().getURI());

                    if (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") > -1
                            && parent.getName().getScheme().startsWith("file") && !parent.isWriteable()
                            && (uri.indexOf("/Documents") > -1 || uri.indexOf("/My Documents") > -1)) {
                        //TODO: Check whether we still need this workaround.
                        //See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4939819
                        //Re: File.canWrite() returns false for the "My Documents" directory (win)
                        String localpath = org.docx4j.utils.VFSUtils.getLocalFilePath(parent);
                        File f = new File(localpath);
                        f.setWritable(true, true);
                    }

                    selectedFile.createFile();
                    newlyCreatedFile = true;

                } else if (!selectedFile.getName().getURI().equalsIgnoreCase(oldFilePath)) {
                    String title = rm.getString(callerActionName + ".Action.text");
                    String message = VFSUtils.getFriendlyName(selectedFile.getName().getURI()) + "\n"
                            + rm.getString(callerActionName + ".Action.confirmMessage");
                    int answer = editor.showConfirmDialog(title, message, JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE);
                    if (answer != JOptionPane.YES_OPTION) {
                        selectedFile = null;
                    }
                } // if (!selectedFileExists)

            } catch (FileSystemException exc) {
                exc.printStackTrace();//ignore
                log.error("Couldn't create new file or assure file existence. File = "
                        + selectedFile.getName().getURI());
                selectedFile = null;
                error = true;
            }
        }

        //Check whether there has been an error, cancellation by user
        //or may proceed to saving file.
        if (selectedFile != null) {
            //Proceed to saving file
            String selectedPath = selectedFile.getName().getURI();
            if (log.isDebugEnabled()) {
                log.debug("saveAsFile(): selectedFile = " + VFSUtils.getFriendlyName(selectedPath));
            }

            prefs.put(Constants.LAST_OPENED_FILE, selectedPath);
            if (selectedFile.getName().getScheme().equals("file")) {
                prefs.put(Constants.LAST_OPENED_LOCAL_FILE, selectedPath);
            }
            PreferenceUtil.flush(prefs);

            boolean success = false;
            if (EXPORT_AS_NON_SHARED_DOC_ACTION_NAME.equals(callerActionName)) {
                log.info("saveAsFile(): Exporting as non shared document to "
                        + VFSUtils.getFriendlyName(selectedPath));
                success = export(iframe, selectedPath, callerActionName);
                if (success) {
                    prefs.put(Constants.LAST_OPENED_FILE, selectedPath);
                    if (selectedPath.startsWith("file:")) {
                        prefs.put(Constants.LAST_OPENED_LOCAL_FILE, selectedPath);
                    }
                    PreferenceUtil.flush(prefs);
                    log.info("saveAsFile(): Opening " + VFSUtils.getFriendlyName(selectedPath));
                    editor.createInternalFrame(selectedFile);
                }
            } else {
                success = save(iframe, selectedPath, callerActionName);
                if (success) {
                    if (Constants.DOCX_STRING.equals(fileType) || Constants.FLAT_OPC_STRING.equals(fileType)) {
                        //If saving as .docx then update the document dirty flag 
                        //of toolbar states as well as internal frame title.
                        editor.getToolbarStates().setDocumentDirty(iframe, false);
                        editor.getToolbarStates().setLocalEditsEnabled(iframe, false);
                        FileObject file = null;
                        try {
                            file = VFSUtils.getFileSystemManager().resolveFile(oldFilePath);
                            editor.updateInternalFrame(file, selectedFile);
                        } catch (FileSystemException exc) {
                            ;//ignore
                        }
                    } else {
                        //Because document dirty flag is not cleared
                        //and internal frame title is not changed,
                        //we present a success message.
                        String title = rm.getString(callerActionName + ".Action.text");
                        String message = VFSUtils.getFriendlyName(selectedPath) + "\n"
                                + rm.getString(callerActionName + ".Action.successMessage");
                        editor.showMessageDialog(title, message, JOptionPane.INFORMATION_MESSAGE);
                    }
                }
            }

            if (!success && newlyCreatedFile) {
                try {
                    selectedFile.delete();
                } catch (FileSystemException exc) {
                    log.error("saveAsFile(): Saving failure and cannot remove the newly created file = "
                            + selectedPath);
                    exc.printStackTrace();
                }
            }
        } else if (error) {
            log.error("saveAsFile(): selectedFile = NULL");
            String title = rm.getString(callerActionName + ".Action.text");
            String message = rm.getString(callerActionName + ".Action.errorMessage");
            editor.showMessageDialog(title, message, JOptionPane.ERROR_MESSAGE);
        }

    } //if (returnVal == JFileChooser.APPROVE_OPTION)

    return returnVal;
}

From source file:org.docx4all.ui.menu.FileMenu.java

public void createInFileSystem(FileObject file) throws FileSystemException {
    FileObject parent = file.getParent();
    String uri = UriParser.decode(parent.getName().getURI());

    if (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") > -1
            && parent.getName().getScheme().startsWith("file") && !parent.isWriteable()
            && (uri.indexOf("/Documents") > -1 || uri.indexOf("/My Documents") > -1)) {
        //TODO: Check whether we still need this workaround.
        //See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4939819
        //Re: File.canWrite() returns false for the "My Documents" directory (win)
        String localpath = org.docx4j.utils.VFSUtils.getLocalFilePath(parent);
        File f = new File(localpath);
        f.setWritable(true, true);/*from w ww.ja  v  a  2s . co m*/
    }

    file.createFile();
}

From source file:org.jboss.dashboard.ui.components.FileNavigationHandler.java

public CommandResponse actionCreateFolder(CommandRequest request) throws FileSystemException {
    if (createFolderAllowed || getUserStatus().isRootUser()) {
        FileObject currentDir = getCurrentDir();
        if (currentDir != null && currentDir.isWriteable()) {
            String folderName = request.getRequestObject().getParameter("folderName");
            FileObject fileObject = getCurrentDir().resolveFile(folderName);
            if (!fileObject.exists()) {
                fileObject.createFolder();
                openPaths.add(currentPath);
                currentPath = fileObject.getName().getPath();
                selectedFile = null;/*from  w w  w. j  av  a  2  s .  co  m*/
                return getCommonResponse(request);
            } else {
                //TODO: Deal with errors
            }
        }
    }
    //TODO: Deal with permission error
    return getCommonResponse(request);
}

From source file:org.jboss.dashboard.ui.components.FileNavigationHandler.java

public CommandResponse actionUploadFile(CommandRequest request) throws IOException {
    if (uploadFileAllowed || getUserStatus().isRootUser()) {
        FileObject currentDir = getCurrentDir();
        if (currentDir != null && currentDir.isWriteable()) {
            File file = (File) request.getFilesByParamName().get("file");
            if (file != null) {
                String fileName = file.getName();
                FileObject fileObject = currentDir.resolveFile(fileName);
                if (!fileObject.exists()) {
                    fileObject.createFile();
                    OutputStream os = fileObject.getContent().getOutputStream(true);
                    InputStream is = new BufferedInputStream(new FileInputStream(file));
                    IOUtils.copy(is, os);
                    is.close();//from  ww w .  ja va2 s .  co m
                    os.close();
                    currentFilePath = fileObject.getName().getPath();
                    return getCommonResponse(request);
                } else {
                    //TODO: Deal with errors
                }
            }
        }
    }
    //TODO: Deal with permission error
    return getCommonResponse(request);
}

From source file:org.jboss.dashboard.ui.components.FileNavigationHandler.java

public CommandResponse actionDeleteFile(CommandRequest request) throws FileSystemException {
    if (isDeleteFileAllowed() || getUserStatus().isRootUser()) {
        FileObject currentFile = getCurrentFile();
        if (currentFile != null && currentFile.isWriteable()) {
            FileObject parentDir = currentFile.getParent();
            if (parentDir != null && parentDir.isWriteable()) {
                if (currentFile.delete()) {
                    currentFilePath = null;
                }/*from w  w w. j ava 2s.  co  m*/
            }
        }
    }
    return getCommonResponse(request);
}

From source file:org.jboss.dashboard.ui.components.FileNavigationHandler.java

public CommandResponse actionDeleteFolder(CommandRequest request) throws FileSystemException {
    if (isDeleteFolderAllowed() || getUserStatus().isRootUser()) {
        if (!getCurrentPath().equals(getBaseDirPath())) {
            FileObject currentDir = getCurrentDir();
            if (currentDir != null && currentDir.isWriteable()
                    && (currentDir.getChildren() == null || currentDir.getChildren().length == 0)) {
                FileObject parentDir = currentDir.getParent();
                if (parentDir != null && parentDir.isWriteable()) {
                    if (currentDir.delete()) {
                        currentPath = currentPath.substring(0, currentPath.lastIndexOf("/"));
                    }//from   w  w w. j a  v a  2 s .co  m
                }
            }
        }
    }
    return getCommonResponse(request);
}