Example usage for org.apache.commons.vfs FileObject isReadable

List of usage examples for org.apache.commons.vfs FileObject isReadable

Introduction

In this page you can find the example usage for org.apache.commons.vfs FileObject isReadable.

Prototype

public boolean isReadable() throws FileSystemException;

Source Link

Document

Determines if this file can be read.

Usage

From source file:com.newatlanta.appengine.junit.vfs.gae.GaeVfsTestCase.java

public static void assertEquals(File file, FileObject fileObject) throws Exception {
    assertEqualPaths(file, fileObject);/*from   ww w .  j  a v a2 s  .  c o m*/
    assertEquals(file.canRead(), fileObject.isReadable());
    assertEquals(file.canWrite(), fileObject.isWriteable());
    assertEquals(file.exists(), fileObject.exists());
    if (file.getParentFile() == null) {
        assertNull(fileObject.getParent());
    } else {
        assertEqualPaths(file.getParentFile(), fileObject.getParent());
    }
    assertEquals(file.isDirectory(), fileObject.getType().hasChildren());
    assertEquals(file.isFile(), fileObject.getType().hasContent());
    assertEquals(file.isHidden(), fileObject.isHidden());
    if (file.isFile()) {
        assertEquals(file.length(), fileObject.getContent().getSize());
    }
    if (file.isDirectory()) { // same children
        File[] childFiles = file.listFiles();
        FileObject[] childObjects = fileObject.getChildren();
        assertEquals(childFiles.length, childObjects.length);
        for (int i = 0; i < childFiles.length; i++) {
            assertEqualPaths(childFiles[i], childObjects[i]);
        }
    }
}

From source file:com.newatlanta.appengine.junit.vfs.gae.GaeFolderTestCase.java

private static void assertFolder(FileObject folder) throws Exception {
    assertTrue(folder.exists());// w w  w. ja v a  2  s  .  co m
    assertTrue(folder.isAttached()); // exists() causes attach
    assertTrue(folder.isReadable());
    assertTrue(folder.isWriteable());
    assertFalse(folder.isHidden());
    assertTrue(folder.getType().hasChildren());
    assertFalse(folder.getType().hasContent());

    // TODO: with combined local option, local children of GAE folder will
    // have a different parent; maybe we can compare paths when GaeFileName
    // is modified to store abspath like LocalFileName
    //      FileObject[] children = folder.getChildren();
    //      for ( FileObject child : children ) {
    //         assertEquals( folder, child.getParent() );
    //         FileObject childObject = folder.getChild( child.getName().getURI() );
    //         assertEquals( child, childObject );
    //         assertEquals( folder, childObject.getParent() );
    //      }

    // TODO: use folder.findFiles( Selectors.SELECT_ALL) to get all
    // descendants, then test FileName.isDescendant() and isAncestor()
}

From source file:com.panet.imeta.job.entries.fileexists.JobEntryFileExists.java

public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = previousResult;
    result.setResult(false);/*from www.j a  v  a  2 s .  c  om*/

    if (filename != null) {
        String realFilename = getRealFilename();
        try {
            FileObject file = KettleVFS.getFileObject(realFilename);
            if (file.exists() && file.isReadable()) {
                log.logDetailed(toString(), Messages.getString("JobEntryFileExists.File_Exists", realFilename)); //$NON-NLS-1$
                result.setResult(true);
            } else {
                log.logDetailed(toString(),
                        Messages.getString("JobEntryFileExists.File_Does_Not_Exist", realFilename)); //$NON-NLS-1$
            }
        } catch (IOException e) {
            result.setNrErrors(1);
            log.logError(toString(),
                    Messages.getString("JobEntryFileExists.ERROR_0004_IO_Exception", e.toString())); //$NON-NLS-1$
        }
    } else {
        result.setNrErrors(1);
        log.logError(toString(), Messages.getString("JobEntryFileExists.ERROR_0005_No_Filename_Defined")); //$NON-NLS-1$
    }

    return result;
}

From source file:com.panet.imeta.job.entries.filesexist.JobEntryFilesExist.java

