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.pentaho.vfs.ui.VfsFileChooserDialog.java

public void updateParentFileCombo(FileObject selectedItem) {
    try {//from w  w  w .j  a va 2 s .co m
        List<FileObject> parentChain = new ArrayList<FileObject>();
        // are we a directory?
        try {
            if (selectedItem.getType() == FileType.FOLDER && selectedItem.getType().hasChildren()) {
                // we have real children....
                parentChain.add(selectedItem);
            }
        } catch (Exception e) {
            // we are not a folder
        }
        FileObject parentFileObject;
        parentFileObject = selectedItem.getParent();
        while (parentFileObject != null) {
            parentChain.add(parentFileObject);
            parentFileObject = parentFileObject.getParent();
        }

        File roots[] = File.listRoots();
        if (currentPanel != null) {
            for (int i = 0; i < roots.length; i++) {
                parentChain.add(currentPanel.resolveFile(roots[i].getAbsolutePath()));
            }
        }

        String items[] = new String[parentChain.size()];
        int idx = 0;
        for (int i = parentChain.size() - 1; i >= 0; i--) {
            items[idx++] = ((FileObject) parentChain.get(i)).getName().getURI();
        }

        openFileCombo.setItems(items);
        openFileCombo.select(items.length - 1);
    } catch (Exception e) {
        e.printStackTrace();
        // then let's not update the GUI
    }
}

From source file:org.renjin.appengine.AppEngineLocalFilesSystemProviderTest.java

@Test
public void test() throws FileSystemException {

    File basePath = new File(getClass().getResource("/jarfiletest.jar").getFile()).getParentFile();

    FileSystemManager dfsm = AppEngineContextFactory
            .createFileSystemManager(new AppEngineLocalFilesSystemProvider(basePath));

    FileObject jarFile = dfsm.resolveFile("/jarfiletest.jar");
    assertThat(jarFile.getName().getURI(), equalTo("file:///jarfiletest.jar"));
    assertThat(jarFile.exists(), equalTo(true));

    FileObject jarRoot = dfsm.resolveFile("jar:file:///jarfiletest.jar!/r/library");
    assertThat(jarRoot.exists(), equalTo(true));
    assertThat(jarRoot.getType(), equalTo(FileType.FOLDER));
    assertThat(jarRoot.getChildren().length, equalTo(1));
}

From source file:org.renjin.primitives.files.Files.java

/**
 * Utility function to extract information about files on the user's file systems.
 *
 * @param context  current call Context//from   ww w  .j av a 2  s .c o m
 * @param paths the list of files for which to return information
 * @return list column-oriented table of file information
 * @throws FileSystemException
 */
@Internal("file.info")
public static ListVector fileInfo(@Current Context context, StringVector paths) throws FileSystemException {

    DoubleArrayVector.Builder size = new DoubleArrayVector.Builder();
    LogicalArrayVector.Builder isdir = new LogicalArrayVector.Builder();
    IntArrayVector.Builder mode = (IntArrayVector.Builder) new IntArrayVector.Builder()
            .setAttribute(Symbols.CLASS, StringVector.valueOf("octmode"));
    DoubleArrayVector.Builder mtime = new DoubleArrayVector.Builder();
    StringVector.Builder exe = new StringVector.Builder();

    for (String path : paths) {
        if (StringVector.isNA(path)) {
            throw new EvalException("invalid filename argument");
        }
        FileObject file = context.resolveFile(path);
        if (file.exists()) {
            if (file.getType() == FileType.FILE) {
                size.add((int) file.getContent().getSize());
            } else {
                size.add(0);
            }
            isdir.add(file.getType() == FileType.FOLDER);
            mode.add(mode(file));
            try {
                mtime.add(file.getContent().getLastModifiedTime());
            } catch (Exception e) {
                mtime.add(0);
            }
            exe.add(file.getName().getBaseName().endsWith(".exe") ? "yes" : "no");
        } else {
            size.addNA();
            isdir.addNA();
            mode.addNA();
            mtime.addNA();
            exe.addNA();
        }
    }

    return ListVector.newNamedBuilder().add("size", size).add("isdir", isdir).add("mode", mode)
            .add("mtime", mtime).add("ctime", mtime).add("atime", mtime).add("exe", exe).build();
}

