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

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

Introduction

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

Prototype

boolean exists() throws FileSystemException;

Source Link

Document

Determines if this file exists.

Usage

From source file:org.obiba.opal.web.magma.view.FileViewDtoExtension.java

@Override
public TableDto asTableDto(ViewDto viewDto, Magma.TableDto.Builder tableDtoBuilder) {
    FileViewDto fileDto = viewDto.getExtension(FileViewDto.view);
    try {/* w  w  w.java  2  s .  c o m*/
        FileObject file = opalRuntime.getFileSystem().getRoot().resolveFile(fileDto.getFilename());
        if (file.exists()) {
            try (InputStream is = file.getContent().getInputStream()) {
                return makeTableDtoFromFile(tableDtoBuilder, fileDto, is);
            }
        }
        throw new RuntimeException("cannot find file specified '" + fileDto.getFilename() + "'");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

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

@GET
@Path("/reports")
public List<Opal.ReportDto> getReports() throws FileSystemException {
    getReportTemplate();//  w w  w .  ja v a  2  s .c o  m
    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 .ja  v a2  s  .  co  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.onehippo.forge.content.exim.repository.jaxrs.AbstractContentEximService.java

/**
 * Return true if a stop signal file is found under the base folder.
 * @param baseFolder the base folder where zip content files are created temporarily.
 * @return true if a stop signal file is found under the base folder
 *//*  ww w.  j  a v a  2  s.co m*/
protected boolean isStopRequested(FileObject baseFolder) {
    try {
        FileObject stopSignalFile = baseFolder.resolveFile(STOP_REQUEST_FILE_REL_PATH);
        return stopSignalFile.exists();
    } catch (Exception e) {
        log.error("Failed to check stop request file.", e);
    }

    return false;
}

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

public FileObject createFile(String pathname) throws FileSystemException {
    FileObject fo = fsm.resolveFile(pathname);
    fo.refresh();/* ww  w  . ja v  a  2  s.c o  m*/
    if (!fo.exists()) {
        fo.createFile();
    }
    return fo;
}

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  w w  w  . ja  v  a2s . 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  w w.java 2  s .  c om
 * <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.dataspace.RestDataspaceImpl.java

/**
 * Retrieve metadata of file in the location specified in <i>dataspace</i>.
 * The format of the HEAD URI is:/*  ww w.ja  va2  s.c om*/
 * <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}
 *
 */
@HEAD
@Path("/{dataspace}/{path-name:.*}")
public Response metadata(@HeaderParam("sessionid") String sessionId,
        @PathParam("dataspace") String dataspacePath, @PathParam("path-name") String pathname)
        throws NotConnectedRestException, PermissionRestException {
    checkPathParams(dataspacePath, pathname);
    Session session = checkSessionValidity(sessionId);
    try {
        FileObject fo = resolveFile(session, dataspacePath, pathname);
        if (!fo.exists()) {
            return notFoundRes();
        }
        logger.debug(String.format("Retrieving metadata for %s in %s", pathname, dataspacePath));
        MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>(FileSystem.metadata(fo));
        return Response.ok().replaceAll(headers).build();
    } catch (Throwable error) {
        logger.error(String.format("Cannot retrieve metadata for %s in %s.", pathname, dataspacePath), error);
        throw rethrow(error);
    }
}

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

public void writeFile(InputStream inputStream, FileObject outputFile, String encoding)
        throws FileSystemException, IOException {
    try {//from w  w w.  j a v a2 s . co m
        if (outputFile.exists()) {
            outputFile.delete(SELECT_SELF);
        }
        if (Strings.isNullOrEmpty(encoding)) {
            outputFile.createFile();
            FileSystem.copy(inputStream, outputFile);
        } else if ("gzip".equals(encoding)) {
            VFSZipper.GZIP.unzip(inputStream, outputFile);
        } else if ("zip".equals(encoding)) {
            VFSZipper.ZIP.unzip(inputStream, outputFile);
        } else {
            outputFile.createFile();
            FileSystem.copy(inputStream, outputFile);
        }
    } catch (Throwable error) {
        if (outputFile != null) {
            try {
                if (outputFile.exists()) {
                    outputFile.delete(SELECT_SELF);
                }
            } catch (FileSystemException e1) {
                logger.error("Error occurred while deleting partially created file.", e1);
            }
        }
        Throwables.propagateIfInstanceOf(error, FileSystemException.class);
        Throwables.propagateIfInstanceOf(error, IOException.class);
        Throwables.propagate(error);
    }
}

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

/**
 * Pushes a file from the local file system into the given DataSpace
 * /*  ww  w  .  java 2s.c om*/
 * @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;
}