Example usage for org.apache.commons.vfs VFS getManager

List of usage examples for org.apache.commons.vfs VFS getManager

Introduction

In this page you can find the example usage for org.apache.commons.vfs VFS getManager.

Prototype

public static synchronized FileSystemManager getManager() throws FileSystemException 

Source Link

Document

Returns the default FileSystemManager instance

Usage

From source file:com.github.stephenc.javaisotools.iso9660.impl.CreateISOTest.java

@Test
public void canCreateAnIsoWithSomeFiles() throws Exception {
    // Output file
    File outfile = new File(workDir, "test.iso");
    File contentsA = new File(workDir, "a.txt");
    OutputStream os = new FileOutputStream(contentsA);
    IOUtil.copy("Hello", os);
    IOUtil.close(os);/*from  www .  j a  va 2s  .co m*/
    File contentsB = new File(workDir, "b.txt");
    os = new FileOutputStream(contentsB);
    IOUtil.copy("Goodbye", os);
    IOUtil.close(os);

    // Directory hierarchy, starting from the root
    ISO9660RootDirectory.MOVED_DIRECTORIES_STORE_NAME = "rr_moved";
    ISO9660RootDirectory root = new ISO9660RootDirectory();

    ISO9660Directory dir = root.addDirectory("root");
    dir.addFile(contentsA);
    dir.addFile(contentsB);

    StreamHandler streamHandler = new ISOImageFileHandler(outfile);
    CreateISO iso = new CreateISO(streamHandler, root);
    ISO9660Config iso9660Config = new ISO9660Config();
    iso9660Config.allowASCII(false);
    iso9660Config.setInterchangeLevel(2);
    iso9660Config.restrictDirDepthTo8(true);
    iso9660Config.setVolumeID("ISO Test");
    iso9660Config.forceDotDelimiter(true);
    RockRidgeConfig rrConfig = new RockRidgeConfig();
    rrConfig.setMkisofsCompatibility(true);
    rrConfig.hideMovedDirectoriesStore(true);
    rrConfig.forcePortableFilenameCharacterSet(true);

    JolietConfig jolietConfig = new JolietConfig();
    jolietConfig.setVolumeID("Joliet Test");
    jolietConfig.forceDotDelimiter(true);

    iso.process(iso9660Config, rrConfig, jolietConfig, null);

    assertThat(outfile.isFile(), is(true));
    assertThat(outfile.length(), not(is(0L)));

    FileSystemManager fsManager = VFS.getManager();
    FileObject isoFile = fsManager.resolveFile("iso:" + outfile.getPath() + "!/root");

    FileObject t = isoFile.getChild("a.txt");
    assertThat(t, CoreMatchers.<Object>notNullValue());
    assertThat(t.getType(), is(FileType.FILE));
    assertThat(t.getContent().getSize(), is(5L));
    assertThat(IOUtil.toString(t.getContent().getInputStream()), is("Hello"));
    t = isoFile.getChild("b.txt");
    assertThat(t, CoreMatchers.<Object>notNullValue());
    assertThat(t.getType(), is(FileType.FILE));
    assertThat(t.getContent().getSize(), is(7L));
    assertThat(IOUtil.toString(t.getContent().getInputStream()), is("Goodbye"));
}

From source file:de.ecclesia.kipeto.RepositoryResolver.java

private String getHostname() throws FileSystemException {
    String hostname = VFS.getManager().resolveURI(defaultRepositoryUrl).getRootURI().replaceAll("sftp://", "");
    if (hostname.contains("@")) {
        int idx = hostname.indexOf("@");
        hostname = hostname.substring(idx + 1, hostname.length());
    }/*from ww w . j  ava2 s .c om*/

    if (hostname.endsWith("/")) {
        hostname = hostname.substring(0, hostname.length() - 1);
    }
    return hostname;
}

From source file:com.github.stephenc.javaisotools.iso9660.impl.CreateISOTest.java