public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = previousResult;
    result.setResult(false);/*from  ww w . j a va  2  s .c  o m*/
    int missingfiles = 0;

    if (arguments != null) {
        for (int i = 0; i < arguments.length && !parentJob.isStopped(); i++) {
            FileObject file = null;

            try {
                String realFilefoldername = environmentSubstitute(arguments[i]);
                file = KettleVFS.getFileObject(realFilefoldername);

                if (file.exists() && file.isReadable()) {
                    if (log.isDetailed())
                        log.logDetailed(toString(),
                                Messages.getString("JobEntryFilesExist.File_Exists", realFilefoldername)); //$NON-NLS-1$
                } else {
                    missingfiles++;
                    result.setNrErrors(missingfiles);
                    if (log.isDetailed())
                        log.logDetailed(toString(), Messages.getString("JobEntryFilesExist.File_Does_Not_Exist", //$NON-NLS-1$
                                realFilefoldername));
                }

            } catch (IOException e) {
                missingfiles++;
                result.setNrErrors(missingfiles);
                log.logError(toString(),
                        Messages.getString("JobEntryFilesExist.ERROR_0004_IO_Exception", e.toString())); //$NON-NLS-1$
            } finally {
                if (file != null) {
                    try {
                        file.close();
                    } catch (IOException ex) {
                    }
                    ;
                }
            }
        }

    }

    if (missingfiles == 0)
        result.setResult(true);

    return result;
}

From source file:com.panet.imeta.core.plugins.PluginLoader.java

/**
 * This method does the actual plugin configuration and should be called
 * after load()/*from ww w.jav  a2  s  . co m*/
 * 
 * @return a collection containing the <code>JobPlugin</code> objects
 *         loaded.
 * @throws KettleConfigException
 */
private void doConfig() throws KettleConfigException {
    synchronized (locs) {
        String sjar = "." + JAR;

        for (PluginLocation plugin : locs) {
            // check to see if the resource type is present
            File base = new File(System.getProperty("user.dir"));
            try {
                FileSystemManager mgr = VFS.getManager();
                FileObject fobj = mgr.resolveFile(base, plugin.getLocation());
                if (fobj.isReadable()) {
                    String name = fobj.getName().getURI();
                    int jindex = name.indexOf(sjar);
                    int nlen = name.length();
                    boolean isJar = jindex == nlen - 4 || jindex == nlen - 6;

                    try {

                        if (isJar)
                            build(fobj, true);
                        else {
                            // loop thru folder
                            for (FileObject childFolder : fobj.getChildren()) {
                                boolean isAlsoJar = childFolder.getName().getURI().endsWith(sjar);

                                // ignore anything that is not a folder or a
                                // jar
                                if (!isAlsoJar && childFolder.getType() != FileType.FOLDER) {
                                    continue;
                                }

                                // ignore any subversion or CVS directories
                                if (childFolder.getName().getBaseName().equalsIgnoreCase(".svn")) {
                                    continue;
                                } else if (childFolder.getName().getBaseName().equalsIgnoreCase(".cvs")) {
                                    continue;
                                }
                                try {
                                    build(childFolder, isAlsoJar);
                                } catch (KettleConfigException e) {
                                    log.logError(Plugin.PLUGIN_LOADER, e.getMessage());
                                    continue;
                                }
                            }

                        }

                    } catch (FileSystemException e) {
                        log.logError(Plugin.PLUGIN_LOADER, e.getMessage());
                        continue;
                    } catch (KettleConfigException e) {
                        log.logError(Plugin.PLUGIN_LOADER, e.getMessage());
                        continue;
                    }

                } else {
                    log.logDebug(Plugin.PLUGIN_LOADER, fobj + " does not exist, ignoring this.");
                }
            } catch (Exception e) {
                throw new KettleConfigException(e);
            }

        }
    }
}

From source file:mondrian.spi.impl.ApacheVfsVirtualFileHandler.java

