Example usage for org.apache.commons.vfs AllFileSelector AllFileSelector

List of usage examples for org.apache.commons.vfs AllFileSelector AllFileSelector

Introduction

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

Prototype

AllFileSelector

Source Link

Usage

From source file:org.pentaho.di.job.entries.hadooptransjobexecutor.DistributedCacheUtilTest.java

@Test
public void stagePluginsForCache() throws Exception {
    DistributedCacheUtil ch = new DistributedCacheUtil();

    Configuration conf = new Configuration();
    org.apache.hadoop.fs.FileSystem fs = org.apache.hadoop.fs.FileSystem.getLocal(conf);

    Path pluginsDir = new Path("bin/test/plugins-installation-dir");

    FileObject pluginDir = createTestFolderWithContent();

    try {//w w  w.  jav  a2s  .  c  o m
        ch.stagePluginsForCache(fs, pluginsDir, true, Arrays.asList(pluginDir));
        Path pluginInstallPath = new Path(pluginsDir, pluginDir.getURL().toURI().getPath());
        assertTrue(fs.exists(pluginInstallPath));
        ContentSummary summary = fs.getContentSummary(pluginInstallPath);
        assertEquals(3, summary.getFileCount());
        assertEquals(2, summary.getDirectoryCount());
    } finally {
        pluginDir.delete(new AllFileSelector());
        fs.delete(pluginsDir, true);
    }
}

From source file:org.pentaho.di.job.entries.hadooptransjobexecutor.DistributedCacheUtilTest.java

@Test
public void configureWithpmr() throws Exception {
    DistributedCacheUtil ch = new DistributedCacheUtil();

    Configuration conf = new Configuration();
    org.apache.hadoop.fs.FileSystem fs = org.apache.hadoop.fs.FileSystem.getLocal(conf);

    // This "empty pmr" contains a lib/ folder and some empty kettle-*.jar files but no actual content
    FileObject pmrArchive = KettleVFS.getFileObject("test-res/empty-pmr.zip");

    FileObject bigDataPluginDir = createTestFolderWithContent(
            DistributedCacheUtil.PENTAHO_BIG_DATA_PLUGIN_FOLDER_NAME);

    Path root = new Path("bin/test/installKettleEnvironment");
    try {//from   w  ww  .  jav  a 2s  .  c o  m
        ch.installKettleEnvironment(pmrArchive, fs, root, bigDataPluginDir, null);
        assertTrue(ch.isKettleEnvironmentInstalledAt(fs, root));

        ch.configureWithKettleEnvironment(conf, fs, root);

        // Make sure our libraries are on the classpath
        assertTrue(conf.get("mapred.cache.files").contains("lib/kettle-core.jar"));
        assertTrue(conf.get("mapred.cache.files").contains("lib/kettle-engine.jar"));
        assertTrue(conf.get("mapred.job.classpath.files").contains("lib/kettle-core.jar"));
        assertTrue(conf.get("mapred.job.classpath.files").contains("lib/kettle-engine.jar"));

        // Make sure our plugins folder is registered
        assertTrue(conf.get("mapred.cache.files").contains("#plugins"));

        // Make sure our libraries aren't included twice
        assertFalse(conf.get("mapred.cache.files").contains("#lib"));

        // We should not have individual files registered
        assertFalse(conf.get("mapred.cache.files").contains("pentaho-big-data-plugin/jar1.jar"));
        assertFalse(conf.get("mapred.cache.files").contains("pentaho-big-data-plugin/jar2.jar"));
        assertFalse(conf.get("mapred.cache.files").contains("pentaho-big-data-plugin/folder/file.txt"));

    } finally {
        bigDataPluginDir.delete(new AllFileSelector());
        fs.delete(root, true);
    }
}

