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

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

Introduction

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

Prototype

boolean isWriteable() throws FileSystemException;

Source Link

Document

Determines if this file can be written to.

Usage

From source file:org.obiba.opal.web.FilesResource.java

/**
 * Delete writable folder and sub-folders.
 *
 * @param folder/*w  ww .j  a v a 2 s  .  c o  m*/
 * @throws FileSystemException
 */
private void deleteFolder(FileObject folder) throws FileSystemException {
    if (!folder.isWriteable())
        return;

    FileObject[] files = folder.getChildren();
    for (FileObject file : files) {
        if (file.getType() == FileType.FOLDER) {
            deleteFolder(file);
        } else if (file.isWriteable()) {
            file.delete();
        }
    }
    if (folder.getChildren().length == 0) {
        folder.delete();
    }
}

From source file:org.obiba.opal.web.FilesResourceTest.java

@Test
public void testCreateFolder_CannotCreateFolderParentIsReadOnly()
        throws FileSystemException, URISyntaxException {
    expect(fileObjectMock.getType()).andReturn(FileType.FOLDER).atLeastOnce();
    expect(fileObjectMock.exists()).andReturn(true).atLeastOnce();
    FileObject childFolderMock = createMock(FileObject.class);
    expect(childFolderMock.exists()).andReturn(false).atLeastOnce();
    FileObject parentFolderMock = createMock(FileObject.class);
    expect(childFolderMock.getParent()).andReturn(parentFolderMock).atLeastOnce();
    expect(parentFolderMock.isWriteable()).andReturn(false).atLeastOnce();
    expect(fileObjectMock.resolveFile("folder")).andReturn(childFolderMock).atLeastOnce();

    replay(fileObjectMock, parentFolderMock, childFolderMock);

    Response response = getFileResource().createFolder("folder1", "folder", uriInfoMock);
    assertThat(response.getStatus()).isEqualTo(Status.FORBIDDEN.getStatusCode());
    assertThat(response.getEntity()).isEqualTo("cannotCreateFolderParentIsReadOnly");
    verify(fileObjectMock, parentFolderMock, childFolderMock);
}

From source file:org.obiba.opal.web.FilesResourceTest.java

@Test
public void testCreateFolder_FolderCreatedSuccessfully() throws FileSystemException, URISyntaxException {
    expect(fileObjectMock.getType()).andReturn(FileType.FOLDER).atLeastOnce();
    expect(fileObjectMock.exists()).andReturn(true).atLeastOnce();

    FileObject childFolderMock = createMock(FileObject.class);

    FileName fileNameMock = createMock(FileName.class);
    expect(fileNameMock.getBaseName()).andReturn("folder").atLeastOnce();
    expect(fileNameMock.getPath()).andReturn("folder1/folder").atLeastOnce();

    expect(childFolderMock.getName()).andReturn(fileNameMock).atLeastOnce();
    expect(childFolderMock.exists()).andReturn(false).atLeastOnce();

    FileContent mockContent = createMock(FileContent.class);
    expect(childFolderMock.getContent()).andReturn(mockContent).atLeastOnce();
    expect(mockContent.getLastModifiedTime()).andReturn((long) 1).atLeastOnce();

    childFolderMock.createFolder();//from w  w w  .j  a  v a2 s. co m
    FileObject parentFolderMock = createMock(FileObject.class);
    expect(childFolderMock.getParent()).andReturn(parentFolderMock).atLeastOnce();
    expect(childFolderMock.isReadable()).andReturn(true).atLeastOnce();
    expect(childFolderMock.isWriteable()).andReturn(true).atLeastOnce();
    expect(parentFolderMock.isWriteable()).andReturn(true).atLeastOnce();
    expect(fileObjectMock.resolveFile("folder")).andReturn(childFolderMock).atLeastOnce();
    expect(uriInfoMock.getBaseUriBuilder()).andReturn(UriBuilder.fromPath("/"));

    replay(fileObjectMock, uriInfoMock, parentFolderMock, childFolderMock, fileNameMock, mockContent);

    Response response = getFileResource().createFolder("folder1", "folder", uriInfoMock);
    assertThat(response.getStatus()).isEqualTo(Status.CREATED.getStatusCode());
    verify(fileObjectMock, uriInfoMock, parentFolderMock, childFolderMock, fileNameMock, mockContent);
}

From source file:org.obiba.opal.web.FileSystemResource.java

