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

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

Introduction

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

Prototype

public FileSystem getFileSystem();

Source Link

Document

Returns the file system that contains this file.

Usage

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

private static void assertSubFolders(FileObject testFolder, String[] subFolderNames) throws Exception {
    FileName rootName = testFolder.getFileSystem().getRootName();
    FileObject[] subFolders = testFolder.findFiles(Selectors.EXCLUDE_SELF);
    assertEquals(subFolders.length, subFolderNames.length);
    for (int i = 0; i < subFolders.length; i++) {
        FileObject subObject = subFolders[i];
        assertTrue(subObject.getName().getPath().endsWith(subFolderNames[i]));
        assertFolder(subObject);//from  www.j a v a 2  s .  co  m
        assertEquals(subObject.getParent(), i == subFolders.length - 1 ? testFolder : subFolders[i + 1]);
        assertTrue(rootName.isDescendent(subObject.getName()));
        assertTrue(subObject.getName().isAncestor(rootName));
    }
}

From source file:com.pongasoft.util.io.IOUtils.java

/**
 * Wraps the provided file object within a jar file object
 * (ex: <code>createJarFileObject(file:///tmp/foo.jar)</code> will return
 * <code>jar:file:///tmp.foo.jar!/</code>
 *
 * @param fileObject the orginal jar file
 * @return the wrapped file object (note that it the orignial object does not exists, it
 *         is simply returned (as wrapping it throws an exception...)
 * @throws IOException if there is something wrong
 *//*from  w  w  w .ja va2  s.com*/
public static FileObject createJarFileObject(FileObject fileObject) throws IOException {
    if (fileObject == null)
        return null;

    if (fileObject.exists()) {
        FileSystemManager fsm = fileObject.getFileSystem().getFileSystemManager();
        return fsm.resolveFile("jar:" + fileObject.getURL() + "!/");
    } else
        return fileObject;
}

From source file:net.sf.vfsjfilechooser.utils.VFSUtils.java

/**
 * Returns the root filesystem of a given file
 * @param fileObject A file//w  w w  .j a v  a2 s  . com
 * @return the root filesystem of a given file
 */
public static FileObject createFileSystemRoot(FileObject fileObject) {
    try {
        return fileObject.getFileSystem().getRoot();
    } catch (FileSystemException ex) {
        return null;
    }
}

From source file:net.sf.vfsjfilechooser.utils.VFSUtils.java

/**
 * Returns the root file system of a file representation
 * @param fileObject A file abstraction/*ww  w. j a va  2 s  .c o  m*/
 * @return the root file system of a file representation
 */
public static FileObject getRootFileSystem(FileObject fileObject) {
    try {
        if ((fileObject == null) || !fileObject.exists()) {
            return null;
        }

        return fileObject.getFileSystem().getRoot();
    } catch (FileSystemException ex) {
        return null;
    }
}

From source file:egovframework.rte.fdl.filehandling.FilehandlingServiceTest.java