public InputStream readVirtualFile(String url) throws FileSystemException {
    // Treat catalogUrl as an Apache VFS (Virtual File System) URL.
    // VFS handles all of the usual protocols (http:, file:)
    // and then some.
    FileSystemManager fsManager = VFS.getManager();
    if (fsManager == null) {
        throw Util.newError("Cannot get virtual file system manager");
    }/*  ww w . j av  a 2  s  .c om*/

    // Workaround VFS bug.
    if (url.startsWith("file://localhost")) {
        url = url.substring("file://localhost".length());
    }
    if (url.startsWith("file:")) {
        url = url.substring("file:".length());
    }

    //work around for VFS bug not closing http sockets
    // (Mondrian-585)
    if (url.startsWith("http")) {
        try {
            return new URL(url).openStream();
        } catch (IOException e) {
            throw Util.newError("Could not read URL: " + url);
        }
    }

    File userDir = new File("").getAbsoluteFile();
    FileObject file = fsManager.resolveFile(userDir, url);
    FileContent fileContent = null;
    try {
        // Because of VFS caching, make sure we refresh to get the latest
        // file content. This refresh may possibly solve the following
        // workaround for defect MONDRIAN-508, but cannot be tested, so we
        // will leave the work around for now.
        file.refresh();

        // Workaround to defect MONDRIAN-508. For HttpFileObjects, verifies
        // the URL of the file retrieved matches the URL passed in.  A VFS
        // cache bug can cause it to treat URLs with different parameters
        // as the same file (e.g. http://blah.com?param=A,
        // http://blah.com?param=B)
        if (file instanceof HttpFileObject && !file.getName().getURI().equals(url)) {
            fsManager.getFilesCache().removeFile(file.getFileSystem(), file.getName());

            file = fsManager.resolveFile(userDir, url);
        }

        if (!file.isReadable()) {
            throw Util.newError("Virtual file is not readable: " + url);
        }

        fileContent = file.getContent();
    } finally {
        file.close();
    }

    if (fileContent == null) {
        throw Util.newError("Cannot get virtual file content: " + url);
    }

    return fileContent.getInputStream();
}

From source file:com.panet.imeta.core.fileinput.FileInputList.java

public static FileInputList createFileList(VariableSpace space, String[] fileName, String[] fileMask,
        String[] fileRequired, boolean[] includeSubdirs, FileTypeFilter[] fileTypeFilters) {
    FileInputList fileInputList = new FileInputList();

    // Replace possible environment variables...
    final String realfile[] = space.environmentSubstitute(fileName);
    final String realmask[] = space.environmentSubstitute(fileMask);

    for (int i = 0; i < realfile.length; i++) {
        final String onefile = realfile[i];
        final String onemask = realmask[i];

        final boolean onerequired = YES.equalsIgnoreCase(fileRequired[i]);
        final boolean subdirs = includeSubdirs[i];
        final FileTypeFilter filter = ((fileTypeFilters == null || fileTypeFilters[i] == null)
                ? FileTypeFilter.ONLY_FILES
                : fileTypeFilters[i]);/* ww  w.j  ava 2  s  .  co m*/

        if (Const.isEmpty(onefile))
            continue;

        // 
        // If a wildcard is set we search for files
        //
        if (!Const.isEmpty(onemask)) {
            try {
                // Find all file names that match the wildcard in this directory
                //
                FileObject directoryFileObject = KettleVFS.getFileObject(onefile);
                if (directoryFileObject != null && directoryFileObject.getType() == FileType.FOLDER) // it's a directory
                {
                    FileObject[] fileObjects = directoryFileObject.findFiles(new AllFileSelector() {
                        public boolean traverseDescendents(FileSelectInfo info) {
                            return info.getDepth() == 0 || subdirs;
                        }

                        public boolean includeFile(FileSelectInfo info) {
                            // Never return the parent directory of a file list.
                            if (info.getDepth() == 0) {
                                return false;
                            }

                            FileObject fileObject = info.getFile();
                            try {
                                if (fileObject != null && filter.isFileTypeAllowed(fileObject.getType())) {
                                    String name = fileObject.getName().getBaseName();
                                    boolean matches = Pattern.matches(onemask, name);
                                    /*
                                    if (matches)
                                    {
                                        System.out.println("File match: URI: "+info.getFile()+", name="+name+", depth="+info.getDepth());
                                    }
                                    */
                                    return matches;
                                }
                                return false;
                            } catch (FileSystemException ex) {
                                // Upon error don't process the file.
                                return false;
                            }
                        }
                    });
                    if (fileObjects != null) {
                        for (int j = 0; j < fileObjects.length; j++) {
                            if (fileObjects[j].exists())
                                fileInputList.addFile(fileObjects[j]);
                        }
                    }
                    if (Const.isEmpty(fileObjects)) {
                        if (onerequired)
                            fileInputList.addNonAccessibleFile(directoryFileObject);
                    }

                    // Sort the list: quicksort, only for regular files
                    fileInputList.sortFiles();
                } else {
                    FileObject[] children = directoryFileObject.getChildren();
                    for (int j = 0; j < children.length; j++) {
                        // See if the wildcard (regexp) matches...
                        String name = children[j].getName().getBaseName();
                        if (Pattern.matches(onemask, name))
                            fileInputList.addFile(children[j]);
                    }
                    // We don't sort here, keep the order of the files in the archive.
                }
            } catch (Exception e) {
                LogWriter.getInstance().logError("FileInputList", Const.getStackTracker(e));
            }
        } else
        // A normal file...
        {
            try {
                FileObject fileObject = KettleVFS.getFileObject(onefile);
                if (fileObject.exists()) {
                    if (fileObject.isReadable()) {
                        fileInputList.addFile(fileObject);
                    } else {
                        if (onerequired)
                            fileInputList.addNonAccessibleFile(fileObject);
                    }
                } else {
                    if (onerequired)
                        fileInputList.addNonExistantFile(fileObject);
                }
            } catch (Exception e) {
                LogWriter.getInstance().logError("FileInputList", Const.getStackTracker(e));
            }
        }
    }

    return fileInputList;
}