From source file:org.renjin.primitives.files.Files.java

/**
  * Gets the type or storage mode of an object.
        /*from   www  .ja  v  a2s . 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.renjin.primitives.files.Files.java

/**
 * {@code list.files} produce a character vector of the names of files in the named directory.
 *
 * @param paths  a character vector of full path names; the default corresponds to the working
 *  directory getwd(). Missing values will be ignored.
 * @param pattern an optional regular expression. Only file names which match the regular
 * expression will be returned./*from  ww w  .  ja v  a  2s .co m*/
 * @param allFiles  If FALSE, only the names of visible files are returned. If TRUE, all
 * file names will be returned.
 * @param fullNames If TRUE, the directory path is prepended to the file names. If FALSE,
 * only the file names are returned.
 * @param recursive Should the listing recurse into directories?
 * @param ignoreCase Should pattern-matching be case-insensitive?
 *
 * If a path does not exist or is not a directory or is unreadable it is skipped, with a warning.
 * The files are sorted in alphabetical order, on the full path if full.names = TRUE. Directories are included only if recursive = FALSE.
 *
 * @return
 */
@Internal("list.files")
public static StringVector listFiles(@Current final Context context, final StringVector paths,
        final String pattern, final boolean allFiles, final boolean fullNames, final boolean recursive,
        final boolean ignoreCase, final boolean includeDirs) throws IOException {

    return new Object() {

        private final StringVector.Builder result = new StringVector.Builder();
        private final RE filter = pattern == null ? null : new ExtendedRE(pattern).ignoreCase(ignoreCase);

        public StringVector list() throws IOException {
            for (String path : paths) {
                FileObject folder = context.resolveFile(path);
                if (folder.getType() == FileType.FOLDER) {
                    if (allFiles & !recursive) {
                        add(path, ".");
                        add(path, "..");
                    }
                    for (FileObject child : folder.getChildren()) {
                        if (filter(child)) {
                            add(path, child);
                        }
                    }
                }
            }
            return result.build();
        }

        void add(String path, FileObject file) {
            if (fullNames) {
                result.add(path + "/" + file.getName().getBaseName());
            } else {
                result.add(file.getName().getBaseName());
            }
        }

        void add(String path, String name) throws FileSystemException {
            if (fullNames) {
                result.add(path + "/" + name);
            } else {
                result.add(name);
            }
        }

        boolean filter(FileObject child) throws FileSystemException {
            if (!allFiles && isHidden(child)) {
                return false;
            }
            if (recursive && !includeDirs && child.getType() == FileType.FOLDER) {
                return false;
            }
            if (filter != null && !filter.match(child.getName().getBaseName())) {
                return false;
            }
            return true;
        }

        private boolean isHidden(FileObject file) throws FileSystemException {
            return file.isHidden() || file.getName().getBaseName().startsWith(".");
        }
    }.list();
}

From source file:org.renjin.primitives.files.Files.java

@Invisible
@Internal/*from   www.java2 s  .  c o m*/
public static String setwd(@Current Context context, String workingDirectoryName) throws FileSystemException {
    FileObject newWorkingDirectory = context.resolveFile(workingDirectoryName);
    if (!newWorkingDirectory.exists() || newWorkingDirectory.getType() != FileType.FOLDER) {
        throw new EvalException("cannot change working directory");
    }

    String previous = context.getSession().getWorkingDirectory().getName().getURI();

    context.getSession().setWorkingDirectory(newWorkingDirectory);
    return previous;
}

From source file:org.renjin.primitives.files.Files.java

private static void delete(FileObject file, boolean recursive) throws FileSystemException {
    if (file.exists()) {
        if (file.getType() == FileType.FILE) {
            file.delete();/*from w  w  w.  j av a2 s .c om*/
        } else if (file.getType() == FileType.FOLDER) {
            if (file.getChildren().length == 0) {
                file.delete();
            } else if (recursive) {
                file.delete();
            }
        }
    }
}

From source file:org.wso2.carbon.connector.FileArchiveConnector.java