@Test
public void testCaching1() throws Exception {
    String testFolder = "d:/workspace/java/e-gov/eGovFramework/RTE/DEV/trunk/Foundation/egovframework.rte.fdl.filehandling/test";

    FileSystemManager manager = VFS.getManager();

    EgovFileUtil.writeFile(testFolder + "/file1.txt", text, "UTF-8");

    /*/*w  w  w  .ja  v  a 2s  . co m*/
     * ? Manager ?
     * CacheStrategy.MANUAL      : Deal with cached data manually. Call FileObject.refresh() to refresh the object data.
     * CacheStrategy.ON_RESOLVE : Refresh the data every time you request a file from FileSystemManager.resolveFile
     * CacheStrategy.ON_CALL   : Refresh the data every time you call a method on the fileObject. You'll use this only if you really need the latest info as this setting is a major performance loss. 
     */
    DefaultFileSystemManager fs = new DefaultFileSystemManager();
    fs.setFilesCache(manager.getFilesCache());

    // zip, jar, tgz, tar, tbz2, file
    if (!fs.hasProvider("file")) {
        fs.addProvider("file", new DefaultLocalFileProvider());
    }
    //       StandardFileSystemManager fs = new StandardFileSystemManager();

    fs.setCacheStrategy(CacheStrategy.ON_RESOLVE);
    fs.init();

    // ? ? ?
    //FileObject foBase2 = fs.resolveFile(testFolder);
    log.debug("####1");
    FileObject cachedFile = fs.toFileObject(new File(testFolder + "/file1.txt"));
    log.debug("####2");

    FilesCache filesCache = fs.getFilesCache();
    log.debug("####3");
    filesCache.putFile(cachedFile);
    FileObject obj = filesCache.getFile(cachedFile.getFileSystem(), cachedFile.getName());

    //FileObject baseFile = fs.getBaseFile();
    //        log.debug("### cachedFile.getContent().getSize() is " + cachedFile.getContent().getSize());

    //        long fileSize = cachedFile.getContent().getSize();
    //        log.debug("#########size is " + fileSize);
    //FileObject cachedFile1 = cachedFile.resolveFile("file2.txt");

    //       FileObject scratchFolder = manager.resolveFile(testFolder);
    //       scratchFolder.delete(Selectors.EXCLUDE_SELF);

    EgovFileUtil.delete(new File(testFolder + "/file1.txt"));

    //       obj.createFile();

    //        log.debug("#########obj is " + obj.toString());
    //        log.debug("#########size is " + obj.getContent().getSize());
    log.debug("#########file is " + obj.exists());

    fs.close();
}

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  .  ja  v a2  s .c o m

    // 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.thinkberg.webdav.lock.LockManager.java

/**
 * Evaluate an 'If:' header condition.//ww w  .  j a v  a 2  s. com
 * The condition may be a tagged list or an untagged list. Tagged lists define the resource, the condition
 * applies to in front of the condition (ex. 1, 2, 5, 6). Conditions may be inverted by using 'Not' at the
 * beginning of the condition (ex. 3, 4, 6). The list constitutes an OR expression while the list of
 * conditions within braces () constitutes an AND expression.
 * <p/>
 * Evaluate example 2:<br/>
 * <code>
 * URI(/resource1) { (
 * is-locked-with(urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2)
 * AND matches-etag(W/"A weak ETag") )
 * OR ( matches-etag("strong ETag") ) }
 * </code>
 * <p/>
 * Examples:
 * <ol>
 * <li> &lt;http://cid:8080/litmus/unmapped_url&gt; (&lt;opaquelocktoken:cd6798&gt;)</li>
 * <li> &lt;/resource1&gt; (&lt;urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2&gt; [W/"A weak ETag"]) (["strong ETag"])</li>
 * <li> (&lt;urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2&gt;) (Not &lt;DAV:no-lock&gt;)</li>
 * <li> (Not &lt;urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2&gt; &lt;urn:uuid:58f202ac-22cf-11d1-b12d-002035b29092&gt;)</li>
 * <li> &lt;/specs/rfc2518.doc&gt; (["4217"])</li>
 * <li> &lt;/specs/rfc2518.doc&gt; (Not ["4217"])</li>
 * </ol>
 *
 * @param contextObject the contextual resource (needed when the If: condition is not tagged)
 * @param ifCondition   the string of the condition as sent by the If: header
 * @return evaluation of the condition expression
 * @throws ParseException        if the condition does not meet the syntax requirements
 * @throws LockConflictException
 * @throws FileSystemException
 */
