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

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

Introduction

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

Prototype

boolean isReadable() throws FileSystemException;

Source Link

Document

Determines if this file can be read.

Usage

From source file:org.obiba.opal.web.shell.reporting.ProjectReportTemplateResource.java

@GET
@Path("/reports/latest")
public Response getReport() throws FileSystemException {
    getReportTemplate();//  w ww. j  a va  2  s  .  com

    FileObject reportFolder = getReportFolder();
    if (!reportFolder.exists()) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }

    FileObject lastReportFile = null;
    File lastReport = null;
    for (FileObject reportFile : reportFolder.getChildren()) {
        if (reportFile.getType() == FileType.FILE && reportFile.getName().getBaseName().startsWith(name + "-")
                && reportFile.isReadable()) {
            File report = opalRuntime.getFileSystem().getLocalFile(reportFile);
            if (lastReport == null || report.lastModified() > lastReport.lastModified()) {
                lastReport = report;
                lastReportFile = reportFile;
            }
        }
    }

    return lastReportFile == null ? Response.status(Response.Status.NOT_FOUND).build()
            : Response.ok(getReportDto(lastReportFile)).build();
}

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

/**
 * Either Pulls a file from the given DataSpace to the local file system or
 * list the content of a directory if the path refers to a directory In the
 * case the path to a file is given, the content of this file will be
 * returns as an input stream In the case the path to a directory is given,
 * the input stream returned will be a text stream containing at each line
 * the content of the directory//from   w ww.  ja  v  a2s.com
 * 
 * @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 whose content must be
 *            received
 **/
@Override
public InputStream pullFile(@HeaderParam("sessionid") String sessionId,
        @PathParam("spaceName") String spaceName, @PathParam("filePath") String filePath)
        throws IOException, NotConnectedRestException, PermissionRestException {

    checkAccess(sessionId, "pullFile");
    Session session = dataspaceRestApi.checkSessionValidity(sessionId);

    filePath = normalizeFilePath(filePath, null);

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

    if (!sourcefo.exists() || !sourcefo.isReadable()) {
        RuntimeException ex = new IllegalArgumentException(
                "File " + filePath + " does not exist or is not readable in space " + spaceName);
        logger.error(ex);
        throw ex;
    }

    if (sourcefo.getType().equals(FileType.FOLDER)) {
        logger.info("[pullFile] reading directory content from " + sourcefo.getURL());
        // if it's a folder we return an InputStream listing its content
        StringBuilder sb = new StringBuilder();
        String nl = System.lineSeparator();
        for (FileObject fo : sourcefo.getChildren()) {
            sb.append(fo.getName().getBaseName() + nl);

        }
        return IOUtils.toInputStream(sb.toString());

    } else if (sourcefo.getType().equals(FileType.FILE)) {
        logger.info("[pullFile] reading file content from " + sourcefo.getURL());
        return sourcefo.getContent().getInputStream();
    } else {
        RuntimeException ex = new IllegalArgumentException(
                "File " + filePath + " has an unsupported type " + sourcefo.getType());
        logger.error(ex);
        throw ex;
    }

}

From source file:org.pentaho.reporting.engine.classic.extensions.datasources.mondrian.SchemaResolver.java

public static String resolveSchema(final ResourceManager resourceManager, final ResourceKey contextKey,
        String catalogUrl) throws FileSystemException {
    final FileSystemManager fsManager = VFS.getManager();
    if (fsManager == null) {
        throw Util.newError("Cannot get virtual file system manager");
    }/*from   w w  w.j  a v  a 2  s  .  c  o m*/

    // Workaround VFS bug.
    if (catalogUrl.startsWith("file://localhost")) {
        catalogUrl = catalogUrl.substring("file://localhost".length());
    }
    if (catalogUrl.startsWith("file:")) {
        catalogUrl = catalogUrl.substring("file:".length());
    }

    try {
        final File catalogFile = new File(catalogUrl).getCanonicalFile();
        final FileObject file = fsManager.toFileObject(catalogFile);
        if (file.isReadable()) {
            return catalogFile.getPath();
        }
    } catch (FileSystemException fse) {
        logger.info("Failed to resolve schema file '" + catalogUrl
                + "' as local file. Treating file as non-readable.", fse);
    } catch (IOException e) {
        logger.info("Failed to resolve schema file '" + catalogUrl
                + "' as local file. Treating file as non-readable.", e);
    }

    if (contextKey == null) {
        return catalogUrl;
    }

    final File contextAsFile = getContextAsFile(contextKey);
    if (contextAsFile == null) {
        return catalogUrl;
    }

    final File resolvedFile = new File(contextAsFile.getParentFile(), catalogUrl);
    if (resolvedFile.isFile() && resolvedFile.canRead()) {
        return resolvedFile.getAbsolutePath();
    }

    return catalogUrl;
}

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;/* w w  w.  j  a v a 2  s . co m*/
    }

    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  ww w.j  ava 2 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:org.wso2.carbon.inbound.endpoint.protocol.file.FilePollingConsumer.java