From source file:org.pentaho.di.job.entries.movefiles.JobEntryMoveFiles.java

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

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

    try {/*from ww  w  . j  ava2 s. c  o  m*/
        sourcefilefolder = KettleVFS.getFileObject(realSourceFilefoldername, this);
        destinationfilefolder = KettleVFS.getFileObject(realDestinationFilefoldername, this);
        if (!Const.isEmpty(MoveToFolder)) {
            movetofolderfolder = KettleVFS.getFileObject(MoveToFolder, 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 MOVE FOLDER TO FILE !!!

                    log.logError(BaseMessages.getString(PKG, "JobMoveFiles.Log.Forbidden"),
                            BaseMessages.getString(PKG, "JobMoveFiles.Log.CanNotMoveFolderToFile",
                                    realSourceFilefoldername, realDestinationFilefoldername));

                    // Update Errors
                    updateErrors();
                } else {
                    if (destinationfilefolder.getType().equals(FileType.FOLDER)
                            && sourcefilefolder.getType().equals(FileType.FILE)) {
                        // Source is a file, destination is a folder
                        // return destination short filename
                        String shortfilename = sourcefilefolder.getName().getBaseName();

                        try {
                            shortfilename = getDestinationFilename(shortfilename);
                        } catch (Exception e) {
                            logError(BaseMessages.getString(PKG,
                                    BaseMessages.getString(PKG, "JobMoveFiles.Error.GettingFilename",
                                            sourcefilefolder.getName().getBaseName(), e.toString())));
                            return entrystatus;
                        }
                        // Move the file to the destination folder

                        String destinationfilenamefull = KettleVFS.getFilename(destinationfilefolder)
                                + Const.FILE_SEPARATOR + shortfilename;
                        FileObject destinationfile = KettleVFS.getFileObject(destinationfilenamefull, this);

                        entrystatus = MoveFile(shortfilename, sourcefilefolder, destinationfile,
                                movetofolderfolder, parentJob, result);
                        return entrystatus;
                    } else if (sourcefilefolder.getType().equals(FileType.FILE) && destination_is_a_file) {
                        // Source is a file, destination is a file

                        FileObject destinationfile = KettleVFS.getFileObject(realDestinationFilefoldername,
                                this);

                        // return destination short filename
                        String shortfilename = destinationfile.getName().getBaseName();
                        try {
                            shortfilename = getDestinationFilename(shortfilename);
                        } catch (Exception e) {
                            logError(BaseMessages.getString(PKG,
                                    BaseMessages.getString(PKG, "JobMoveFiles.Error.GettingFilename",
                                            sourcefilefolder.getName().getBaseName(), e.toString())));
                            return entrystatus;
                        }

                        String destinationfilenamefull = KettleVFS.getFilename(destinationfile.getParent())
                                + Const.FILE_SEPARATOR + shortfilename;
                        destinationfile = KettleVFS.getFileObject(destinationfilenamefull, this);

                        entrystatus = MoveFile(shortfilename, sourcefilefolder, destinationfile,
                                movetofolderfolder, parentJob, result);
                        return entrystatus;
                    } else {
                        // Both source and destination are folders
                        if (log.isDetailed()) {
                            logDetailed("  ");
                            logDetailed(BaseMessages.getString(PKG, "JobMoveFiles.Log.FetchFolder",
                                    sourcefilefolder.toString()));
                        }

                        FileObject[] fileObjects = sourcefilefolder.findFiles(new AllFileSelector() {
                            public boolean traverseDescendents(FileSelectInfo info) {
                                return true;
                            }

                            public boolean includeFile(FileSelectInfo info) {
                                FileObject fileObject = info.getFile();
                                try {
                                    if (fileObject == null) {
                                        return false;
                                    }
                                } catch (Exception ex) {
                                    // Upon error don't process the file.
                                    return false;
                                } finally {
                                    if (fileObject != null) {
                                        try {
                                            fileObject.close();
                                        } catch (IOException ex) { /* Ignore */
                                        }
                                    }

                                }
                                return true;
                            }
                        });

                        if (fileObjects != null) {
                            for (int j = 0; j < fileObjects.length && !parentJob.isStopped(); j++) {
                                // Success condition broken?
                                if (successConditionBroken) {
                                    if (!successConditionBrokenExit) {
                                        logError(BaseMessages.getString(PKG,
                                                "JobMoveFiles.Error.SuccessConditionbroken", "" + NrErrors));
                                        successConditionBrokenExit = true;
                                    }
                                    return false;
                                }
                                // Fetch files in list one after one ...
                                Currentfile = fileObjects[j];

                                if (!MoveOneFile(Currentfile, sourcefilefolder, realDestinationFilefoldername,
                                        realWildcard, parentJob, result, movetofolderfolder)) {
                                    // Update Errors
                                    updateErrors();
                                }

                            }
                        }
                    }

                }
                entrystatus = true;
            } else {
                // Destination Folder or Parent folder is missing
                logError(BaseMessages.getString(PKG, "JobMoveFiles.Error.DestinationFolderNotFound",
                        realDestinationFilefoldername));
            }
        } else {
            logError(BaseMessages.getString(PKG, "JobMoveFiles.Error.SourceFileNotExists",
                    realSourceFilefoldername));
        }
    } catch (Exception e) {
        logError(BaseMessages.getString(PKG, "JobMoveFiles.Error.Exception.MoveProcess",
                realSourceFilefoldername.toString(), destinationfilefolder.toString(), e.getMessage()));
    } finally {
        if (sourcefilefolder != null) {
            try {
                sourcefilefolder.close();
            } catch (IOException ex) {
                /* Ignore */
            }
        }
        if (destinationfilefolder != null) {
            try {
                destinationfilefolder.close();
            } catch (IOException ex) {
                /* Ignore */
            }
        }
        if (Currentfile != null) {
            try {
                Currentfile.close();
            } catch (IOException ex) {
                /* Ignore */
            }
        }
        if (movetofolderfolder != null) {
            try {
                movetofolderfolder.close();
            } catch (IOException ex) {
                /* Ignore */
            }
        }
    }
    return entrystatus;
}

