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

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

Introduction

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

Prototype

boolean isFile() throws FileSystemException;

Source Link

Document

Checks if this file is a regular file.

Usage

From source file:com.sonicle.webtop.vfs.PublicService.java

private void writeStoreFile(HttpServletResponse response, int storeId, String filePath, String outFileName) {
    try {// ww w.jav a2  s  .c  o m
        FileObject fo = null;
        try {
            fo = manager.getStoreFile(storeId, filePath);

            if (fo.isFile()) {
                String mediaType = ServletHelper.guessMediaType(fo.getName().getBaseName(), true);
                ServletUtils.setFileStreamHeaders(response, mediaType, DispositionType.ATTACHMENT, outFileName);
                ServletUtils.setContentLengthHeader(response, fo.getContent().getSize());
                IOUtils.copy(fo.getContent().getInputStream(), response.getOutputStream());

            } else if (fo.isFolder()) {
                ServletUtils.setFileStreamHeaders(response, "application/zip", DispositionType.ATTACHMENT,
                        outFileName);

                ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
                try {
                    VfsUtils.zipFileObject(fo, zos, true);
                    zos.flush();
                } finally {
                    IOUtils.closeQuietly(zos);
                }
            }

        } finally {
            IOUtils.closeQuietly(fo);
        }

    } catch (Exception ex) {
        logger.error("Error in DownloadFile", ex);
        ServletUtils.sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.sonicle.webtop.vfs.Service.java

public void processDownloadFiles(HttpServletRequest request, HttpServletResponse response) {

    try {/*ww w . j  a v a2 s.c o m*/
        StringArray fileIds = ServletUtils.getObjectParameter(request, "fileIds", StringArray.class, true);

        if (fileIds.size() > 1)
            throw new WTException("Unable to download multiple files for now");
        String fileId = fileIds.get(0);
        //TODO: Implementare download file multipli

        StoreNodeId nodeId = (StoreNodeId) new StoreNodeId().parse(fileId);
        int storeId = Integer.valueOf(nodeId.getStoreId());

        FileObject fo = null;
        try {
            fo = manager.getStoreFile(storeId, nodeId.getPath());

            if (!fo.isFile()) {
                logger.warn("Cannot download a non-file [{}, {}]", storeId, nodeId.getPath());
                throw new WTException("Requested file is not a real file");
            }

            String filename = fo.getName().getBaseName();
            String mediaType = ServletHelper.guessMediaType(filename, true);
            IOUtils.copy(fo.getContent().getInputStream(), response.getOutputStream());
            ServletUtils.setFileStreamHeaders(response, mediaType, DispositionType.ATTACHMENT, filename);
            ServletUtils.setContentLengthHeader(response, fo.getContent().getSize());
        } finally {
            IOUtils.closeQuietly(fo);
        }

    } catch (Exception ex) {
        logger.error("Error in action DownloadFiles", ex);
        ServletUtils.writeErrorHandlingJs(response, ex.getMessage());
    }
}

From source file:maspack.fileutil.FileCacher.java

public File cache(URIx uri, File cacheFile, FileTransferMonitor monitor) throws FileSystemException {

    // For atomic operation, first download to temporary directory
    File tmpCacheFile = new File(cacheFile.getAbsolutePath() + TMP_EXTENSION);
    URIx cacheURI = new URIx(cacheFile.getAbsoluteFile());
    URIx tmpCacheURI = new URIx(tmpCacheFile.getAbsoluteFile());
    FileObject localTempFile = manager.resolveFile(tmpCacheURI.toString(true));
    FileObject localCacheFile = manager.resolveFile(cacheURI.toString(true));

    FileObject remoteFile = null; // will resolve next

    // loop through authenticators until we either succeed or cancel
    boolean cancel = false;
    while (remoteFile == null && cancel == false) {
        remoteFile = resolveRemote(uri);
    }/*  w ww  . ja v a 2 s  .  c o m*/

    if (remoteFile == null || !remoteFile.exists()) {
        throw new FileSystemException("Cannot find remote file <" + uri.toString() + ">",
                new FileNotFoundException("<" + uri.toString() + ">"));
    }

    // monitor the file transfer progress
    if (monitor != null) {
        monitor.monitor(localTempFile, remoteFile, -1, cacheFile.getName());
        monitor.start();
        monitor.fireStartEvent(localTempFile);
    }

    // transfer content
    try {
        if (remoteFile.isFile()) {
            localTempFile.copyFrom(remoteFile, Selectors.SELECT_SELF);
        } else if (remoteFile.isFolder()) {
            // final FileObject fileSystem = manager.createFileSystem(remoteFile);
            localTempFile.copyFrom(remoteFile, new AllFileSelector());
            // fileSystem.close();
        }

        if (monitor != null) {
            monitor.fireCompleteEvent(localTempFile);
        }
    } catch (Exception e) {
        // try to delete local file
        localTempFile.delete();
        throw new RuntimeException(
                "Failed to complete transfer of " + remoteFile.getURL() + " to " + localTempFile.getURL(), e);
    } finally {
        // close files if we need to
        localTempFile.close();
        remoteFile.close();
        if (monitor != null) {
            monitor.release(localTempFile);
            monitor.stop();
        }

    }

    // now that the copy is complete, do a rename operation
    try {
        if (tmpCacheFile.isDirectory()) {
            SafeFileUtils.moveDirectory(tmpCacheFile, cacheFile);
        } else {
            SafeFileUtils.moveFile(tmpCacheFile, cacheFile);
        }
    } catch (Exception e) {
        localCacheFile.delete(); // delete if possible
        throw new RuntimeException("Failed to atomically move " + "to " + localCacheFile.getURL(), e);
    }

    return cacheFile;

}

From source file:maspack.fileutil.FileCacher.java

public boolean copy(URIx from, URIx to, FileTransferMonitor monitor) throws FileSystemException {

    FileObject fromFile = null;
    FileObject toFile = null;//from   w  ww  .j a  va  2  s.c o m

    // clear authenticators
    setAuthenticator(fsOpts, null);
    setIdentityFactory(fsOpts, null);

    // loop through authenticators until we either succeed or cancel
    boolean cancel = false;
    while (toFile == null && cancel == false) {
        toFile = resolveRemote(to);
    }

    cancel = false;
    while (fromFile == null && cancel == false) {
        fromFile = resolveRemote(from);
    }

    if (fromFile == null || !fromFile.exists()) {
        throw new FileSystemException("Cannot find source file <" + from.toString() + ">",
                new FileNotFoundException("<" + from.toString() + ">"));
    }

    if (toFile == null) {
        throw new FileSystemException("Cannot find destination <" + to.toString() + ">",
                new FileNotFoundException("<" + to.toString() + ">"));
    }

    // monitor the file transfer progress
    if (monitor != null) {
        monitor.monitor(fromFile, toFile, -1, fromFile.getName().getBaseName());
        monitor.start();
        monitor.fireStartEvent(toFile);
    }

    // transfer content
    try {
        if (fromFile.isFile()) {
            toFile.copyFrom(fromFile, Selectors.SELECT_SELF);
        } else if (fromFile.isFolder()) {
            // final FileObject fileSystem = manager.createFileSystem(remoteFile);
            toFile.copyFrom(fromFile, new AllFileSelector());
            // fileSystem.close();
        }

        if (monitor != null) {
            monitor.fireCompleteEvent(toFile);
        }
    } catch (Exception e) {
        throw new FileTransferException(
                "Failed to complete transfer of " + fromFile.getURL() + " to " + toFile.getURL(), e);
    } finally {
        // close files if we need to
        fromFile.close();
        toFile.close();
        if (monitor != null) {
            monitor.release(toFile);
            monitor.stop();
        }
    }

    return true;

}

From source file:org.luwrain.app.commander.InfoAndProperties.java

static public long getTotalSize(FileObject fileObj) throws org.apache.commons.vfs2.FileSystemException {
    NullCheck.notNull(fileObj, "fileObj");
    if (!fileObj.isFolder() && !fileObj.isFile())
        return 0;
    if (fileObj instanceof org.apache.commons.vfs2.provider.local.LocalFile
            && java.nio.file.Files.isSymbolicLink(java.nio.file.Paths.get(fileObj.getName().getPath())))
        return 0;
    if (!fileObj.isFolder())
        return fileObj.getContent().getSize();
    long res = 0;
    for (FileObject child : fileObj.getChildren())
        res += getTotalSize(child);/*  w w w  .j  ava 2s. c om*/
    return res;
}

From source file:org.pentaho.di.trans.steps.pentahoreporting.urlrepository.FileObjectContentLocation.java

/**
 * Lists all content entities stored in this content-location. This method filters out all files that have an invalid
 * name (according to the repository rules).
 *
 * @return the content entities for this location.
 * @throws ContentIOException if an repository error occured.
 *///from  www . j  a  v  a2s  .  c o  m
public ContentEntity[] listContents() throws ContentIOException {
    try {
        final FileObject file = getBackend();
        final FileObject[] files = file.getChildren();
        final ContentEntity[] entities = new ContentEntity[files.length];
        for (int i = 0; i < files.length; i++) {
            final FileObject child = files[i];
            if (RepositoryUtilities.isInvalidPathName(child.getPublicURIString())) {
                continue;
            }

            if (child.isFolder()) {
                entities[i] = new FileObjectContentLocation(this, child);
            } else if (child.isFile()) {
                entities[i] = new FileObjectContentLocation(this, child);
            }
        }
        return entities;
    } catch (FileSystemException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.pentaho.di.trans.steps.pentahoreporting.urlrepository.FileObjectContentLocation.java

/**
 * Returns the content entity with the given name. If the entity does not exist, an Exception will be raised.
 *
 * @param name the name of the entity to be retrieved.
 * @return the content entity for this name, never null.
 * @throws ContentIOException if an repository error occured.
 *//*from w  ww . java2  s  .co m*/
public ContentEntity getEntry(final String name) throws ContentIOException {
    try {
        if (RepositoryUtilities.isInvalidPathName(name)) {
            throw new IllegalArgumentException("The name given is not valid.");
        }

        final FileObject file = getBackend();
        final FileObject child = file.resolveFile(name);
        if (child.exists() == false) {
            throw new ContentIOException("Not found:" + child);
        }

        if (child.isFolder()) {
            return new FileObjectContentLocation(this, child);
        } else if (child.isFile()) {
            return new FileObjectContentItem(this, child);
        } else {
            throw new ContentIOException("Not File nor directory.");
        }
    } catch (FileSystemException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.pentaho.hadoop.shim.common.format.avro.PentahoAvroInputFormat.java

private DataFileStream<GenericRecord> createDataFileStream(String schemaFileName, String fileName)
        throws Exception {
    DatumReader<GenericRecord> datumReader;
    if (schemaFileName != null && schemaFileName.length() > 0) {
        datumReader = new GenericDatumReader<GenericRecord>(readAvroSchema(schemaFileName));
    } else {//from   ww w  . jav a2  s.  co  m
        datumReader = new GenericDatumReader<GenericRecord>();
    }
    FileObject fileObject = KettleVFS.getFileObject(fileName);
    if (fileObject.isFile()) {
        return new DataFileStream<GenericRecord>(fileObject.getContent().getInputStream(), datumReader);
    } else {
        FileObject[] avroFiles = fileObject.findFiles(new FileExtensionSelector("avro"));
        if (!Utils.isEmpty(avroFiles)) {
            return new DataFileStream<GenericRecord>(avroFiles[0].getContent().getInputStream(), datumReader);
        }
        return null;
    }
}

From source file:org.pentaho.metaverse.impl.VfsLineageWriter.java

protected FileObject getOutputDirectoryAsFile(LineageHolder holder) {
    try {//from   ww w . j a va  2 s .c  o  m
        FileObject dateRootFolder = getDateFolder(holder);
        dateRootFolder.createFolder();
        String id = holder.getId() == null ? "unknown_artifact" : holder.getId();
        if (id.startsWith(File.separator)) { // For *nix
            id = id.substring(1);
        } else if (Const.isWindows() && id.charAt(1) == ':') { // For windows
            id = id.replaceFirst(Pattern.quote(":"), "");
        }
        try {
            FileObject folder = dateRootFolder.resolveFile(id);
            folder.createFolder();
            if (folder.isFile()) {
                // must be a folder
                throw new IllegalStateException(
                        Messages.getErrorString("ERROR.OutputFolderWrongType", folder.getName().getPath()));
            }
            return folder;
        } catch (Exception e) {
            log.error(Messages.getErrorString("ERROR.CouldNotCreateFile"), e);
            return null;
        }
    } catch (Exception e) {
        log.error(Messages.getErrorString("ERROR.CouldNotCreateFile"), e);
        throw new IllegalStateException(e);
    }
}