/**
 * /*  ww w. jav a 2s .co m*/
 * Do the file processing operation for the given set of properties. Do the
 * checks and pass the control to processFile method
 * 
 * */
public FileObject poll() {
    if (fileURI == null || fileURI.trim().equals("")) {
        log.error("Invalid file url. Check the inbound endpoint configuration. Endpoint Name : " + name
                + ", File URL : " + VFSUtils.maskURLPassword(fileURI));
        return null;
    }

    if (log.isDebugEnabled()) {
        log.debug("Start : Scanning directory or file : " + VFSUtils.maskURLPassword(fileURI));
    }

    if (!initFileCheck()) {
        // Unable to read from the source location provided.
        return null;
    }

    // If file/folder found proceed to the processing stage
    try {
        lastCycle = 0;
        if (fileObject.exists() && fileObject.isReadable()) {
            FileObject[] children = null;
            try {
                children = fileObject.getChildren();
            } catch (FileNotFolderException ignored) {
                if (log.isDebugEnabled()) {
                    log.debug("No Folder found. Only file found on : " + VFSUtils.maskURLPassword(fileURI));
                }
            } catch (FileSystemException ex) {
                log.error(ex.getMessage(), ex);
            }

            // if this is a file that would translate to a single message
            if (children == null || children.length == 0) {
                // Fail record is a one that is processed but was not moved
                // or deleted due to an error.
                boolean isFailedRecord = VFSUtils.isFailRecord(fsManager, fileObject);
                if (!isFailedRecord) {
                    fileHandler();
                    if (injectHandler == null) {
                        return fileObject;
                    }
                } else {
                    try {
                        lastCycle = 2;
                        moveOrDeleteAfterProcessing(fileObject);
                    } catch (SynapseException synapseException) {
                        log.error("File object '" + VFSUtils.maskURLPassword(fileObject.getURL().toString())
                                + "' " + "cloud not be moved after first attempt", synapseException);
                    }
                    if (fileLock) {
                        // TODO: passing null to avoid build break. Fix properly
                        VFSUtils.releaseLock(fsManager, fileObject, fso);
                    }
                    if (log.isDebugEnabled()) {
                        log.debug("File '" + VFSUtils.maskURLPassword(fileObject.getURL().toString())
                                + "' has been marked as a failed" + " record, it will not process");
                    }
                }
            } else {
                FileObject fileObject = directoryHandler(children);
                if (fileObject != null) {
                    return fileObject;
                }
            }
        } else {
            log.warn("Unable to access or read file or directory : " + VFSUtils.maskURLPassword(fileURI) + "."
                    + " Reason: "
                    + (fileObject.exists()
                            ? (fileObject.isReadable() ? "Unknown reason" : "The file can not be read!")
                            : "The file does not exists!"));
            return null;
        }
    } catch (FileSystemException e) {
        log.error("Error checking for existence and readability : " + VFSUtils.maskURLPassword(fileURI), e);
        return null;
    } catch (Exception e) {
        log.error("Error while processing the file/folder in URL : " + VFSUtils.maskURLPassword(fileURI), e);
        return null;
    } finally {
        try {
            if (fsManager != null) {
                fsManager.closeFileSystem(fileObject.getParent().getFileSystem());
            }
            fileObject.close();
        } catch (Exception e) {
            log.error("Unable to close the file system. " + e.getMessage());
            log.error(e);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("End : Scanning directory or file : " + VFSUtils.maskURLPassword(fileURI));
    }
    return null;
}

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

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

    if (flag)/*from   w w  w  .  j  a va 2 s .  c  o 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();
            }
        }
    }
}