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

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

Introduction

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

Prototype

public FileObject getChild(String name) throws FileSystemException;

Source Link

Document

Returns a child of this file.

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  w  ww. ja  va2 s  . c  o 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:com.github.lucapino.sheetmaker.parsers.mediainfo.MediaInfoRetriever.java

@Override
public MovieInfo getMovieInfo(String filePath) {
    MediaInfo mediaInfo = new MediaInfo();
    String fileToParse = filePath;
    // test if we have iso
    if (filePath.toLowerCase().endsWith("iso")) {
        // open iso and parse the ifo files
        Map<Integer, String> ifoFiles = new TreeMap<>();
        try {/* w  w  w.jav  a  2 s  .com*/
            FileSystemManager fsManager = VFS.getManager();
            FileObject fo = fsManager.resolveFile("iso:" + filePath + "!/");
            // create an ifo file selector
            FileSelector ifoFs = new FileFilterSelector(new FileFilter() {

                @Override
                public boolean accept(FileSelectInfo fsi) {
                    return fsi.getFile().getName().getBaseName().toLowerCase().endsWith("ifo");
                }
            });
            FileObject[] files = fo.getChild("VIDEO_TS").findFiles(ifoFs);
            for (FileObject file : files) {
                File tmpFile = new File(
                        System.getProperty("java.io.tmpdir") + File.separator + file.getName().getBaseName());
                System.out.println(file.getName().getBaseName());
                IOUtils.copy(file.getContent().getInputStream(), new FileOutputStream(tmpFile));
                mediaInfo.Open(tmpFile.getAbsolutePath());
                String format = mediaInfo.Get(MediaInfo.StreamKind.General, 0, "Format_Profile",
                        MediaInfo.InfoKind.Text, MediaInfo.InfoKind.Name);
                System.out.println("Format profile: " + format);
                // if format is "Program" -> it's a video file
                if (format.equalsIgnoreCase("program")) {
                    String duration = mediaInfo.Get(MediaInfo.StreamKind.General, 0, "Duration",
                            MediaInfo.InfoKind.Text, MediaInfo.InfoKind.Name);
                    System.out.println("Duration: " + duration);
                    ifoFiles.put(Integer.valueOf(duration), tmpFile.getName());
                }
                mediaInfo.Close();
            }
            if (!ifoFiles.isEmpty()) {
                if (ifoFiles.size() == 1) {
                    fileToParse = ifoFiles.values().iterator().next();
                } else {
                    // get the last entry -> the bigger one
                    Set<Integer> keys = ifoFiles.keySet();
                    Iterator<Integer> iterator = keys.iterator();
                    for (int i = 0; i < keys.size(); i++) {
                        String fileName = ifoFiles.get(iterator.next());
                        if (i == keys.size() - 1) {
                            fileToParse = fileName;
                        } else {
                            new File(fileName).delete();
                        }
                    }
                }
            }
        } catch (IOException | NumberFormatException ex) {

        }
    }
    // here fileToParse is correct
    mediaInfo.Open(fileToParse);
    System.out.println(mediaInfo.Inform());

    return new MovieInfoImpl(mediaInfo, filePath);
}

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