public EvaluationResult evaluateCondition(FileObject contextObject, String ifCondition)
        throws FileSystemException, LockConflictException, ParseException {
    List<Lock> locks = discoverLock(contextObject);
    EvaluationResult evaluation = new EvaluationResult();

    if (ifCondition == null || "".equals(ifCondition)) {
        if (locks != null) {
            throw new LockConflictException(locks);
        }
        evaluation.result = true;
        return evaluation;
    }

    Matcher matcher = IF_PATTERN.matcher(ifCondition);
    FileObject resource = contextObject;
    while (matcher.find()) {
        String token = matcher.group();
        switch (token.charAt(0)) {
        case TOKEN_LOWER_THAN:
            String resourceUri = token.substring(1, token.length() - 1);
            try {
                resource = contextObject.getFileSystem().resolveFile(new URI(resourceUri).getPath());
                locks = discoverLock(resource);
            } catch (URISyntaxException e) {
                throw new ParseException(ifCondition, matcher.start());
            }
            break;
        case TOKEN_LEFT_BRACE:
            LOG.debug(String.format("URI(%s) {", resource));
            Matcher condMatcher = CONDITION_PATTERN.matcher(token.substring(1, token.length() - 1));
            boolean expressionResult = true;
            while (condMatcher.find()) {
                String condToken = condMatcher.group();
                boolean negate = false;
                if (condToken.matches("[Nn][Oo][Tt]")) {
                    negate = true;
                    condMatcher.find();
                    condToken = condMatcher.group();
                }
                switch (condToken.charAt(0)) {
                case TOKEN_LOWER_THAN:
                    String lockToken = condToken.substring(1, condToken.length() - 1);

                    boolean foundLock = false;
                    if (locks != null) {
                        for (Lock lock : locks) {
                            if (lockToken.equals(lock.getToken())) {
                                evaluation.locks.add(lock);
                                foundLock = true;
                                break;
                            }
                        }
                    }
                    final boolean foundLockResult = negate ? !foundLock : foundLock;
                    LOG.debug(String.format("  %sis-locked-with(%s) = %b", negate ? "NOT " : "", lockToken,
                            foundLockResult));
                    expressionResult = expressionResult && foundLockResult;
                    break;
                case TOKEN_LEFT_BRACKET:
                    String eTag = condToken.substring(1, condToken.length() - 1);
                    String resourceETag = Util.getETag(resource);
                    boolean resourceTagMatches = resourceETag.equals(eTag);
                    final boolean matchesEtagResult = negate ? !resourceTagMatches : resourceTagMatches;
                    LOG.debug(String.format("  %smatches-etag(%s) = %b", negate ? "NOT " : "", eTag,
                            matchesEtagResult));
                    expressionResult = expressionResult && matchesEtagResult;
                    break;
                default:
                    throw new ParseException(
                            String.format("syntax error in condition '%s' at %d", ifCondition,
                                    matcher.start() + condMatcher.start()),
                            matcher.start() + condMatcher.start());
                }
            }

            evaluation.result = evaluation.result || expressionResult;
            LOG.debug("} => " + evaluation.result);
            break;
        default:
            throw new ParseException(
                    String.format("syntax error in condition '%s' at %d", ifCondition, matcher.start()),
                    matcher.start());
        }
    }

    // regardless of the evaluation, if the object is locked but there is no valed lock token in the
    // conditions we must fail with a lock conflict too
    if (evaluation.result && (locks != null && !locks.isEmpty()) && evaluation.locks.isEmpty()) {
        throw new LockConflictException(locks);
    }
    return evaluation;
}

From source file:mondrian.olap.Util.java

/**
 * Gets content via Apache VFS. File must exist and have content
 *
 * @param url String//  w ww  .j av a 2s.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;// w w  w  .j a  va 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();
        }
    }
}

From source file:org.codehaus.mojo.unix.core.FsFileCollector.java

public FsFileCollector(FileObject fsRoot) throws FileSystemException {
    this.fsRoot = fsRoot;
    FileSystemManager fileSystemManager = fsRoot.getFileSystem().getFileSystemManager();
    FileObject root = fileSystemManager.createVirtualFileSystem(fsRoot);
    root.createFolder();//from   w  ww  .j  ava2 s.  c  o  m
    this.root = root;
}