@Test
public void canCreateAnIsoWithLoadsOfFiles() throws Exception {
    final int numFiles = entropy.nextInt(50) + 50;
    // Output file
    File outfile = new File(workDir, "big.iso");
    File rootDir = new File(workDir, "big");
    assertThat(rootDir.isDirectory() || rootDir.mkdirs(), is(true));

    // Directory hierarchy, starting from the root
    ISO9660RootDirectory.MOVED_DIRECTORIES_STORE_NAME = "rr_moved";
    ISO9660RootDirectory root = new ISO9660RootDirectory();
    for (int i = 0; i < numFiles; i++) {
        File content = new File(rootDir, Integer.toString(i) + ".bin");
        int length = entropy.nextInt(1024 * 10 + 1);
        byte[] contents = new byte[length];
        entropy.nextBytes(contents);//  w ww.  j  av  a2  s . c o m
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(content);
            fos.write(contents);
        } finally {
            IOUtil.close(fos);
        }
        root.addFile(content);
    }

    StreamHandler streamHandler = new ISOImageFileHandler(outfile);
    CreateISO iso = new CreateISO(streamHandler, root);
    ISO9660Config iso9660Config = new ISO9660Config();
    iso9660Config.allowASCII(false);
    iso9660Config.setInterchangeLevel(2);
    iso9660Config.restrictDirDepthTo8(true);
    iso9660Config.setVolumeID("ISO Test");
    iso9660Config.forceDotDelimiter(true);
    RockRidgeConfig rrConfig = new RockRidgeConfig();
    rrConfig.setMkisofsCompatibility(true);
    rrConfig.hideMovedDirectoriesStore(true);
    rrConfig.forcePortableFilenameCharacterSet(true);

    JolietConfig jolietConfig = new JolietConfig();
    jolietConfig.setVolumeID("Joliet Test");
    jolietConfig.forceDotDelimiter(true);

    iso.process(iso9660Config, rrConfig, jolietConfig, null);

    assertThat(outfile.isFile(), is(true));
    assertThat(outfile.length(), not(is(0L)));

    FileSystemManager fsManager = VFS.getManager();
    for (int i = 0; i < numFiles; i++) {
        File content = new File(rootDir, Integer.toString(i) + ".bin");
        FileObject t = fsManager.resolveFile("iso:" + outfile.getPath() + "!/" + Integer.toString(i) + ".bin");
        assertThat(t, CoreMatchers.<Object>notNullValue());
        assertThat(t.getType(), is(FileType.FILE));
        assertThat(t.getContent().getSize(), is(content.length()));
        assertThat(IOUtil.toByteArray(t.getContent().getInputStream()),
                is(IOUtil.toByteArray(new FileInputStream(content))));
    }
}

From source file:com.thinkberg.vfs.s3.tests.S3FileProviderTest.java

public void testCloseFileSystem() throws FileSystemException {
    VFS.getManager().closeFileSystem(ROOT.getFileSystem());
}

From source file:com.collabnet.ccf.core.transformer.XsltProcessor.java

/**
 * Hook to perform any validation of the component properties required by
 * the implementation. Default behaviour should be a no-op.
 *///from w  w w  .  j  a  v a 2s  .  c  o  m
