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.eobjects.datacleaner.user.DataCleanerHome.java

private static FileObject findDataCleanerHome() throws FileSystemException {
    final FileSystemManager manager = VFSUtils.getFileSystemManager();

    FileObject candidate = null;

    final String env = System.getenv("DATACLEANER_HOME");
    if (!StringUtils.isNullOrEmpty(env)) {
        candidate = manager.resolveFile(env);
        logger.info("Resolved env. variable DATACLEANER_HOME ({}) to: {}", env, candidate);
    }/*from   w  w w. j av a2  s .c om*/

    if (isUsable(candidate)) {
        return candidate;
    }

    if (ClassLoaderUtils.IS_WEB_START) {
        // in web start, the default folder will be in user.home
        final String userHomePath = System.getProperty("user.home");
        if (userHomePath == null) {
            throw new IllegalStateException("Could not determine user home directory: " + candidate);
        }

        final String path = userHomePath + File.separatorChar + ".datacleaner" + File.separatorChar
                + Version.getVersion();
        candidate = manager.resolveFile(path);
        logger.info("Running in WebStart mode. Attempting to build DATACLEANER_HOME in user.home: {} -> {}",
                path, candidate);
    } else {
        // in normal mode, the default folder will be in the working
        // directory
        candidate = manager.resolveFile(".");
        logger.info("Running in standard mode. Attempting to build DATACLEANER_HOME in '.' -> {}", candidate);
    }

    if ("true".equalsIgnoreCase(System.getProperty(SystemProperties.SANDBOX))) {
        logger.info("Running in sandbox mode ({}), setting {} as DATACLEANER_HOME", SystemProperties.SANDBOX,
                candidate);
        if (!candidate.exists()) {
            candidate.createFolder();
        }
        return candidate;
    }

    if (!isUsable(candidate)) {
        if (!candidate.exists()) {
            logger.debug("DATACLEANER_HOME directory does not exist, creating: {}", candidate);
            candidate.createFolder();
        }

        if (candidate.isWriteable()) {
            logger.debug("Copying default configuration and examples to DATACLEANER_HOME directory: {}",
                    candidate);
            copyIfNonExisting(candidate, manager, "conf.xml");
            copyIfNonExisting(candidate, manager, "examples/countrycodes.csv");
            copyIfNonExisting(candidate, manager, "examples/employees.analysis.xml");
            copyIfNonExisting(candidate, manager, "examples/duplicate_customer_detection.analysis.xml");
            copyIfNonExisting(candidate, manager, "examples/customer_data_cleansing.analysis.xml");
            copyIfNonExisting(candidate, manager, "examples/write_order_information.analysis.xml");
            copyIfNonExisting(candidate, manager, "examples/customer_data_completeness.analysis.xml");
        }
    }

    return candidate;
}

From source file:org.esupportail.portlet.filemanager.services.vfs.VfsAccessImpl.java

private JsTreeFile resourceAsJsTreeFile(FileObject resource, boolean folderDetails, boolean fileDetails,
        boolean showHiddenFiles) throws FileSystemException {
    String lid = resource.getName().getPath();
    String rootPath = this.root.getName().getPath();
    // lid must be a relative path from rootPath
    if (lid.startsWith(rootPath))
        lid = lid.substring(rootPath.length());
    if (lid.startsWith("/"))
        lid = lid.substring(1);//from  www .j a  v  a2  s . c  o m

    String title = "";
    String type = "drive";
    if (!"".equals(lid)) {
        type = resource.getType().getName();
        title = resource.getName().getBaseName();
    }
    JsTreeFile file = new JsTreeFile(title, lid, type);

    file.setHidden(this.isFileHidden(resource));

    if ("file".equals(type)) {
        String icon = resourceUtils.getIcon(title);
        file.setIcon(icon);
        file.setSize(resource.getContent().getSize());
        file.setOverSizeLimit(file.getSize() > resourceUtils.getSizeLimit(title));
    }

    try {
        if (folderDetails && ("folder".equals(type) || "drive".equals(type))) {
            if (resource.getChildren() != null) {
                long totalSize = 0;
                long fileCount = 0;
                long folderCount = 0;
                for (FileObject child : resource.getChildren()) {
                    if (showHiddenFiles || !this.isFileHidden(child)) {
                        if ("folder".equals(child.getType().getName())) {
                            ++folderCount;
                        } else if ("file".equals(child.getType().getName())) {
                            ++fileCount;
                            totalSize += child.getContent().getSize();
                        }
                    }
                }
                file.setTotalSize(totalSize);
                file.setFileCount(fileCount);
                file.setFolderCount(folderCount);
            }
        }

        final Calendar date = Calendar.getInstance();
        date.setTimeInMillis(resource.getContent().getLastModifiedTime());
        // In order to have a readable date
        file.setLastModifiedTime(new SimpleDateFormat(this.datePattern).format(date.getTime()));

        file.setReadable(resource.isReadable());
        file.setWriteable(resource.isWriteable());

    } catch (FileSystemException fse) {
        // we don't want that exception during retrieving details 
        // of the folder breaks  all this method ...
        log.error("Exception during retrieveing details on " + lid
                + " ... maybe broken symbolic links or whatever ...", fse);
    }

    return file;
}