From source file:org.pentaho.di.job.entries.pgpdecryptfiles.JobEntryPGPDecryptFiles.java

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

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

    try {/* w  w  w . j  a va 2 s . c  om*/

        sourcefilefolder = KettleVFS.getFileObject(realSourceFilefoldername);
        destinationfilefolder = KettleVFS.getFileObject(realDestinationFilefoldername);
        if (!Const.isEmpty(MoveToFolder)) {
            movetofolderfolder = KettleVFS.getFileObject(MoveToFolder);
        }

        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 MOVE FOLDER TO FILE !!!

                    logError(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Log.Forbidden"),
                            BaseMessages.getString(PKG, "JobPGPDecryptFiles.Log.CanNotMoveFolderToFile",
                                    realSourceFilefoldername, realDestinationFilefoldername));

                    // Update Errors
                    updateErrors();
                } else {
                    if (destinationfilefolder.getType().equals(FileType.FOLDER)
                            && sourcefilefolder.getType().equals(FileType.FILE)) {
                        // Source is a file, destination is a folder
                        // return destination short filename
                        String shortfilename = sourcefilefolder.getName().getBaseName();

                        try {
                            shortfilename = getDestinationFilename(sourcefilefolder.getName().getBaseName());
                        } catch (Exception e) {
                            logError(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Error.GettingFilename",
                                    sourcefilefolder.getName().getBaseName(), e.toString()));
                            return entrystatus;
                        }
                        // Move the file to the destination folder

                        String destinationfilenamefull = destinationfilefolder.toString() + Const.FILE_SEPARATOR
                                + shortfilename;
                        FileObject destinationfile = KettleVFS.getFileObject(destinationfilenamefull);

                        entrystatus = DecryptFile(shortfilename, sourcefilefolder, passPhrase, destinationfile,
                                movetofolderfolder, parentJob, result);

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

                        FileObject destinationfile = KettleVFS.getFileObject(realDestinationFilefoldername);

                        // return destination short filename
                        String shortfilename = destinationfile.getName().getBaseName();
                        try {
                            shortfilename = getDestinationFilename(destinationfile.getName().getBaseName());
                        } catch (Exception e) {
                            logError(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Error.GettingFilename",
                                    sourcefilefolder.getName().getBaseName(), e.toString()));
                            return entrystatus;
                        }

                        String destinationfilenamefull = destinationfilefolder.getParent().toString()
                                + Const.FILE_SEPARATOR + shortfilename;
                        destinationfile = KettleVFS.getFileObject(destinationfilenamefull);

                        entrystatus = DecryptFile(shortfilename, sourcefilefolder, passPhrase, destinationfile,
                                movetofolderfolder, parentJob, result);

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

                        FileObject[] fileObjects = sourcefilefolder.findFiles(new AllFileSelector() {
                            public boolean traverseDescendents(FileSelectInfo info) {
                                return info.getDepth() == 0 || include_subfolders;
                            }

                            public boolean includeFile(FileSelectInfo info) {
                                FileObject fileObject = info.getFile();
                                try {
                                    if (fileObject == null) {
                                        return false;
                                    }
                                } catch (Exception ex) {
                                    // Upon error don't process the file.
                                    return false;
                                } finally {
                                    if (fileObject != null) {
                                        try {
                                            fileObject.close();
                                            fileObject = null;
                                        } catch (IOException ex) { /* Ignore */
                                        }
                                    }
                                }
                                return true;
                            }
                        });

                        if (fileObjects != null) {
                            for (int j = 0; j < fileObjects.length && !parentJob.isStopped(); j++) {
                                // Success condition broken?
                                if (successConditionBroken) {
                                    if (!successConditionBrokenExit) {
                                        logError(BaseMessages.getString(PKG,
                                                "JobPGPDecryptFiles.Error.SuccessConditionbroken",
                                                "" + NrErrors));
                                        successConditionBrokenExit = true;
                                    }
                                    return false;
                                }
                                // Fetch files in list one after one ...
                                Currentfile = fileObjects[j];

                                if (!DecryptOneFile(Currentfile, sourcefilefolder, passPhrase,
                                        realDestinationFilefoldername, realWildcard, parentJob, result,
                                        movetofolderfolder)) {
                                    // Update Errors
                                    updateErrors();
                                }

                            }
                        }
                    }
                }
                entrystatus = true;
            } else {
                // Destination Folder or Parent folder is missing
                logError(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Error.DestinationFolderNotFound",
                        realDestinationFilefoldername));
            }
        } else {
            logError(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Error.SourceFileNotExists",
                    realSourceFilefoldername));
        }
    } catch (Exception e) {
        logError(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Error.Exception.MoveProcess",
                realSourceFilefoldername.toString(), destinationfilefolder.toString(), e.getMessage()));
        // Update Errors
        updateErrors();
    } finally {
        if (sourcefilefolder != null) {
            try {
                sourcefilefolder.close();
            } catch (IOException ex) { /* Ignore */
            }
        }
        if (destinationfilefolder != null) {
            try {
                destinationfilefolder.close();
            } catch (IOException ex) { /* Ignore */
            }
        }
        if (Currentfile != null) {
            try {
                Currentfile.close();
            } catch (IOException ex) { /* Ignore */
            }
        }
        if (movetofolderfolder != null) {
            try {
                movetofolderfolder.close();
            } catch (IOException ex) { /* Ignore */
            }
        }
    }
    return entrystatus;
}