@SuppressWarnings("unchecked")
public void validate(List exceptions) {
    // we have to make this map thread safe because it will be
    // updated asynchronously
    xsltFileNameTransformerMap = Collections.synchronizedMap(new HashMap<String, Transformer>());
    if (isListenForFileUpdates()) {
        try {
            fsManager = VFS.getManager();
        } catch (FileSystemException e) {
            exceptions
                    .add(new ValidationException("could not initialize file manager: " + e.getMessage(), this));
            return;
        }
        fileMonitor = new DefaultFileMonitor(new FileListener() {
            public void fileChanged(org.apache.commons.vfs.FileChangeEvent arg0) throws Exception {
                xsltFileNameTransformerMap.clear();
            }

            public void fileCreated(FileChangeEvent arg0) throws Exception {
                xsltFileNameTransformerMap.clear();
            }

            public void fileDeleted(FileChangeEvent arg0) throws Exception {
                xsltFileNameTransformerMap.clear();
            }
        });
    }

    String xsltDir = this.getXsltDir();
    String xsltFile = this.getXsltFile();
    if (!StringUtils.isEmpty(xsltDir)) {
        File xsltDirFile = new File(xsltDir);
        if (xsltDirFile.exists() && xsltDirFile.isDirectory()) {
            log.debug("xsltDir property " + xsltDir + " is a valid directory");
            if (listenForFileUpdates) {
                FileObject fileObject = null;
                try {
                    fileObject = fsManager.resolveFile(xsltDirFile.getAbsolutePath());
                } catch (FileSystemException e) {
                    exceptions.add(new ValidationException(
                            "xsltDir property " + xsltDir + " is not a valid directory: " + e.getMessage(),
                            this));
                    return;
                }
                fileMonitor.setRecursive(true);
                fileMonitor.addFile(fileObject);
                fileMonitor.start();
            }

        } else {
            exceptions.add(new ValidationException(
                    "xsltDir property " + xsltDir + " is not a valid directory...!", this));
            return;
        }
    } else if (!StringUtils.isEmpty(xsltFile)) {
        File xsltFileFile = new File(xsltFile);
        if (xsltFileFile.exists() && xsltFileFile.isFile()) {
            log.debug("xsltFile property " + xsltFile + " is a valid file");
            if (listenForFileUpdates) {
                FileObject fileObject = null;
                try {
                    fileObject = fsManager.resolveFile(xsltFileFile.getAbsolutePath());
                } catch (FileSystemException e) {
                    exceptions.add(new ValidationException(
                            "xsltFile property " + xsltFile + " is not a valid file...:" + e.getMessage(),
                            this));
                    return;
                }
                fileMonitor.addFile(fileObject);
                fileMonitor.start();
            }
        } else {
            exceptions.add(new ValidationException("xsltFile property " + xsltFile + " is not a valid file...!",
                    this));
            return;
        }
    }
}

From source file:com.github.stephenc.javaisotools.iso9660.impl.CreateISOTest.java

@Test
public void canOpenFakeIso() throws Exception {
    final String contentString = "This is a text file, not an iso";
    // Output file
    File fakeIso = new File(workDir, "fake.iso");
    OutputStream os = new FileOutputStream(fakeIso);
    IOUtil.copy(contentString, os);// w w w. j  a v  a2  s .  c  o  m
    IOUtil.close(os);

    // Trying to open a fake iso
    FileSystemManager fsManager = VFS.getManager();
    FileObject fo = fsManager.resolveFile("iso:" + fakeIso.getPath() + "!/");
    assertFalse("The file '" + fakeIso.getName() + "' is not a valid iso file", fo.exists());
}

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

@Test
public void testUserAuthentication() throws Exception {
    StaticUserAuthenticator auth = new StaticUserAuthenticator(null, "username", "password");
    FileSystemOptions opts = new FileSystemOptions();
    DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);

    FileSystemManager manager = VFS.getManager();

    FileObject baseDir = manager.resolveFile(System.getProperty("user.dir"));
    FileObject file = manager.resolveFile(baseDir, "testfolder/file1.txt");
    FileObject fo = manager.resolveFile("d:" + file.getName().getPath(), opts);

    fo.createFile();/*w  ww  .jav a  2s.  c  o  m*/

}

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");

    /*/*from w  w w  .  j a va  2s .c o 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:egovframework.rte.fdl.filehandling.EgovFileUtil.java

/**
 * <p>//from  w  w w . j  av  a2s.  co  m
 * ? ? ? .
 * </p>
 * @param filepath
 *        <code>String</code>
 * @return ? ?
 * @throws Exception
 */