From source file:org.mycore.backend.filesystem.MCRCStoreVFS.java

@Override
public void init(String storeId) {
    super.init(storeId);

    uri = MCRConfiguration.instance().getString(storeConfigPrefix + "URI");
    String check = MCRConfiguration.instance().getString(storeConfigPrefix + "StrictHostKeyChecking", "no");

    try {// w  w  w. ja v a2 s .co m
        fsManager = VFS.getManager();

        opts = new FileSystemOptions();
        SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, check);

        FileObject baseDir = getBase();

        // Create a folder, if it does not exist or throw an
        // exception, if baseDir is not a folder
        baseDir.createFolder();

        if (!baseDir.isWriteable()) {
            String msg = "Content store base directory is not writeable: " + uri;
            throw new MCRConfigurationException(msg);
        }
    } catch (FileSystemException ex) {
        throw new MCRException(ex.getCode(), ex);
    }
}

From source file:org.obiba.opal.core.service.ProjectsServiceImpl.java

private void deleteFolder(FileObject folder) throws FileSystemException {
    if (!folder.isWriteable())
        return;/* w  w w  .j a  v a2 s .c  o m*/

    for (FileObject file : folder.getChildren()) {
        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.FilesResource.java

/**
 * Copy or move a file to the current folder.
 *
 * @param path/*from w  w w .  j a  va  2 s. c  o  m*/
 * @param action 'copy' (default) or 'move'
 * @param file
 * @return
 * @throws IOException
 */
@PUT
@Path("/{path:.*}")
@AuthenticatedByCookie
public Response updateFile(@PathParam("path") String destinationPath,
        @QueryParam("action") @DefaultValue("copy") String action, @QueryParam("file") List<String> sourcesPath)
        throws IOException {

    // destination check
    FileObject destinationFile = resolveFileInFileSystem(destinationPath);
    if (!destinationFile.exists())
        getPathNotExistResponse(destinationPath);
    if (!destinationFile.isWriteable())
        return Response.status(Status.FORBIDDEN).entity("Destination file is not writable: " + destinationPath)
                .build();

    // sources check
    if (sourcesPath == null || sourcesPath.isEmpty())
        return Response.status(Status.BAD_REQUEST).entity("Source file is missing").build();

    // filter actions: copy, move
    if ("move".equals(action.toLowerCase())) {
        return moveTo(destinationFile, sourcesPath);
    }

    if ("copy".equals(action.toLowerCase())) {
        return copyFrom(destinationFile, sourcesPath);
    }

    return Response.status(Status.BAD_REQUEST).entity("Unexpected file action: " + action).build();
}

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

private Response moveTo(FileObject destinationFolder, Iterable<String> sourcesPath) throws IOException {
    // destination check
    String destinationPath = destinationFolder.getName().getPath();
    if (destinationFolder.getType() != FileType.FOLDER)
        return Response.status(Status.BAD_REQUEST).entity("Destination must be a folder: " + destinationPath)
                .build();//from   w w  w .j  a  v a 2s.  c o  m

    // sources check
    for (String sourcePath : sourcesPath) {
        FileObject sourceFile = resolveFileInFileSystem(sourcePath);
        if (!sourceFile.exists())
            getPathNotExistResponse(sourcePath);
        if (!sourceFile.isReadable()) {
            return Response.status(Status.FORBIDDEN).entity("Source file is not readable: " + sourcePath)
                    .build();
        }
        if (!sourceFile.isWriteable()) {
            return Response.status(Status.FORBIDDEN).entity("Source file cannot be moved: " + sourcePath)
                    .build();
        }
    }

    // do action
    for (String sourcePath : sourcesPath) {
        FileObject sourceFile = resolveFileInFileSystem(sourcePath);
        FileObject destinationFile = resolveFileInFileSystem(
                destinationPath + "/" + sourceFile.getName().getBaseName());
        sourceFile.moveTo(destinationFile);
    }

    return Response.ok().build();
}

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

@DELETE
@Path("/{path:.*}")
public Response deleteFile(@PathParam("path") String path) throws FileSystemException {
    FileObject file = resolveFileInFileSystem(path);

    // File or folder does not exist.
    if (!file.exists()) {
        return getPathNotExistResponse(path);
    }/*from w w  w  .j  a v  a 2  s .co m*/

    // Read-only file or folder.
    if (!file.isWriteable()) {
        return Response.status(Status.FORBIDDEN).entity("cannotDeleteReadOnlyFile").build();
    }

    try {
        if (file.getType() == FileType.FOLDER) {
            deleteFolder(file);
        } else {
            file.delete();
        }
        subjectAclService.deleteNodePermissions("/files/" + path);
        return Response.ok("The following file or folder has been deleted : " + path).build();
    } catch (FileSystemException couldNotDeleteFile) {
        return Response.status(Status.INTERNAL_SERVER_ERROR).entity("couldNotDeleteFileError").build();
    }
}

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

private Response getFileDetails(FileObject file) throws FileSystemException {
    Opal.FileDto.Builder fileBuilder;//  w  ww  .j  a v a 2  s .co  m

    fileBuilder = Opal.FileDto.newBuilder();
    fileBuilder.setName(file.getName().getBaseName()).setPath(file.getName().getPath());
    fileBuilder.setType(
            file.getType() == FileType.FILE ? Opal.FileDto.FileType.FILE : Opal.FileDto.FileType.FOLDER);
    fileBuilder.setReadable(file.isReadable()).setWritable(file.isWriteable());

    // Set size on files only, not folders.
    if (file.getType() == FileType.FILE) {
        fileBuilder.setSize(file.getContent().getSize());
    }

    fileBuilder.setLastModifiedTime(file.getContent().getLastModifiedTime());

    return Response.ok(fileBuilder.build()).build();
}

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

private Opal.FileDto.Builder getBaseFolderBuilder(FileObject folder) throws FileSystemException {
    Opal.FileDto.Builder fileBuilder = Opal.FileDto.newBuilder();
    String folderName = folder.getName().getBaseName();
    fileBuilder.setName("".equals(folderName) ? "root" : folderName).setType(Opal.FileDto.FileType.FOLDER)
            .setPath(folder.getName().getPath());
    fileBuilder.setLastModifiedTime(folder.getContent().getLastModifiedTime());
    fileBuilder.setReadable(folder.isReadable()).setWritable(folder.isWriteable());
    return fileBuilder;
}

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

private void addChildren(Opal.FileDto.Builder folderBuilder, FileObject parentFolder, int level)
        throws FileSystemException {
    Opal.FileDto.Builder fileBuilder;/*from   w  w  w  . ja va2  s  .c  om*/

    // 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());

        // Set size on files only, not folders.
        if (child.getType() == FileType.FILE) {
            fileBuilder.setSize(child.getContent().getSize());
        }

        fileBuilder.setLastModifiedTime(child.getContent().getLastModifiedTime());

        if (child.getType().hasChildren() && child.getChildren().length > 0 && level - 1 > 0
                && child.isReadable()) {
            addChildren(fileBuilder, child, level - 1);
        }

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