/**
 * Archive a file/folder.//from   w  ww  .  j  av  a  2s. c  om
 *
 * @param messageContext The message context that is generated for processing the file.
 * @return return true, if the file/folder is successfully archived, false, if not.
 * @throws FileSystemException On error parsing the file name, determining if the file exists and getting file type.
 */
private boolean fileCompress(MessageContext messageContext) throws FileSystemException {
    String source = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.FILE_LOCATION);
    String destination = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.NEW_FILE_LOCATION);
    StandardFileSystemManager manager = FileConnectorUtils.getManager();
    FileSystemOptions opts = FileConnectorUtils.init(messageContext);
    FileObject fileObj = manager.resolveFile(source, opts);
    FileObject destObj = manager.resolveFile(destination, opts);
    if (!fileObj.exists()) {
        log.error("The File location does not exist.");
        return false;
    }
    if (FileType.FOLDER.equals(fileObj.getType())) {
        List<FileObject> fileList = new ArrayList<>();
        addAllFilesToList(fileObj, fileList);
        writeZipFiles(fileObj, destObj, fileList);
    } else {
        ZipOutputStream outputStream = null;
        InputStream fileIn = null;
        try {
            outputStream = new ZipOutputStream(destObj.getContent().getOutputStream());
            fileIn = fileObj.getContent().getInputStream();
            ZipEntry zipEntry = new ZipEntry(fileObj.getName().getBaseName());
            outputStream.putNextEntry(zipEntry);
            int length;
            while ((length = fileIn.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }
        } catch (IOException e) {
            throw new SynapseException("Error while writing an array of bytes to the ZipOutputStream", e);
        } finally {
            try {
                // close the file object
                fileObj.close();
            } catch (FileSystemException e) {
                log.error("Error while closing the source FileObject", e);
            }
            try {
                // close the file object
                destObj.close();
            } catch (FileSystemException e) {
                log.error("Error while closing the destination FileObject", e);
            }
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                log.error("Error while closing ZipOutputStream", e);
            }
            try {
                if (fileIn != null) {
                    fileIn.close();
                }
            } catch (IOException e) {
                log.error("Error while closing InputStream:", e);
            }
            // close the StandardFileSystemManager
            manager.close();
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("File archiving completed." + destination);
    }
    return true;
}

From source file:org.wso2.carbon.connector.FileArchiveConnector.java

/**
 * Add the all files into List./*from   w  w  w .  j  a  v a 2s . com*/
 *
 * @param dir      The source file/folder directory.
 * @param fileList List for adding the files.
 */
private void addAllFilesToList(FileObject dir, List<FileObject> fileList) {
    try {
        FileObject[] children = dir.getChildren();
        for (FileObject child : children) {
            fileList.add(child);
            if (FileType.FOLDER.equals(child.getType())) {
                addAllFilesToList(child, fileList);
            }
        }
    } catch (FileSystemException e) {
        throw new SynapseException("Unable to add all files into List", e);
    } finally {
        try {
            dir.close();
        } catch (FileSystemException e) {
            log.error("Error while closing the FileObject", e);
        }
    }
}

From source file:org.wso2.carbon.connector.FileArchiveConnector.java

/**
 * Extract all files to add the zip directory.
 *
 * @param fileObj        Source fileObject.
 * @param directoryToZip Destination fileObject.
 * @param fileList       List of files to be compressed.
 * @throws FileSystemException When get the OutputStream, get file type.
 *//*  ww  w .  j a v a 2 s  .c o m*/
private void writeZipFiles(FileObject fileObj, FileObject directoryToZip, List<FileObject> fileList)
        throws FileSystemException {
    ZipOutputStream zos = null;
    try {
        zos = new ZipOutputStream(directoryToZip.getContent().getOutputStream());
        for (FileObject file : fileList) {
            if (FileType.FILE.equals(file.getType())) {
                addToZip(fileObj, file, zos);
            }
        }
    } catch (FileSystemException e) {
        throw new SynapseException("Error occurs in writing files", e);
    } finally {
        try {
            if (zos != null) {
                zos.close();
            }
        } catch (IOException e) {
            log.error("Error while closing the ZipOutputStream");
        }
        try {
            fileObj.close();
            directoryToZip.close();
        } catch (FileSystemException e) {
            log.error("Error while closing the FileObject", e);
        }
    }
}