public static FileObject getFileObject(final String filepath) throws Exception {
    FileSystemManager mgr = VFS.getManager();

    return mgr.resolveFile(mgr.resolveFile(System.getProperty("user.dir")), filepath);
}

From source file:com.collabnet.ccf.core.transformer.DynamicXsltProcessor.java

/**
 * Hook to perform any validation of the component properties required by
 * the implementation. Default behaviour should be a no-op.
 *///from w ww .j a v  a  2 s .  c  om
@SuppressWarnings("unchecked")
public void validate(List exceptions) {
    // we have to make this map thread safe because it will be
    // updated asynchronously
    xsltFileNameTransformerMap = Collections.synchronizedMap(new HashMap<String, List<Transformer>>());
    if (isListenForFileUpdates()) {
        try {
            fsManager = VFS.getManager();
        } catch (FileSystemException e) {
            exceptions
                    .add(new ValidationException("could not initialize file manager: " + e.getMessage(), this));
            return;
        }
        fileMonitor = new DefaultFileMonitor(new FileListener() {
            public void fileChanged(org.apache.commons.vfs.FileChangeEvent arg0) throws Exception {
                xsltFileNameTransformerMap.clear();
            }

            public void fileCreated(FileChangeEvent arg0) throws Exception {
                xsltFileNameTransformerMap.clear();
            }

            public void fileDeleted(FileChangeEvent arg0) throws Exception {
                xsltFileNameTransformerMap.clear();
            }
        });
    }

    String xsltDir = this.getXsltDir();
    String xsltFile = this.getXsltFile();
    if (!StringUtils.isEmpty(xsltDir)) {
        File xsltDirFile = new File(xsltDir);
        if (xsltDirFile.exists() && xsltDirFile.isDirectory()) {
            log.debug("xsltDir property " + xsltDir + " is a valid directory");
            if (listenForFileUpdates) {
                FileObject fileObject = null;
                try {
                    fileObject = fsManager.resolveFile(xsltDirFile.getAbsolutePath());
                } catch (FileSystemException e) {
                    exceptions.add(new ValidationException(
                            "xsltDir property " + xsltDir + " is not a valid directory: " + e.getMessage(),
                            this));
                    return;
                }
                fileMonitor.setRecursive(true);
                fileMonitor.addFile(fileObject);
                fileMonitor.start();
            }
            if (scriptProcessors.isEmpty()) {
                log.warn("No scripts supplied, so dynamic XSLT processor will not change data at all");
            }
        } else {
            exceptions.add(new ValidationException(
                    "xsltDir property " + xsltDir + " is not a valid directory...!", this));
            return;
        }
    } else if (!StringUtils.isEmpty(xsltFile)) {
        File xsltFileFile = new File(xsltFile);
        if (xsltFileFile.exists() && xsltFileFile.isFile()) {
            log.debug("xsltFile property " + xsltFile + " is a valid file");
            if (listenForFileUpdates) {
                FileObject fileObject = null;
                try {
                    fileObject = fsManager.resolveFile(xsltFileFile.getAbsolutePath());
                } catch (FileSystemException e) {
                    exceptions.add(new ValidationException(
                            "xsltFile property " + xsltFile + " is not a valid file...:" + e.getMessage(),
                            this));
                    return;
                }
                fileMonitor.addFile(fileObject);
                fileMonitor.start();
            }
        } else {
            exceptions.add(new ValidationException("xsltFile property " + xsltFile + " is not a valid file...!",
                    this));
            return;
        }
    }
    factory = TransformerFactory.newInstance();
    if (isOnlyAllowWhiteListedJavaFunctionCalls()) {
        try {
            secureFactory = TransformerFactory.newInstance();
            secureFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
            secureFactory.setErrorListener(new XsltValidationErrorListener());
        } catch (TransformerConfigurationException e) {
            exceptions.add(new ValidationException(
                    "Setting secure processing feature on XSLT processor failed, bailing out since this feature is required by onlyAllowWhiteListedJavaFunctions property",
                    this));
            return;
        }
    }
}