From source file:com.panet.imeta.core.plugins.PluginLoader.java

private void build(FileObject parent, boolean isJar) throws KettleConfigException {
    try {/*from  ww  w  . j a v a2  s . co  m*/
        FileObject xml = null;

        if (isJar) {
            FileObject exploded = explodeJar(parent);

            // try reading annotations first ...
            ResolverUtil<Plugin> resPlugins = new ResolverUtil<Plugin>();

            // grab all jar files not part of the "lib"
            File fparent = new File(exploded.getURL().getFile());
            File[] files = fparent.listFiles(new JarNameFilter());

            URL[] classpath = new URL[files.length];
            for (int i = 0; i < files.length; i++)
                classpath[i] = files[i].toURI().toURL();

            ClassLoader cl = new PDIClassLoader(classpath, Thread.currentThread().getContextClassLoader());
            resPlugins.setClassLoader(cl);

            for (FileObject couldBeJar : exploded.getChildren()) {
                if (couldBeJar.getName().getExtension().equals(JAR))
                    resPlugins.loadImplementationsInJar(Const.EMPTY_STRING, couldBeJar.getURL(),
                            tests.values().toArray(new ResolverUtil.Test[2]));
            }

            for (Class<? extends Plugin> match : resPlugins.getClasses()) {
                for (Class<? extends Annotation> cannot : tests.keySet()) {
                    Annotation annot = match.getAnnotation(cannot);
                    if (annot != null)
                        fromAnnotation(annot, exploded, match);
                }

            }

            // and we also read from the xml if present
            xml = exploded.getChild(Plugin.PLUGIN_XML_FILE);

            if (xml == null || !xml.exists())
                return;

            parent = exploded;

        } else
            xml = parent.getChild(Plugin.PLUGIN_XML_FILE);

        // then read the xml if it is there
        if (xml != null && xml.isReadable())
            fromXML(xml, parent);

    } catch (Exception e) {
        throw new KettleConfigException(e);
    }

    // throw new KettleConfigException("Unable to read plugin.xml from " +
    // parent);
}

From source file:mondrian.olap.Util.java

/**
 * Gets content via Apache VFS. File must exist and have content
 *
 * @param url String/*from w  w w  .j av a 2 s  .  c  o m*/
 * @return Apache VFS FileContent for further processing
 * @throws FileSystemException on error
 */
