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

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

Introduction

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

Prototype

FileType getType() throws FileSystemException;

Source Link

Document

Returns this file's type.

Usage

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  w  w w  . j a  va2 s  .com

    // 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.obiba.opal.web.shell.reporting.ProjectReportTemplateResource.java

@GET
@Path("/reports")
public List<Opal.ReportDto> getReports() throws FileSystemException {
    getReportTemplate();/*www . j av a2  s .c  om*/
    FileObject reportFolder = getReportFolder();
    List<Opal.ReportDto> reports = Lists.newArrayList();
    if (reportFolder.exists()) {
        for (FileObject reportFile : reportFolder.getChildren()) {
            if (reportFile.getType() == FileType.FILE
                    && reportFile.getName().getBaseName().startsWith(name + "-") && reportFile.isReadable()) {
                reports.add(getReportDto(reportFile));
            }
        }
    }
    return reports;
}

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

@GET
@Path("/reports/latest")
public Response getReport() throws FileSystemException {
    getReportTemplate();/*w w  w.j  a  v a2  s .  c  o  m*/

    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.dataspace.FileSystem.java

public static ListFile list(FileObject fo, List<String> includes, List<String> excludes)
        throws FileSystemException {
    fo.refresh();//from   w  w  w.  ja va2s  . com
    ListFile answer = new ListFile();
    List<String> dirList = Lists.newArrayList();
    List<String> fileList = Lists.newArrayList();
    List<String> fullList = Lists.newArrayList();
    List<FileObject> foundFileObjects = new LinkedList<>();
    if (isNullOrEmpty(includes) && isNullOrEmpty(excludes)) {
        fo.findFiles(Selectors.SELECT_CHILDREN, false, foundFileObjects);
    } else {
        FileSelector selector = new org.objectweb.proactive.extensions.dataspaces.vfs.selector.FileSelector(
                includes, excludes);
        fo.findFiles(selector, false, foundFileObjects);
    }

    for (FileObject child : foundFileObjects) {
        FileType type = child.getType();
        FileName childName = child.getName();
        switch (type) {
        case FOLDER:
            if (!child.equals(fo)) {
                // exclude root directory from the list
                String relativePath = fo.getName().getRelativeName(childName);
                dirList.add(relativePath);
                fullList.add(relativePath);
            }
            break;
        case FILE:
            String relativePath = fo.getName().getRelativeName(childName);
            fileList.add(relativePath);
            fullList.add(relativePath);
            break;
        default:
            throw new RuntimeException("Unknown : " + type);
        }
    }
    Collections.sort(dirList);
    Collections.sort(fileList);
    Collections.sort(fullList);
    answer.setDirectoryListing(dirList);
    answer.setFileListing(fileList);
    answer.setFullListing(fullList);
    return answer;
}

From source file:org.ow2.proactive_grid_cloud_portal.dataspace.FileSystem.java

public static Map<String, Object> metadata(FileObject fo) throws FileSystemException {
    Map<String, Object> props = Maps.newHashMap();
    switch (fo.getType()) {
    case FOLDER://from  ww  w  . j  a  v  a2s.c o m
        fillDirProps(fo, props);
        break;
    case FILE:
        fillFileProps(fo, props);
        break;
    default:
        throw new RuntimeException("Unknown location.");
    }
    return props;
}

From source file:org.ow2.proactive_grid_cloud_portal.dataspace.RestDataspaceImpl.java

/**
 * Retrieves single or multiple files from specified location of the server.
 * The format of the GET URI is:/*from  ww  w .  ja va2  s .  c  om*/
 * <P>
 * {@code http://<rest-server-path>/data/<dataspace>/<path-name>}
 * <p>
 * Example:
 * <p>
 * {@code http://localhost:8080/rest/rest/data/user/my-files/my-text-file.txt}
 * <ul>
 * <li>dataspace: can have two possible values, 'user' or 'global',
 * depending on the target <i>DATASPACE</i></li>
 * <li>path-name: location from which the file will be retrieved.</li>
 * </ul>
 * <b>Notes:</b>
 * <ul>
 * <li>If 'list' is specified as the 'comp' query parameter, an
 * {@link ListFile} type object will be return in JSON format. It will contain a list of files and folder contained in the selected
 * path.
 * </li>
 * <li>If 'recursive' is specified as the 'comp' query parameter, an
 * {@link ListFile} type object will be return in JSON format. It will contain a list of files and folder contained in the selected
 * path and all subfolders.
 * </li>
 * <li>If the pathname represents a file its contents will be returned as:
 * <ul>
 * <li>an octet stream, if its a compressed file or the client doesn't
 * accept encoded content</li>
 * <li>a 'gzip' encoded stream, if the client accepts 'gzip' encoded content
 * </li>
 * <li>a 'zip' encoded stream, if the client accepts 'zip' encoded contents</li>
 * </ul>
 * </li>
 * <li>If the pathname represents a directory, its contents will be returned
 * as 'zip' encoded stream.</li>
 * <li>file names or regular expressions can be used as 'includes' and
 * 'excludes' query parameters, in order to select which files to be
 * returned can be used to select the files returned.</li>
 * </ul>
 */
@GET
@Path("/{dataspace}/{path-name:.*}")
public Response retrieve(@HeaderParam("sessionid") String sessionId,
        @HeaderParam("Accept-Encoding") String encoding, @PathParam("dataspace") String dataspace,
        @PathParam("path-name") String pathname, @QueryParam("comp") String component,
        @QueryParam("includes") List<String> includes, @QueryParam("excludes") List<String> excludes)
        throws NotConnectedRestException, PermissionRestException {
    checkPathParams(dataspace, pathname);
    Session session = checkSessionValidity(sessionId);
    try {
        FileObject fo = resolveFile(session, dataspace, pathname);

        if (!fo.exists()) {
            return notFoundRes();
        }
        if (!Strings.isNullOrEmpty(component)) {
            return componentResponse(component, fo, includes, excludes);
        }
        if (fo.getType() == FileType.FILE) {
            if (VFSZipper.isZipFile(fo)) {
                logger.debug(String.format("Retrieving file %s in %s", pathname, dataspace));
                return fileComponentResponse(fo);
            } else if (Strings.isNullOrEmpty(encoding) || encoding.contains("*") || encoding.contains("gzip")) {
                logger.debug(String.format("Retrieving file %s as gzip in %s", pathname, dataspace));
                return gzipComponentResponse(pathname, fo);
            } else if (encoding.contains("zip")) {
                logger.debug(String.format("Retrieving file %s as zip in %s", pathname, dataspace));
                return zipComponentResponse(fo, null, null);
            } else {
                logger.debug(String.format("Retrieving file %s in %s", pathname, dataspace));
                return fileComponentResponse(fo);
            }
        } else {
            // folder
            if (Strings.isNullOrEmpty(encoding) || encoding.contains("*") || encoding.contains("zip")) {
                logger.debug(String.format("Retrieving folder %s as zip in %s", pathname, dataspace));
                return zipComponentResponse(fo, includes, excludes);
            } else {
                return badRequestRes("Folder retrieval only supported with zip encoding.");
            }
        }
    } catch (Throwable error) {
        logger.error(String.format("Cannot retrieve %s in %s.", pathname, dataspace), error);
        throw rethrow(error);
    }
}

From source file:org.ow2.proactive_grid_cloud_portal.dataspace.RestDataspaceImpl.java

/**
 * Delete file(s) from the specified location in the <i>dataspace</i>. The
 * format of the DELETE URI is://from  w  ww.  j a va 2  s  .co  m
 * <p>
 * {@code http://<rest-server-path>/data/<dataspace>/<path-name>}
 * <p>
 * Example:
 * {@code http://localhost:8080/rest/rest/data/user/my-files/my-text-file.txt}
 * <ul>
 * <li>dataspace: can have two possible values, 'user' or 'global',
 * depending on the target <i>DATASPACE</i></li>
 * <li>path-name: location of the file(s) to be deleted.</li>
 * </ul>
 * <b>Notes:</b>
 * <ul>
 * <li>Only empty directories can be deleted.</li>
 * <li>File names or regular expressions can be used as 'includes' and
 * 'excludes' query parameters, in order to select which files to be deleted
 * inside the specified directory (path-name).</li>
 * </ul>
 *
 */
@DELETE
@Path("/{dataspace}/{path-name:.*}")
public Response delete(@HeaderParam("sessionid") String sessionId, @PathParam("dataspace") String dataspace,
        @PathParam("path-name") String pathname, @QueryParam("includes") List<String> includes,
        @QueryParam("excludes") List<String> excludes)
        throws NotConnectedRestException, PermissionRestException {
    checkPathParams(dataspace, pathname);
    Session session = checkSessionValidity(sessionId);

    try {
        FileObject fo = resolveFile(session, dataspace, pathname);

        if (!fo.exists()) {
            return Response.status(Response.Status.NO_CONTENT).build();
        }
        if (fo.getType() == FileType.FOLDER) {
            logger.debug(String.format("Deleting directory %s in %s", pathname, dataspace));
            return deleteDir(fo, includes, excludes);
        } else {
            logger.debug(String.format("Deleting file %s in %s", pathname, dataspace));
            fo.close();
            return fo.delete() ? noContentRes() : serverErrorRes("Cannot delete the file: %s", pathname);
        }
    } catch (Throwable error) {
        logger.error(String.format("Cannot delete %s in %s.", pathname, dataspace), error);
        throw rethrow(error);
    }
}

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/*  ww w  .  j av  a  2 s . 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.ow2.proactive_grid_cloud_portal.scheduler.SchedulerStateRest.java

/**
 * Deletes a file or recursively delete a directory from the given DataSpace
 * //from  w  w  w  .j a v  a 2  s  . 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 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.pentaho.di.core.hadoop.HadoopConfigurationBootstrap.java

public synchronized List<HadoopConfigurationInfo> getHadoopConfigurationInfos()
        throws KettleException, ConfigurationException, IOException {
    List<HadoopConfigurationInfo> result = new ArrayList<>();
    FileObject hadoopConfigurationsDir = resolveHadoopConfigurationsDirectory();
    // If the folder doesn't exist, return an empty list
    if (hadoopConfigurationsDir.exists()) {
        String activeId = getActiveConfigurationId();
        String willBeActiveId = getWillBeActiveConfigurationId();
        for (FileObject childFolder : hadoopConfigurationsDir.getChildren()) {
            if (childFolder.getType() == FileType.FOLDER) {
                String id = childFolder.getName().getBaseName();
                FileObject configPropertiesFile = childFolder.getChild(CONFIG_PROPERTIES);
                if (configPropertiesFile.exists()) {
                    Properties properties = new Properties();
                    properties.load(configPropertiesFile.getContent().getInputStream());
                    result.add(new HadoopConfigurationInfo(id, properties.getProperty("name", id),
                            id.equals(activeId), willBeActiveId.equals(id)));
                }/* ww  w  .  j  a v  a  2 s . com*/
            }
        }
    }
    return result;
}