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

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

Introduction

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

Prototype

FileObject[] getChildren() throws FileSystemException;

Source Link

Document

Lists the children of this file.

Usage

From source file:org.clever.ClusterManager.StorageManagerPlugins.StorageManagerClever.StorageManager.java

/**
 * This method checks if a directory has child nodes (VirtualizationManager)
 * Is necessary to differentiate the two cases: creatVM and registerVM (HYP)
 * @param path/*  w w  w.j a va2 s . c o m*/
 * @return
 * @throws Exception 
 */
@Override
public boolean check(String path) throws Exception {

    VFSDescription vfsD = discoveryNode(path, "");
    VirtualFileSystem a = new VirtualFileSystem();
    a.setURI(vfsD);
    FileObject file = a.resolver(vfsD, a.getURI(), vfsD.getPath1());

    FileObject[] children = file.getChildren();

    if (file.getType().equals(FileType.FOLDER) && children.length > 0) {
        return false;
    }

    return true;

}

From source file:org.clever.Common.Storage.VirtualFileSystem.java

/**
 * This method lists contents of a file or folder
 * @param file//w ww . j  a  v a 2  s .c o m
 * @return
 * @throws FileSystemException 
 */
public String ls(FileObject file) throws FileSystemException {
    String str = "Contents of " + file.getName() + "\n";
    if (file.exists()) {
        if (file.getType().equals(FileType.FILE)) {
            str = str + "Size: " + file.getContent().getSize() + " bytes\n" + "Last modified: "
                    + DateFormat.getInstance().format(new Date(file.getContent().getLastModifiedTime())) + "\n"
                    + "Readable: " + file.isReadable() + "\n" + "Writeable: " + file.isWriteable() + "\n";
            return str;
        } else if (file.getType().equals(FileType.FOLDER) && file.isReadable()) {
            FileObject[] children = file.getChildren();
            str = str = "Directory with " + children.length + " files \n" + "Readable: " + file.isReadable()
                    + "\n" + "Writeable: " + file.isWriteable() + "\n\n";
            //str=str+"Last modified: " +DateFormat.getInstance().format(new Date(file.getContent().getLastModifiedTime()))+"\n" ;
            for (int i = 0; i < children.length; i++) {
                str = str + children[i].getName().getBaseName() + "\n";
            }
        }
    } else {
        str = str + "The file does not exist";
    }
    return str;
}

From source file:org.codehaus.mojo.vfs.internal.DefaultVfsDirectoryScanner.java

/**
 * Scans the given directory for files and directories. Found files are placed in a collection, based on the
 * matching of includes, excludes, and the selectors. When a directory is found, it is scanned recursively.
 *
 * @throws FileSystemException/*from  w ww.ja va2 s .co  m*/
 * @see #includedFiles
 */
private void scanSubDir(FileObject dir, String relativePath) throws FileSystemException {

    FileObject[] children = dir.getChildren();

    for (FileObject child : children) {
        String newRelativePath = child.getName().getBaseName();
        if (!relativePath.isEmpty()) {
            newRelativePath = relativePath + "/" + child.getName().getBaseName();
        }

        if (this.isDirectory(child)) {
            if (!surelyExcluded(newRelativePath)) {
                // FIXME we need one more check to see if we really need to scan the subdir
                // to solve the case where includes="{'*'}", scanning sub-directory does not help
                // but only slow down the completion
                scanSubDir(child, newRelativePath);
            }
        } else {
            if (isIncluded(newRelativePath)) {
                if (!isExcluded(newRelativePath)) {
                    includedFiles.add(child);
                }
            }
        }
    }
}

From source file:org.codehaus.mojo.vfs.internal.DefaultVfsDirectoryScanner.java

private boolean isDirectory(FileObject file) throws FileSystemException {
    if (FileType.FOLDER == file.getType()) {
        return true;
    }//  w  w w .  j a v  a 2  s  .c  o  m

    if (FileType.FILE_OR_FOLDER == file.getType()) {
        try {
            file.getChildren();
        } catch (FileNotFolderException e) {
            return false;
        }

        return true;
    }

    return false;
}

From source file:org.datacleaner.user.upgrade.DataCleanerHomeUpgrader.java

/**
 * Finds a folder to upgrade from based on the "newFolder" parameter -
 * upgrades are performed only within the same major version.
 * /*from   www  .java 2s  .c o m*/
 * @param newFolder
 *            The folder we want to upgrade to (the new version)
 * @return true if upgrade was successful, false otherwise
 */
public boolean upgrade(FileObject newFolder) {
    try {
        if (newFolder.getChildren().length != 0) {
            // if the folder is not new then we don't want to touch it
            return false;
        }

        final FileObject upgradeFromFolderCandidate = findUpgradeCandidate(newFolder);

        if (upgradeFromFolderCandidate == null) {
            logger.info("Did not find a suitable upgrade candidate");
            return false;
        }

        logger.info("Upgrading DATACLEANER_HOME from : {}", upgradeFromFolderCandidate);
        newFolder.copyFrom(upgradeFromFolderCandidate, new AllFileSelector());

        // special handling of userpreferences.dat - we only want to keep
        // the good parts ;-)
        final UserPreferencesUpgrader userPreferencesUpgrader = new UserPreferencesUpgrader(newFolder);
        userPreferencesUpgrader.upgrade();

        // Overwrite example jobs
        final List<String> allFilePaths = DemoConfiguration.getAllFilePaths();
        for (String filePath : allFilePaths) {
            overwriteFileWithDefaults(newFolder, filePath);
        }
        return true;
    } catch (FileSystemException e) {
        logger.warn("Exception occured during upgrading: {}", e);
        return false;
    }
}

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