@GET
public Opal.FileDto getFileSystem() throws FileSystemException {
    FileObject root = opalRuntime.getFileSystem().getRoot();

    // Create a root FileDto representing the root of the FileSystem.
    Opal.FileDto.Builder fileBuilder = Opal.FileDto.newBuilder();
    fileBuilder.setName("root").setType(Opal.FileDto.FileType.FOLDER).setPath("/");
    fileBuilder.setReadable(root.isReadable()).setWritable(root.isWriteable());

    // Create FileDtos for each file & folder in the FileSystem and add them to the root FileDto recursively.
    addFiles(fileBuilder, root);//  ww  w .j a v  a 2 s .  co  m

    return fileBuilder.build();
}

From source file:org.obiba.opal.web.FileSystemResource.java

private void addFiles(Opal.FileDto.Builder parentFolderBuilder, FileObject parentFolder)
        throws FileSystemException {
    Opal.FileDto.Builder fileBuilder;/*from   www.j a va2s  .  c  o m*/

    // Get the children for the current folder (list of files & folders).
    List<FileObject> children = Arrays.asList(parentFolder.getChildren());

    Collections.sort(children, new Comparator<FileObject>() {

        @Override
        public int compare(FileObject arg0, FileObject arg1) {
            return arg0.getName().compareTo(arg1.getName());
        }
    });

    // Loop through all children.
    for (FileObject child : children) {

        // Build a FileDto representing the child.
        fileBuilder = Opal.FileDto.newBuilder();
        fileBuilder.setName(child.getName().getBaseName()).setPath(child.getName().getPath());
        fileBuilder.setType(
                child.getType() == FileType.FILE ? Opal.FileDto.FileType.FILE : Opal.FileDto.FileType.FOLDER);
        fileBuilder.setReadable(child.isReadable()).setWritable(child.isWriteable());

        // If the current child is a folder, add its children recursively.
        if (child.getType() == FileType.FOLDER && child.isReadable()) {
            addFiles(fileBuilder, child);
        }

        // Add the current child to the parent FileDto (folder).
        parentFolderBuilder.addChildren(fileBuilder.build());
    }
}

From source file:org.ow2.proactive_grid_cloud_portal.scheduler.SchedulerStateRest.java

/**
 * Pushes a file from the local file system into the given DataSpace
 * //from  w  w  w.  j a  v  a2 s.  c o  m
 * @param sessionId
 *            a valid session id
 * @param spaceName
 *            the name of the DataSpace
 * @param filePath
 *            the path inside the DataSpace where to put the file e.g.
 *            "/myfolder"
 * @param multipart
 *            the form data containing : - fileName the name of the file
 *            that will be created on the DataSpace - fileContent the
 *            content of the file
 * @return true if the transfer succeeded
 * @see org.ow2.proactive.scheduler.common.SchedulerConstants for spaces
 *      names
 **/
@Override
public boolean pushFile(@HeaderParam("sessionid") String sessionId, @PathParam("spaceName") String spaceName,
        @PathParam("filePath") String filePath, MultipartFormDataInput multipart)
        throws IOException, NotConnectedRestException, PermissionRestException {
    checkAccess(sessionId, "pushFile");

    Session session = dataspaceRestApi.checkSessionValidity(sessionId);

    Map<String, List<InputPart>> formDataMap = multipart.getFormDataMap();

    List<InputPart> fNL = formDataMap.get("fileName");
    if ((fNL == null) || (fNL.size() == 0)) {
        throw new IllegalArgumentException("Illegal multipart argument definition (fileName), received " + fNL);
    }
    String fileName = fNL.get(0).getBody(String.class, null);

    List<InputPart> fCL = formDataMap.get("fileContent");
    if ((fCL == null) || (fCL.size() == 0)) {
        throw new IllegalArgumentException(
                "Illegal multipart argument definition (fileContent), received " + fCL);
    }
    InputStream fileContent = fCL.get(0).getBody(InputStream.class, null);

    if (fileName == null) {
        throw new IllegalArgumentException("Wrong file name : " + fileName);
    }

    filePath = normalizeFilePath(filePath, fileName);

    FileObject destfo = dataspaceRestApi.resolveFile(session, spaceName, filePath);

    URL targetUrl = destfo.getURL();
    logger.info("[pushFile] pushing file to " + targetUrl);

    if (!destfo.isWriteable()) {
        RuntimeException ex = new IllegalArgumentException(
                "File " + filePath + " is not writable in space " + spaceName);
        logger.error(ex);
        throw ex;
    }
    if (destfo.exists()) {
        destfo.delete();
    }
    // used to create the necessary directories if needed
    destfo.createFile();

    dataspaceRestApi.writeFile(fileContent, destfo, null);

    return true;
}