From source file:org.pentaho.di.job.entries.pgpencryptfiles.JobEntryPGPEncryptFiles.java

private boolean ProcessFileFolder(int actionType, String sourcefilefoldername, String userID,
        String destinationfilefoldername, String wildcard, Job parentJob, Result result, String MoveToFolder) {
    boolean entrystatus = false;
    FileObject sourcefilefolder = null;
    FileObject destinationfilefolder = null;
    FileObject movetofolderfolder = null;
    FileObject Currentfile = null;

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

    try {/*from  w ww.ja  va 2s  . c o m*/

        sourcefilefolder = KettleVFS.getFileObject(realSourceFilefoldername);
        destinationfilefolder = KettleVFS.getFileObject(realDestinationFilefoldername);
        if (!Const.isEmpty(MoveToFolder)) {
            movetofolderfolder = KettleVFS.getFileObject(MoveToFolder);
        }

        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 MOVE FOLDER TO FILE !!!

                    logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.Forbidden"),
                            BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.CanNotMoveFolderToFile",
                                    realSourceFilefoldername, realDestinationFilefoldername));

                    // Update Errors
                    updateErrors();
                } else {
                    if (destinationfilefolder.getType().equals(FileType.FOLDER)
                            && sourcefilefolder.getType().equals(FileType.FILE)) {
                        // Source is a file, destination is a folder
                        // return destination short filename
                        String shortfilename = sourcefilefolder.getName().getBaseName();

                        try {
                            shortfilename = getDestinationFilename(sourcefilefolder.getName().getBaseName());
                        } catch (Exception e) {
                            logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Error.GettingFilename",
                                    sourcefilefolder.getName().getBaseName(), e.toString()));
                            return entrystatus;
                        }
                        // Move the file to the destination folder

                        String destinationfilenamefull = destinationfilefolder.toString() + Const.FILE_SEPARATOR
                                + shortfilename;
                        FileObject destinationfile = KettleVFS.getFileObject(destinationfilenamefull);

                        entrystatus = EncryptFile(actionType, shortfilename, sourcefilefolder, realuserID,
                                destinationfile, movetofolderfolder, parentJob, result);

                    } else if (sourcefilefolder.getType().equals(FileType.FILE) && destination_is_a_file) {

                        // Source is a file, destination is a file

                        FileObject destinationfile = KettleVFS.getFileObject(realDestinationFilefoldername);

                        // return destination short filename
                        String shortfilename = destinationfile.getName().getBaseName();
                        try {
                            shortfilename = getDestinationFilename(destinationfile.getName().getBaseName());
                        } catch (Exception e) {
                            logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Error.GettingFilename",
                                    sourcefilefolder.getName().getBaseName(), e.toString()));
                            return entrystatus;
                        }

                        String destinationfilenamefull = destinationfilefolder.getParent().toString()
                                + Const.FILE_SEPARATOR + shortfilename;
                        destinationfile = KettleVFS.getFileObject(destinationfilenamefull);

                        entrystatus = EncryptFile(actionType, shortfilename, sourcefilefolder, realuserID,
                                destinationfile, movetofolderfolder, parentJob, result);

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

                        FileObject[] fileObjects = sourcefilefolder.findFiles(new AllFileSelector() {
                            public boolean traverseDescendents(FileSelectInfo info) {
                                return info.getDepth() == 0 || include_subfolders;
                            }

                            public boolean includeFile(FileSelectInfo info) {
                                FileObject fileObject = info.getFile();
                                try {
                                    if (fileObject == null) {
                                        return false;
                                    }
                                } catch (Exception ex) {
                                    // Upon error don't process the file.
                                    return false;
                                } finally {
                                    if (fileObject != null) {
                                        try {
                                            fileObject.close();
                                            fileObject = null;
                                        } catch (IOException ex) { /* Ignore */
                                        }
                                    }
                                }
                                return true;
                            }
                        });

                        if (fileObjects != null) {
                            for (int j = 0; j < fileObjects.length && !parentJob.isStopped(); j++) {
                                // Success condition broken?
                                if (successConditionBroken) {
                                    if (!successConditionBrokenExit) {
                                        logError(BaseMessages.getString(PKG,
                                                "JobPGPEncryptFiles.Error.SuccessConditionbroken",
                                                "" + NrErrors));
                                        successConditionBrokenExit = true;
                                    }
                                    return false;
                                }
                                // Fetch files in list one after one ...
                                Currentfile = fileObjects[j];

                                if (!EncryptOneFile(actionType, Currentfile, sourcefilefolder, realuserID,
                                        realDestinationFilefoldername, realWildcard, parentJob, result,
                                        movetofolderfolder)) {
                                    // Update Errors
                                    updateErrors();
                                }

                            }
                        }
                    }
                }
                entrystatus = true;
            } else {
                // Destination Folder or Parent folder is missing
                logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Error.DestinationFolderNotFound",
                        realDestinationFilefoldername));
            }
        } else {
            logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Error.SourceFileNotExists",
                    realSourceFilefoldername));
        }
    } catch (Exception e) {
        logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Error.Exception.MoveProcess",
                realSourceFilefoldername.toString(), destinationfilefolder.toString(), e.getMessage()));
        // Update Errors
        updateErrors();
    } finally {
        if (sourcefilefolder != null) {
            try {
                sourcefilefolder.close();
            } catch (IOException ex) { /* Ignore */
            }
        }
        if (destinationfilefolder != null) {
            try {
                destinationfilefolder.close();
            } catch (IOException ex) { /* Ignore */
            }
        }
        if (Currentfile != null) {
            try {
                Currentfile.close();
            } catch (IOException ex) { /* Ignore */
            }
        }
        if (movetofolderfolder != null) {
            try {
                movetofolderfolder.close();
            } catch (IOException ex) { /* Ignore */
            }
        }
    }
    return entrystatus;
}