public static InputStream readVirtualFile(String url) throws FileSystemException {
    // Treat catalogUrl as an Apache VFS (Virtual File System) URL.
    // VFS handles all of the usual protocols (http:, file:)
    // and then some.
    FileSystemManager fsManager = VFS.getManager();
    if (fsManager == null) {
        throw newError("Cannot get virtual file system manager");
    }

    // Workaround VFS bug.
    if (url.startsWith("file://localhost")) {
        url = url.substring("file://localhost".length());
    }
    if (url.startsWith("file:")) {
        url = url.substring("file:".length());
    }

    // work around for VFS bug not closing http sockets
    // (Mondrian-585)
    if (url.startsWith("http")) {
        try {
            return new URL(url).openStream();
        } catch (IOException e) {
            throw newError("Could not read URL: " + url);
        }
    }

    File userDir = new File("").getAbsoluteFile();
    FileObject file = fsManager.resolveFile(userDir, url);
    FileContent fileContent = null;
    try {
        // Because of VFS caching, make sure we refresh to get the latest
        // file content. This refresh may possibly solve the following
        // workaround for defect MONDRIAN-508, but cannot be tested, so we
        // will leave the work around for now.
        file.refresh();

        // Workaround to defect MONDRIAN-508. For HttpFileObjects, verifies
        // the URL of the file retrieved matches the URL passed in.  A VFS
        // cache bug can cause it to treat URLs with different parameters
        // as the same file (e.g. http://blah.com?param=A,
        // http://blah.com?param=B)
        if (file instanceof HttpFileObject && !file.getName().getURI().equals(url)) {
            fsManager.getFilesCache().removeFile(file.getFileSystem(), file.getName());

            file = fsManager.resolveFile(userDir, url);
        }

        if (!file.isReadable()) {
            throw newError("Virtual file is not readable: " + url);
        }

        fileContent = file.getContent();
    } finally {
        file.close();
    }

    if (fileContent == null) {
        throw newError("Cannot get virtual file content: " + url);
    }

    return fileContent.getInputStream();
}

From source file:org.apache.commons.vfs.example.ShowProperties.java

public static void main(String[] args) {
    if (args.length == 0) {
        System.err.println("Please pass the name of a file as parameter.");
        System.err.println("e.g. java org.apache.commons.vfs.example.ShowProperties LICENSE.txt");
        return;//ww w .j a v  a  2 s .  c  o m
    }
    for (int i = 0; i < args.length; i++) {
        try {
            FileSystemManager mgr = VFS.getManager();
            System.out.println();
            System.out.println("Parsing: " + args[i]);
            FileObject file = mgr.resolveFile(args[i]);
            System.out.println("URL: " + file.getURL());
            System.out.println("getName(): " + file.getName());
            System.out.println("BaseName: " + file.getName().getBaseName());
            System.out.println("Extension: " + file.getName().getExtension());
            System.out.println("Path: " + file.getName().getPath());
            System.out.println("Scheme: " + file.getName().getScheme());
            System.out.println("URI: " + file.getName().getURI());
            System.out.println("Root URI: " + file.getName().getRootURI());
            System.out.println("Parent: " + file.getName().getParent());
            System.out.println("Type: " + file.getType());
            System.out.println("Exists: " + file.exists());
            System.out.println("Readable: " + file.isReadable());
            System.out.println("Writeable: " + file.isWriteable());
            System.out.println("Root path: " + file.getFileSystem().getRoot().getName().getPath());
            if (file.exists()) {
                if (file.getType().equals(FileType.FILE)) {
                    System.out.println("Size: " + file.getContent().getSize() + " bytes");
                } else if (file.getType().equals(FileType.FOLDER) && file.isReadable()) {
                    FileObject[] children = file.getChildren();
                    System.out.println("Directory with " + children.length + " files");
                    for (int iterChildren = 0; iterChildren < children.length; iterChildren++) {
                        System.out.println("#" + iterChildren + ": " + children[iterChildren].getName());
                        if (iterChildren > 5) {
                            break;
                        }
                    }
                }
                System.out.println("Last modified: "
                        + DateFormat.getInstance().format(new Date(file.getContent().getLastModifiedTime())));
            } else {
                System.out.println("The file does not exist");
            }
            file.close();
        } catch (FileSystemException ex) {
            ex.printStackTrace();
        }
    }
}