private void build(FileObject parent, boolean isJar) throws KettleConfigException {
    try {/*from   ww  w.jav a  2 s .  c om*/
        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:org.codehaus.mojo.unix.core.OperationTest.java

public void testExtractWithPattern() throws Exception {
    String archivePath = PlexusTestCase.getTestPath("src/test/resources/operation/extract.jar");

    FileSystemManager fsManager = VFS.getManager();
    FileObject archiveObject = fsManager.resolveFile(archivePath);
    assertEquals(FileType.FILE, archiveObject.getType());
    FileObject archive = fsManager.createFileSystem(archiveObject);

    FileObject fooLicense = archive.getChild("foo-license.txt");
    UnixFsObject.RegularFile fooLicenseUnixFile = fromFileObject(relativePath("licenses/foo-license.txt"),
            fooLicense, fileAttributes);

    FileObject barLicense = archive.getChild("mydir").getChild("bar-license.txt");
    UnixFsObject.RegularFile barLicenseUnixFile = fromFileObject(relativePath("licenses/bar-license.txt"),
            barLicense, fileAttributes);

    MockControl control = MockControl.createControl(FileCollector.class);
    FileCollector fileCollector = (FileCollector) control.getMock();

    control.expectAndReturn(fileCollector.addFile(barLicense, barLicenseUnixFile), fileCollector);
    control.expectAndReturn(fileCollector.addFile(fooLicense, fooLicenseUnixFile), fileCollector);
    control.replay();// w  w  w.j av  a2 s .  c  o m

    new CopyDirectoryOperation(archive, relativePath("licenses"), asList("**/*license.txt"), null,
            some(p(".*/(.*license.*)", "$1")), fileAttributes, directoryAttributes).perform(fileCollector);

    control.verify();
}

From source file:org.codehaus.mojo.unix.maven.rpm.RpmUnixPackageTest.java

public void testBasic() throws Exception {
    if (!Rpmbuild.available()) {
        return;/* www .j a v  a 2  s .c o m*/
    }

    String archivePath = getTestPath("src/test/resources/operation/extract.jar");

    FileSystemManager fsManager = VFS.getManager();
    FileObject pomXml = fsManager.resolveFile(getTestPath("pom.xml"));
    FileObject archiveObject = fsManager.resolveFile(archivePath);
    FileObject archive = fsManager.createFileSystem(archiveObject);
    FileObject fooLicense = archive.getChild("foo-license.txt");
    FileObject barLicense = archive.getChild("mydir").getChild("bar-license.txt");

    RpmPackagingFormat packagingFormat = (RpmPackagingFormat) lookup(PackagingFormat.ROLE, "rpm");

    FileObject rpmTest = VFS.getManager().resolveFile(getTestPath("target/rpm-test"));
    FileObject packageRoot = rpmTest.resolveFile("root");
    File packageFile = getTestFile("target/rpm-test/file.rpm");

    PackageVersion version = packageVersion("1.0-1", "123", false, Option.<String>none());
    PackageParameters parameters = packageParameters("mygroup", "myartifact", version, "id", "default-name",
            Option.<String>none(), EMPTY, EMPTY).contact("Kurt Cobain").architecture("all").name("Yo!")
                    .license("BSD");

    UnixPackage unixPackage = RpmPackagingFormat
            .cast(packagingFormat.start().parameters(parameters).workingDirectory(packageRoot)).group("Fun");

    LocalDateTime now = new LocalDateTime();
    Option<FileAttributes> none = Option.none();

    unixPackage.addFile(pomXml, regularFile(relativePath("/pom.xml"), now, 0, none))
            .addFile(fooLicense, regularFile(relativePath("/foo-license.txt"), now, 0, none))
            .addFile(barLicense, regularFile(relativePath("/bar-license.txt"), now, 0, none));

    unixPackage.debug(true).packageToFile(packageFile, ScriptUtil.Strategy.SINGLE);

    assertTrue(packageFile.canRead());
}

From source file:org.nanocontainer.deployer.NanoContainerDeployer.java

private FileObject getDeploymentScript(FileObject applicationFolder) throws FileSystemException {
    final FileObject metaInf = applicationFolder.getChild("META-INF");
    if (metaInf == null) {
        throw new FileSystemException("Missing META-INF folder in " + applicationFolder.getName().getPath());
    }/*from w w  w .  ja va 2s  .c om*/
    final FileObject[] nanocontainerScripts = metaInf.findFiles(new FileSelector() {
        public boolean includeFile(FileSelectInfo fileSelectInfo) throws Exception {
            return fileSelectInfo.getFile().getName().getBaseName().startsWith("nanocontainer");
        }

        public boolean traverseDescendents(FileSelectInfo fileSelectInfo) throws Exception {
            return true;
        }
    });
    if (nanocontainerScripts == null || nanocontainerScripts.length < 1) {
        throw new FileSystemException("No deployment script (nanocontainer.[groovy|bsh|js|py|xml]) in "
                + applicationFolder.getName().getPath() + "/META-INF");
    }
    return nanocontainerScripts[0];
}

From source file:org.pentaho.di.core.plugins.PluginFolder.java

public FileObject[] findJarFiles(final boolean includeLibJars) throws KettleFileException {

    try {//w  w w . j a  va 2 s .  com
        // Find all the jar files in this folder...
        //
        FileObject folderObject = KettleVFS.getFileObject(this.getFolder());
        FileObject[] fileObjects = folderObject.findFiles(new FileSelector() {
            @Override
            public boolean traverseDescendents(FileSelectInfo fileSelectInfo) throws Exception {
                FileObject fileObject = fileSelectInfo.getFile();
                String folder = fileObject.getName().getBaseName();
                FileObject kettleIgnore = fileObject.getChild(".kettle-ignore");
                return includeLibJars || (kettleIgnore == null && !"lib".equals(folder));
            }

            @Override
            public boolean includeFile(FileSelectInfo fileSelectInfo) throws Exception {
                return fileSelectInfo.getFile().toString().endsWith(".jar");
            }
        });

        return fileObjects;
    } catch (Exception e) {
        throw new KettleFileException("Unable to list jar files in plugin folder '" + toString() + "'", e);
    }
}

From source file:org.pentaho.di.job.entries.copyfiles.JobEntryCopyFiles.java

private boolean ProcessFileFolder(String sourcefilefoldername, String destinationfilefoldername,
        String wildcard, Job parentJob, Result result) {
    boolean entrystatus = false;
    FileObject sourcefilefolder = null;
    FileObject destinationfilefolder = null;

    // Clear list files to remove after copy process
    // This list is also added to result files name
    list_files_remove.clear();//from   w w w .  j a v  a2 s  .com
    list_add_result.clear();

    // Get real source, destination file and wildcard
    String realSourceFilefoldername = environmentSubstitute(sourcefilefoldername);
    String realDestinationFilefoldername = environmentSubstitute(destinationfilefoldername);
    String realWildcard = environmentSubstitute(wildcard);

    try {
        sourcefilefolder = KettleVFS.getFileObject(realSourceFilefoldername, this);
        destinationfilefolder = KettleVFS.getFileObject(realDestinationFilefoldername, this);

        if (sourcefilefolder.exists()) {

            // Check if destination folder/parent folder exists !
            // If user wanted and if destination folder does not exist
            // PDI will create it
            if (CreateDestinationFolder(destinationfilefolder)) {

                // Basic Tests
                if (sourcefilefolder.getType().equals(FileType.FOLDER) && destination_is_a_file) {
                    // Source is a folder, destination is a file
                    // WARNING !!! CAN NOT COPY FOLDER TO FILE !!!

                    logError(BaseMessages.getString(PKG, "JobCopyFiles.Log.CanNotCopyFolderToFile",
                            realSourceFilefoldername, realDestinationFilefoldername));

                    NbrFail++;

                } else {

                    if (destinationfilefolder.getType().equals(FileType.FOLDER)
                            && sourcefilefolder.getType().equals(FileType.FILE)) {
                        // Source is a file, destination is a folder
                        // Copy the file to the destination folder

                        destinationfilefolder.copyFrom(sourcefilefolder.getParent(),
                                new TextOneFileSelector(sourcefilefolder.getParent().toString(),
                                        sourcefilefolder.getName().getBaseName(),
                                        destinationfilefolder.toString()));
                        if (isDetailed()) {
                            logDetailed(BaseMessages.getString(PKG, "JobCopyFiles.Log.FileCopied",
                                    sourcefilefolder.getName().toString(),
                                    destinationfilefolder.getName().toString()));
                        }

                    } else if (sourcefilefolder.getType().equals(FileType.FILE) && destination_is_a_file) {
                        // Source is a file, destination is a file

                        destinationfilefolder.copyFrom(sourcefilefolder,
                                new TextOneToOneFileSelector(destinationfilefolder));
                    } else {
                        // Both source and destination are folders
                        if (isDetailed()) {
                            logDetailed("  ");
                            logDetailed(BaseMessages.getString(PKG, "JobCopyFiles.Log.FetchFolder",
                                    sourcefilefolder.toString()));

                        }

                        TextFileSelector textFileSelector = new TextFileSelector(sourcefilefolder,
                                destinationfilefolder, realWildcard, parentJob);
                        try {
                            destinationfilefolder.copyFrom(sourcefilefolder, textFileSelector);
                        } finally {
                            textFileSelector.shutdown();
                        }
                    }

                    // Remove Files if needed
                    if (remove_source_files && !list_files_remove.isEmpty()) {
                        String sourceFilefoldername = sourcefilefolder.toString();
                        int trimPathLength = sourceFilefoldername.length() + 1;
                        FileObject removeFile;

                        for (Iterator<String> iter = list_files_remove.iterator(); iter.hasNext()
                                && !parentJob.isStopped();) {
                            String fileremoventry = iter.next();
                            removeFile = null; // re=null each iteration
                            // Try to get the file relative to the existing connection
                            if (fileremoventry.startsWith(sourceFilefoldername)) {
                                if (trimPathLength < fileremoventry.length()) {
                                    removeFile = sourcefilefolder
                                            .getChild(fileremoventry.substring(trimPathLength));
                                }
                            }

                            // Unable to retrieve file through existing connection; Get the file through a new VFS connection
                            if (removeFile == null) {
                                removeFile = KettleVFS.getFileObject(fileremoventry, this);
                            }

                            // Remove ONLY Files
                            if (removeFile.getType() == FileType.FILE) {
                                boolean deletefile = removeFile.delete();
                                logBasic(" ------ ");
                                if (!deletefile) {
                                    logError("      " + BaseMessages.getString(PKG,
                                            "JobCopyFiles.Error.Exception.CanRemoveFileFolder",
                                            fileremoventry));
                                } else {
                                    if (isDetailed()) {
                                        logDetailed("      " + BaseMessages.getString(PKG,
                                                "JobCopyFiles.Log.FileFolderRemoved", fileremoventry));
                                    }
                                }
                            }
                        }
                    }

                    // Add files to result files name
                    if (add_result_filesname && !list_add_result.isEmpty()) {
                        String destinationFilefoldername = destinationfilefolder.toString();
                        int trimPathLength = destinationFilefoldername.length() + 1;
                        FileObject addFile;

                        for (Iterator<String> iter = list_add_result.iterator(); iter.hasNext();) {
                            String fileaddentry = iter.next();
                            addFile = null; // re=null each iteration

                            // Try to get the file relative to the existing connection
                            if (fileaddentry.startsWith(destinationFilefoldername)) {
                                if (trimPathLength < fileaddentry.length()) {
                                    addFile = destinationfilefolder
                                            .getChild(fileaddentry.substring(trimPathLength));
                                }
                            }

                            // Unable to retrieve file through existing connection; Get the file through a new VFS connection
                            if (addFile == null) {
                                addFile = KettleVFS.getFileObject(fileaddentry, this);
                            }

                            // Add ONLY Files
                            if (addFile.getType() == FileType.FILE) {
                                ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, addFile,
                                        parentJob.getJobname(), toString());
                                result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
                                if (isDetailed()) {
                                    logDetailed(" ------ ");
                                    logDetailed("      " + BaseMessages.getString(PKG,
                                            "JobCopyFiles.Log.FileAddedToResultFilesName", fileaddentry));
                                }
                            }
                        }
                    }
                }
                entrystatus = true;
            } else {
                // Destination Folder or Parent folder is missing
                logError(BaseMessages.getString(PKG, "JobCopyFiles.Error.DestinationFolderNotFound",
                        realDestinationFilefoldername));
            }
        } else {
            logError(BaseMessages.getString(PKG, "JobCopyFiles.Error.SourceFileNotExists",
                    realSourceFilefoldername));

        }
    } catch (FileSystemException fse) {
        logError(BaseMessages.getString(PKG, "JobCopyFiles.Error.Exception.CopyProcessFileSystemException",
                fse.getMessage()));
        Throwable throwable = fse.getCause();
        while (throwable != null) {
            logError(BaseMessages.getString(PKG, "JobCopyFiles.Log.CausedBy", throwable.getMessage()));
            throwable = throwable.getCause();
        }
    } catch (Exception e) {
        logError(BaseMessages.getString(PKG, "JobCopyFiles.Error.Exception.CopyProcess",
                realSourceFilefoldername, realDestinationFilefoldername, e.getMessage()), e);
    } finally {
        if (sourcefilefolder != null) {
            try {
                sourcefilefolder.close();
                sourcefilefolder = null;
            } catch (IOException ex) { /* Ignore */
            }
        }
        if (destinationfilefolder != null) {
            try {
                destinationfilefolder.close();
                destinationfilefolder = null;
            } catch (IOException ex) { /* Ignore */
            }
        }
    }

    return entrystatus;
}