From source file:org.pentaho.di.job.entries.talendjobexec.JobEntryTalendJobExec.java

private URL[] prepareJarFiles(FileObject zipFile) throws Exception {

    // zip:file:///tmp/foo.zip
    FileInputList fileList = FileInputList.createFileList(this, new String[] { "zip:" + zipFile.toString(), },
            new String[] { ".*\\.jar$", }, // Include mask: only jar files
            new String[] { ".*classpath\\.jar$", }, // Exclude mask: only jar files
            new String[] { "Y", }, // File required
            new boolean[] { true, }); // Search sub-directories

    List<URL> files = new ArrayList<URL>();

    // Copy the jar files in the temp folder...
    ///*from   w w  w .  j  a  v  a  2  s. c o  m*/
    for (FileObject file : fileList.getFiles()) {
        FileObject jarfilecopy = KettleVFS.createTempFile(file.getName().getBaseName(), ".jar",
                environmentSubstitute("${java.io.tmpdir}"));
        jarfilecopy.copyFrom(file, new AllFileSelector());
        files.add(jarfilecopy.getURL());
    }

    return files.toArray(new URL[files.size()]);
}

From source file:org.pentaho.di.job.entries.unzip.JobEntryUnZip.java

private boolean unzipFile(FileObject sourceFileObject, String realTargetdirectory, String realWildcard,
        String realWildcardExclude, Result result, Job parentJob, FileObject fileObject, FileObject movetodir,
        String realMovetodirectory) {
    boolean retval = false;
    String unzipToFolder = realTargetdirectory;
    try {//from  www .  java  2s . co m

        if (log.isDetailed()) {
            logDetailed(
                    BaseMessages.getString(PKG, "JobUnZip.Log.ProcessingFile", sourceFileObject.toString()));
        }

        // Do you create a root folder?
        //
        if (rootzip) {
            String shortSourceFilename = sourceFileObject.getName().getBaseName();
            int lenstring = shortSourceFilename.length();
            int lastindexOfDot = shortSourceFilename.lastIndexOf('.');
            if (lastindexOfDot == -1) {
                lastindexOfDot = lenstring;
            }

            String foldername = realTargetdirectory + "/" + shortSourceFilename.substring(0, lastindexOfDot);
            FileObject rootfolder = KettleVFS.getFileObject(foldername, this);
            if (!rootfolder.exists()) {
                try {
                    rootfolder.createFolder();
                    if (log.isDetailed()) {
                        logDetailed(BaseMessages.getString(PKG, "JobUnZip.Log.RootFolderCreated", foldername));
                    }
                } catch (Exception e) {
                    throw new Exception(
                            BaseMessages.getString(PKG, "JobUnZip.Error.CanNotCreateRootFolder", foldername),
                            e);
                }
            }
            unzipToFolder = foldername;
        }

        // Try to read the entries from the VFS object...
        //
        String zipFilename = "zip:" + sourceFileObject.getName().getFriendlyURI();
        FileObject zipFile = KettleVFS.getFileObject(zipFilename, this);
        FileObject[] items = zipFile.findFiles(new AllFileSelector() {
            public boolean traverseDescendents(FileSelectInfo info) {
                return true;
            }

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

                FileObject fileObject = info.getFile();
                return fileObject != null;
            }
        });

        Pattern pattern = null;
        if (!Const.isEmpty(realWildcard)) {
            pattern = Pattern.compile(realWildcard);

        }
        Pattern patternexclude = null;
        if (!Const.isEmpty(realWildcardExclude)) {
            patternexclude = Pattern.compile(realWildcardExclude);

        }

        for (FileObject item : items) {

            if (successConditionBroken) {
                if (!successConditionBrokenExit) {
                    logError(BaseMessages.getString(PKG, "JobUnZip.Error.SuccessConditionbroken",
                            "" + NrErrors));
                    successConditionBrokenExit = true;
                }
                return false;
            }

            synchronized (KettleVFS.getInstance().getFileSystemManager()) {
                FileObject newFileObject = null;
                try {
                    if (log.isDetailed()) {
                        logDetailed(BaseMessages.getString(PKG, "JobUnZip.Log.ProcessingZipEntry",
                                item.getName().getURI(), sourceFileObject.toString()));
                    }

                    // get real destination filename
                    //
                    String newFileName = unzipToFolder + Const.FILE_SEPARATOR + getTargetFilename(item);
                    newFileObject = KettleVFS.getFileObject(newFileName, this);

                    if (item.getType().equals(FileType.FOLDER)) {
                        // Directory
                        //
                        if (log.isDetailed()) {
                            logDetailed(BaseMessages.getString(PKG, "JobUnZip.CreatingDirectory.Label",
                                    newFileName));
                        }

                        // Create Directory if necessary ...
                        //
                        if (!newFileObject.exists()) {
                            newFileObject.createFolder();
                        }
                    } else {
                        // File
                        //
                        boolean getIt = true;
                        boolean getItexclude = false;

                        // First see if the file matches the regular expression!
                        //
                        if (pattern != null) {
                            Matcher matcher = pattern.matcher(item.getName().getURI());
                            getIt = matcher.matches();
                        }

                        if (patternexclude != null) {
                            Matcher matcherexclude = patternexclude.matcher(item.getName().getURI());
                            getItexclude = matcherexclude.matches();
                        }

                        boolean take = takeThisFile(item, newFileName);

                        if (getIt && !getItexclude && take) {
                            if (log.isDetailed()) {
                                logDetailed(BaseMessages.getString(PKG, "JobUnZip.ExtractingEntry.Label",
                                        item.getName().getURI(), newFileName));
                            }

                            if (iffileexist == IF_FILE_EXISTS_UNIQ) {
                                // Create file with unique name

                                int lenstring = newFileName.length();
                                int lastindexOfDot = newFileName.lastIndexOf('.');
                                if (lastindexOfDot == -1) {
                                    lastindexOfDot = lenstring;
                                }

                                newFileName = newFileName.substring(0, lastindexOfDot)
                                        + StringUtil.getFormattedDateTimeNow(true)
                                        + newFileName.substring(lastindexOfDot, lenstring);

                                if (log.isDebug()) {
                                    logDebug(BaseMessages.getString(PKG, "JobUnZip.Log.CreatingUniqFile",
                                            newFileName));
                                }
                            }

                            // See if the folder to the target file exists...
                            //
                            if (!newFileObject.getParent().exists()) {
                                newFileObject.getParent().createFolder(); // creates the whole path.
                            }
                            InputStream is = null;
                            OutputStream os = null;

                            try {
                                is = KettleVFS.getInputStream(item);
                                os = KettleVFS.getOutputStream(newFileObject, false);

                                if (is != null) {
                                    byte[] buff = new byte[2048];
                                    int len;

                                    while ((len = is.read(buff)) > 0) {
                                        os.write(buff, 0, len);
                                    }

                                    // Add filename to result filenames
                                    addFilenameToResultFilenames(result, parentJob, newFileName);
                                }
                            } finally {
                                if (is != null) {
                                    is.close();
                                }
                                if (os != null) {
                                    os.close();
                                }
                            }
                        } // end if take
                    }
                } catch (Exception e) {
                    updateErrors();
                    logError(BaseMessages.getString(PKG, "JobUnZip.Error.CanNotProcessZipEntry",
                            item.getName().getURI(), sourceFileObject.toString()), e);
                } finally {
                    if (newFileObject != null) {
                        try {
                            newFileObject.close();
                            if (setOriginalModificationDate) {
                                // Change last modification date
                                newFileObject.getContent()
                                        .setLastModifiedTime(item.getContent().getLastModifiedTime());
                            }
                        } catch (Exception e) { /* Ignore */
                        } // ignore this
                    }
                    // Close file object
                    // close() does not release resources!
                    KettleVFS.getInstance().getFileSystemManager().closeFileSystem(item.getFileSystem());
                    if (items != null) {
                        items = null;
                    }
                }
            } // Synchronized block on KettleVFS.getInstance().getFileSystemManager()
        } // End for

        // Here gc() is explicitly called if e.g. createfile is used in the same
        // job for the same file. The problem is that after creating the file the
        // file object is not properly garbaged collected and thus the file cannot
        // be deleted anymore. This is a known problem in the JVM.

        // System.gc();

        // Unzip done...
        if (afterunzip == 1) {
            // delete zip file
            boolean deleted = fileObject.delete();
            if (!deleted) {
                updateErrors();
                logError(BaseMessages.getString(PKG, "JobUnZip.Cant_Delete_File.Label",
                        sourceFileObject.toString()));
            }
            // File deleted
            if (log.isDebug()) {
                logDebug(BaseMessages.getString(PKG, "JobUnZip.File_Deleted.Label",
                        sourceFileObject.toString()));
            }
        } else if (afterunzip == 2) {
            FileObject destFile = null;
            // Move File
            try {
                String destinationFilename = movetodir + Const.FILE_SEPARATOR
                        + fileObject.getName().getBaseName();
                destFile = KettleVFS.getFileObject(destinationFilename, this);

                fileObject.moveTo(destFile);

                // File moved
                if (log.isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "JobUnZip.Log.FileMovedTo",
                            sourceFileObject.toString(), realMovetodirectory));
                }
            } catch (Exception e) {
                updateErrors();
                logError(BaseMessages.getString(PKG, "JobUnZip.Cant_Move_File.Label",
                        sourceFileObject.toString(), realMovetodirectory, e.getMessage()));
            } finally {
                if (destFile != null) {
                    try {
                        destFile.close();
                    } catch (IOException ex) { /* Ignore */
                    }
                }
            }
        }

        retval = true;
    } catch (Exception e) {
        updateErrors();
        log.logError(BaseMessages.getString(PKG, "JobUnZip.Error.Label"), BaseMessages.getString(PKG,
                "JobUnZip.ErrorUnzip.Label", sourceFileObject.toString(), e.getMessage()), e);
    }

    return retval;
}