@Override
public List<JsTreeFile> getChildren(String path, SharedUserPortletParameters userParameters) {
    try {/*from w  ww  . j a v a 2  s .  c o  m*/
        List<JsTreeFile> files = new ArrayList<JsTreeFile>();
        FileObject resource = cd(path, userParameters);
        FileObject[] children = resource.getChildren();
        if (children != null)
            for (FileObject child : children)
                if (!"imaginary".equals(child.getType().getName())
                        && (userParameters.isShowHiddenFiles() || !this.isFileHidden(child)))
                    files.add(resourceAsJsTreeFile(child, false, true, userParameters.isShowHiddenFiles()));
        return files;
    } catch (FileSystemException fse) {
        Throwable cause = ExceptionUtils.getCause(fse);
        if (cause != null && cause.getClass().equals(SftpException.class)) {
            SftpException sfe = (SftpException) cause;
            if (sfe.id == ChannelSftp.SSH_FX_PERMISSION_DENIED)
                throw new EsupStockPermissionDeniedException(sfe);
        }
        if (cause != null && cause.getClass().equals(JSchException.class)) {
            if ("session is down".equals(cause.getMessage())) {
                log.info("Session is down, we close all so that we can try to reopen a connection");
                throw new EsupStockLostSessionException((JSchException) cause);
            }
        }
        throw new EsupStockException(fse);
    }
}

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  w w  w  .j  av a 2  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.fuin.vfs2.filter.EmptyFileFilter.java

/**
 * Checks to see if the file is empty. A non-existing file is also
 * considered empty./*  w ww.j  a  va  2  s .  co  m*/
 * 
 * @param fileInfo
 *            the file or directory to check
 * 
 * @return {@code true} if the file or directory is <i>empty</i>, otherwise
 *         {@code false}.
 */
@Override
public boolean accept(final FileSelectInfo fileInfo) {
    final FileObject file = fileInfo.getFile();
    try {
        if (!file.exists()) {
            return true;
        }
        if (file.getType() == FileType.FOLDER) {
            final FileObject[] files = file.getChildren();
            return files == null || files.length == 0;
        }
        final FileContent content = file.getContent();
        try {
            return content.getSize() == 0;
        } finally {
            content.close();
        }
    } catch (final FileSystemException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.geoserver.backuprestore.utils.BackupUtils.java

/**
 * Compress {@code sourceFolder} to the archive file {@code archiveFile}; both shall previously exist.
 * //  w w  w .  j av a 2 s  .c o m
 * @param sourceFolder
 * @param archiveFile
 * @throws IOException
 */
public static void compressTo(Resource sourceFolder, Resource archiveFile) throws IOException {
    // See https://commons.apache.org/proper/commons-vfs/filesystems.html
    // for the supported filesystems

    FileSystemManager manager = VFS.getManager();

    FileObject sourceDir = manager
            .createVirtualFileSystem(manager.resolveFile(sourceFolder.dir().getAbsolutePath()));

    try {
        if ("zip".equalsIgnoreCase(FileUtils.getExtension(archiveFile.path()))) {
            // apache VFS does not support ZIP as writable FileSystem

            OutputStream fos = archiveFile.out();

            // Create access to zip.
            ZipOutputStream zos = new ZipOutputStream(fos);

            // add entry/-ies.
            for (FileObject sourceFile : sourceDir.getChildren()) {
                writeEntry(zos, sourceFile, null);
            }

            // Close streams
            zos.flush();
            zos.close();
            fos.close();
        } else {
            // Create access to archive.
            FileObject zipFile = manager.resolveFile(resolveArchiveURI(archiveFile));
            zipFile.createFile();
            ZipOutputStream zos = new ZipOutputStream(zipFile.getContent().getOutputStream());

            // add entry/-ies.
            for (FileObject sourceFile : sourceDir.getChildren()) {
                writeEntry(zos, sourceFile, null);
            }

            // Close streams
            zos.flush();
            zos.close();
            zipFile.close();
            manager.closeFileSystem(zipFile.getFileSystem());
        }
    } finally {
        manager.closeFileSystem(sourceDir.getFileSystem());
    }
}

From source file:org.geoserver.backuprestore.utils.BackupUtils.java

/**
 * @param zos/*from  w  w w  .java2s.c o m*/
 * @param sourceFile
 * @throws FileSystemException
 * @throws IOException
 */
private static void writeEntry(ZipOutputStream zos, FileObject sourceFile, String baseDir)
        throws FileSystemException, IOException {
    if (sourceFile.getType() == FileType.FOLDER) {
        // add entry/-ies.
        for (FileObject file : sourceFile.getChildren()) {
            writeEntry(zos, file, Paths.path(baseDir, sourceFile.getName().getBaseName()));
        }
    } else {
        String fileName = (baseDir != null ? Paths.path(baseDir, sourceFile.getName().getBaseName())
                : sourceFile.getName().getBaseName());
        ZipEntry zipEntry = new ZipEntry(fileName);
        InputStream is = sourceFile.getContent().getInputStream();

        // Write to zip.
        byte[] buf = new byte[1024];
        zos.putNextEntry(zipEntry);
        for (int readNum; (readNum = is.read(buf)) != -1;) {
            zos.write(buf, 0, readNum);
        }
        zos.closeEntry();
        is.close();
    }
}