From source file:org.ow2.proactive_grid_cloud_portal.scheduler.SchedulerStateRest.java

/**
 * Deletes a file or recursively delete a directory from the given DataSpace
 * /*from ww w  .j  a v a 2 s  .c  o m*/
 * @param sessionId
 *            a valid session id
 * @param spaceName
 *            the name of the data space involved (GLOBAL or USER)
 * @param filePath
 *            the path to the file or directory which must be deleted
 **/
@Override
public boolean deleteFile(@HeaderParam("sessionid") String sessionId, @PathParam("spaceName") String spaceName,
        @PathParam("filePath") String filePath)
        throws IOException, NotConnectedRestException, PermissionRestException {
    checkAccess(sessionId, "deleteFile");

    Session session = dataspaceRestApi.checkSessionValidity(sessionId);

    filePath = normalizeFilePath(filePath, null);

    FileObject sourcefo = dataspaceRestApi.resolveFile(session, spaceName, filePath);

    if (!sourcefo.exists() || !sourcefo.isWriteable()) {
        RuntimeException ex = new IllegalArgumentException(
                "File or Folder " + filePath + " does not exist or is not writable in space " + spaceName);
        logger.error(ex);
        throw ex;
    }
    if (sourcefo.getType().equals(FileType.FILE)) {
        logger.info("[deleteFile] deleting file " + sourcefo.getURL());
        sourcefo.delete();
    } else if (sourcefo.getType().equals(FileType.FOLDER)) {
        logger.info("[deleteFile] deleting folder (and all its descendants) " + sourcefo.getURL());
        sourcefo.delete(Selectors.SELECT_ALL);
    } else {
        RuntimeException ex = new IllegalArgumentException(
                "File " + filePath + " has an unsupported type " + sourcefo.getType());
        logger.error(ex);
        throw ex;
    }
    return true;
}

From source file:org.renjin.primitives.files.Files.java

private static int checkAccess(FileObject file, int mode) throws FileSystemException {

    boolean ok = true;
    if ((mode & CHECK_ACCESS_EXISTENCE) != 0 && !file.exists()) {
        ok = false;/*www.ja va2  s .c om*/
    }

    if ((mode & CHECK_ACCESS_READ) != 0 && !file.isReadable()) {
        ok = false;
    }

    if ((mode & CHECK_ACCESS_WRITE) != 0 & !file.isWriteable()) {
        ok = false;
    }

    //case CHECK_ACCESS_EXECUTE:
    //      return -1; // don't know if this is possible to check with VFS
    //  }
    return ok ? 0 : -1;
}

From source file:org.renjin.primitives.files.Files.java

/**
  * Gets the type or storage mode of an object.
        /*from  w ww.j  a v a2  s. c  o m*/
  * @return  unix-style file mode integer
  */
private static int mode(FileObject file) throws FileSystemException {
    int access = 0;
    if (file.isReadable()) {
        access += 4;
    }

    if (file.isWriteable()) {
        access += 2;
    }
    if (file.getType() == FileType.FOLDER) {
        access += 1;
    }
    // i know this is braindead but i can't be bothered
    // to do octal math at the moment
    String digit = Integer.toString(access);
    String octalString = digit + digit + digit;

    return Integer.parseInt(octalString, 8);
}

From source file:tain.kr.test.vfs.v01.ShowProperties.java

private static void test01(String[] args) throws Exception {

    if (flag)/*from   ww w .  jav  a  2 s .  co  m*/
        new ShowProperties();

    if (flag) {

        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.vfs2.example.ShowProperties LICENSE.txt");
            return;
        }

        for (final String arg : args) {
            try {
                final FileSystemManager mgr = VFS.getManager();
                System.out.println();
                System.out.println("Parsing   : " + arg);
                final FileObject file = mgr.resolveFile(arg);
                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()) {

                        final 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 > SHOW_MAX) {
                                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 (final FileSystemException ex) {
                ex.printStackTrace();
            }
        }
    }
}