From source file:org.pentaho.di.job.entries.xmlwellformed.JobEntryXMLWellFormed.java

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

    // Get real source file and wilcard
    String realSourceFilefoldername = environmentSubstitute(sourcefilefoldername);
    if (Const.isEmpty(realSourceFilefoldername)) {
        logError(BaseMessages.getString(PKG, "JobXMLWellFormed.log.FileFolderEmpty", sourcefilefoldername));
        // Update Errors
        updateErrors();/*from   w  w  w .  j a  va 2 s .c o  m*/

        return entrystatus;
    }
    String realWildcard = environmentSubstitute(wildcard);

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

        if (sourcefilefolder.exists()) {
            if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobXMLWellFormed.Log.FileExists",
                        sourcefilefolder.toString()));
            }
            if (sourcefilefolder.getType() == FileType.FILE) {
                entrystatus = checkOneFile(sourcefilefolder, result, parentJob);

            } else if (sourcefilefolder.getType() == FileType.FOLDER) {
                FileObject[] fileObjects = sourcefilefolder.findFiles(new AllFileSelector() {
                    public boolean traverseDescendents(FileSelectInfo info) {
                        return true;
                    }

                    public boolean includeFile(FileSelectInfo info) {

                        FileObject fileObject = info.getFile();
                        try {
                            if (fileObject == null) {
                                return false;
                            }
                            if (fileObject.getType() != FileType.FILE) {
                                return false;
                            }
                        } catch (Exception ex) {
                            // Upon error don't process the file.
                            return false;
                        } finally {
                            if (fileObject != null) {
                                try {
                                    fileObject.close();
                                } catch (IOException ex) {
                                    /* Ignore */
                                }
                            }

                        }
                        return true;
                    }
                });

                if (fileObjects != null) {
                    for (int j = 0; j < fileObjects.length && !parentJob.isStopped(); j++) {
                        if (successConditionBroken) {
                            if (!successConditionBrokenExit) {
                                logError(BaseMessages.getString(PKG,
                                        "JobXMLWellFormed.Error.SuccessConditionbroken", "" + NrAllErrors));
                                successConditionBrokenExit = true;
                            }
                            return false;
                        }
                        // Fetch files in list one after one ...
                        CurrentFile = fileObjects[j];

                        if (!CurrentFile.getParent().toString().equals(sourcefilefolder.toString())) {
                            // Not in the Base Folder..Only if include sub folders
                            if (include_subfolders) {
                                if (GetFileWildcard(CurrentFile.toString(), realWildcard)) {
                                    checkOneFile(CurrentFile, result, parentJob);
                                }
                            }

                        } else {
                            // In the base folder
                            if (GetFileWildcard(CurrentFile.toString(), realWildcard)) {
                                checkOneFile(CurrentFile, result, parentJob);
                            }
                        }
                    }
                }
            } else {
                logError(BaseMessages.getString(PKG, "JobXMLWellFormed.Error.UnknowFileFormat",
                        sourcefilefolder.toString()));
                // Update Errors
                updateErrors();
            }
        } else {
            logError(BaseMessages.getString(PKG, "JobXMLWellFormed.Error.SourceFileNotExists",
                    realSourceFilefoldername));
            // Update Errors
            updateErrors();
        }
    } catch (Exception e) {
        logError(BaseMessages.getString(PKG, "JobXMLWellFormed.Error.Exception.Processing",
                realSourceFilefoldername.toString(), e));
        // Update Errors
        updateErrors();
    } finally {
        if (sourcefilefolder != null) {
            try {
                sourcefilefolder.close();
            } catch (IOException ex) {
                /* Ignore */
            }

        }
        if (CurrentFile != null) {
            try {
                CurrentFile.close();
            } catch (IOException ex) {
                /* Ignore */
            }
        }
    }
    return entrystatus;
}

From source file:org.vivoweb.harvester.util.FileAide.java

/**
 * Deletes the file at the given path//from w w w .j a v a 2  s.co m
 * @param path the path to delete
 * @return true if deleted, false otherwise
 * @throws IOException error resolving path
 */
public static boolean delete(String path) throws IOException {
    FileObject file = getFileObject(path);
    if (!file.exists()) {
        return true;
    }
    if (isFolder(path)) {
        try {
            for (FileObject subFile : file.findFiles(new AllFileSelector())) {
                try {
                    String subPath = subFile.getName().getPath();
                    if (!subPath.equals(path)) {
                        delete(subPath);
                    }
                } catch (FileSystemException e) {
                    //log.trace(e.getMessage(), e);
                }
            }
            file.delete(new AllFileSelector());
        } catch (FileSystemException e) {
            //log.trace(e.getMessage(), e);
            throw new IOException("Error deleting file!");
        }
    }
    return file.delete();
}

From source file:org.vivoweb.harvester.util.FileAide.java

/**
 * Get an inputstream from the first file under the given path with a matching fileName
 * @param path the path to search under/*from   w  ww  .j a v a2s  .c  o  m*/
 * @param fileName the file name to match
 * @return an input stream to the matched file, null if none found
 * @throws IOException error resolving path
 */
public static InputStream getFirstFileNameChildInputStream(String path, String fileName) throws IOException {
    for (FileObject file : FileAide.getFileObject(path).findFiles(new AllFileSelector())) {
        if (file.getName().getBaseName().equals(fileName)) {
            return file.getContent().getInputStream();
        }
    }
    return null;
}