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

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

Introduction

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

Prototype

public FileObject[] findFiles(FileSelector selector) throws FileSystemException;

Source Link

Document

Finds the set of matching descendents of this file, in depthwise order.

Usage

From source file:com.newatlanta.appengine.junit.vfs.provider.GaeProviderTestCase.java

/**
  * Returns the base folder for tests. Copies test files from the local file
  * system to GaeVFS. Note that SVN (.svn) folders are not copied; if the are,
  * then the size of the LRUFilesCache created within GaeFileSystemManager.prepare()
  * must be increased to avoid testcase failures.
  *///from   ww  w  . j  a v  a 2 s .com
@Override
public FileObject getBaseTestFolder(FileSystemManager manager) throws Exception {
    FileObject gaeTestBaseDir = manager.getBaseFile().resolveFile("test-data");
    if (!gaeTestBaseDir.exists()) {
        FileObject localTestBaseDir = manager
                .resolveFile("file://" + GaeFileNameParser.getRootPath(manager.getBaseFile().getName())
                        + gaeTestBaseDir.getName().getPath());
        gaeTestBaseDir.copyFrom(localTestBaseDir, new TestFileSelector());
        // confirm that the correct number of files were copied
        FileObject[] testFiles = localTestBaseDir.findFiles(new TestFileSelector());
        FileObject[] gaeFiles = gaeTestBaseDir.findFiles(Selectors.SELECT_FILES);
        assertEquals(testFiles.length, gaeFiles.length);
    }
    return gaeTestBaseDir;
}

From source file:com.panet.imeta.job.entries.folderisempty.JobEntryFolderIsEmpty.java

public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = previousResult;
    result.setResult(false);//  www .j  a  va  2s . co  m
    result.setNrErrors(1);

    filescount = 0;
    folderscount = 0;
    pattern = null;

    if (!Const.isEmpty(getWildcard()))
        pattern = Pattern.compile(getRealWildcard());

    if (foldername != null) {
        String realFoldername = getRealFoldername();
        FileObject FolderObject = null;
        try {
            FolderObject = KettleVFS.getFileObject(realFoldername);

            if (FolderObject.exists()) {
                //Check if it's a folder
                if (FolderObject.getType() == FileType.FOLDER) {
                    // File provided is a folder, so we can process ...
                    FolderObject.findFiles(new TextFileSelector(FolderObject.toString()));
                    if (log.isBasic())
                        log.logBasic("Total files", "We found : " + filescount + " file(s)");
                    if (filescount == 0) {
                        result.setResult(true);
                        result.setNrErrors(0);
                    }
                } else {
                    // Not a folder, fail
                    log.logError("Found files", "[" + realFoldername + "] is not a folder, failing.");
                }
            } else {
                //  No Folder found   
                if (log.isBasic())
                    log.logBasic(toString(), "we can not find [" + realFoldername + "] !");
            }
        } catch (IOException e) {
            log.logError(toString(),
                    "Could not create Folder [" + realFoldername + "], exception: " + e.getMessage());
            result.setResult(false);
            result.setNrErrors(1);
        } finally {
            if (FolderObject != null) {
                try {
                    FolderObject.close();
                } catch (IOException ex) {
                }
                ;
            }
        }
    } else {
        log.logError(toString(), "No Foldername is defined.");
    }

    return result;
}

From source file:com.pongasoft.kiwidoc.builder.doclet.SourceCodeParser.java

/**
 * Parses the sources using a doclet. It is ok to provide a big number of files, since it will
 * automatically be split in chunks.//w ww  .  java 2  s .c  om
 *
 * @param library the library to store the results
 * @param sources the sources
 * @return the number of processed files
 * @throws IOException if there is an issue reading the files
 */
public int parseSources(LibraryModelBuilder library, FileObject sources, String overviewFilename,
        FileObject javadoc, Collection<FileObject> dependencies) throws IOException, InternalException {
    DefaultFileSystemManager dfs = new DefaultFileSystemManager();
    dfs.addProvider("file", new DefaultLocalFileProvider());
    dfs.setReplicator(new DefaultFileReplicator(IOUtils.createTempDirectory("SourceCodeParser", "")));
    dfs.init();
    try {
        File localSources = dfs.getReplicator().replicateFile(sources, SourcesSelector.INSTANCE);

        sources = dfs.toFileObject(localSources);

        FileObject[] allSources = sources.findFiles(JavaSelector.INSTANCE);

        if (allSources == null || allSources.length == 0)
            return 0;

        List<String> sourcePath = new ArrayList<String>();

        for (FileObject sourceFile : allSources) {
            //        if(javadoc != null)
            //        {
            //          String name = sources.getName().getRelativeName(sourceFile.getName());
            //          name = name.substring(0, name.length() - JAVA_EXTENSION.length());
            //          name += HTML_EXTENSION;
            //          if(javadoc.resolveFile(name, NameScope.DESCENDENT).exists())
            //            sourcePath.add(sourceFile.getName().getPath());
            //        }
            //        else
            //        {
            //          sourcePath.add(sourceFile.getName().getPath());
            //        }
            sourcePath.add(sourceFile.getName().getPath());
        }

        List<String> deps = new ArrayList<String>();

        if (dependencies != null) {
            for (FileObject dependency : dependencies) {
                if (dependency.exists()) {
                    File localDependency = dfs.getReplicator().replicateFile(dependency,
                            DependenciesSelector.INSTANCE);
                    deps.add(localDependency.getCanonicalPath());
                }
            }
        }

        FileObject overviewFile = sources.resolveFile(overviewFilename, NameScope.CHILD);

        String overviewPath = null;
        if (overviewFile.exists())
            overviewPath = overviewFile.getName().getPath();

        parseSources(library, overviewPath, sourcePath, deps);

        return sourcePath.size();
    } finally {
        dfs.close();
    }
}

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

public void testMoveDeepFolder() throws FileSystemException {
    FileObject origFolder = ROOT.resolveFile(FOLDER);
    origFolder.delete(ALL_FILE_SELECTOR);
    origFolder.createFolder();/*  w  ww .  ja va2 s . c  o  m*/

    origFolder.resolveFile("file.0").createFile();
    origFolder.resolveFile("file.1").createFile();
    origFolder.resolveFile("file.2").createFile();
    origFolder.resolveFile("subfolder").createFolder();
    origFolder.resolveFile("subfolder").resolveFile("subfile.0").createFile();
    origFolder.resolveFile("subfolder").resolveFile("subfile.1").createFile();
    origFolder.resolveFile("subfolder").resolveFile("subfile.2").createFile();

    FileObject[] origFiles = origFolder.findFiles(ALL_FILE_SELECTOR);
    assertEquals(8, origFiles.length);

    FileObject destFolder = ROOT.resolveFile(FOLDER + "_dest");
    destFolder.delete(ALL_FILE_SELECTOR);
    assertFalse(destFolder.exists());

    origFolder.moveTo(destFolder);
    assertFalse(origFolder.exists());
    assertTrue(destFolder.exists());

    FileObject[] destFiles = destFolder.findFiles(ALL_FILE_SELECTOR);
    assertEquals(8, destFiles.length);

    destFolder.delete(ALL_FILE_SELECTOR);

    assertFalse(origFolder.exists());
    assertFalse(destFolder.exists());
}

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

public void testCopyShallowFolder() throws FileSystemException {
    FileObject origFolder = ROOT.resolveFile(FOLDER);
    origFolder.delete(ALL_FILE_SELECTOR);
    origFolder.createFolder();//from w w  w  . j av a 2  s  .c om

    origFolder.resolveFile("file.0").createFile();
    origFolder.resolveFile("file.1").createFile();
    origFolder.resolveFile("file.2").createFile();

    System.out.println(Arrays.asList(origFolder.getChildren()));
    assertEquals(3, origFolder.getChildren().length);

    FileObject destFolder = ROOT.resolveFile(FOLDER + "_dest");
    assertFalse(destFolder.exists());
    destFolder.copyFrom(origFolder, new DepthFileSelector(1));
    assertTrue(destFolder.exists());

    assertEquals(3, destFolder.getChildren().length);

    FileObject[] origFiles = origFolder.findFiles(new DepthFileSelector(1));
    FileObject[] destFiles = destFolder.findFiles(new DepthFileSelector(1));
    for (int i = 0; i < origFiles.length; i++) {
        assertEquals(origFiles[i].getName().getRelativeName(origFolder.getName()),
                destFiles[i].getName().getRelativeName(destFolder.getName()));
    }

    origFolder.delete(ALL_FILE_SELECTOR);
    destFolder.delete(ALL_FILE_SELECTOR);

    assertFalse(origFolder.exists());
    assertFalse(destFolder.exists());
}

From source file:com.sonatype.nexus.plugin.groovyconsole.DefaultScriptStorage.java

public void initialize() throws InitializationException {
    scripts = new LinkedHashMap<String, String>();

    FileObject listendir;
    try {/* w  ww.ja v  a  2s .  c  o  m*/
        FileSystemManager fsManager = VFS.getManager();
        scriptDir = applicationConfiguration.getWorkingDirectory("scripts");
        if (!scriptDir.exists()) {
            scriptDir.mkdirs();

            try {
                new File(scriptDir, "place your .groovy files here.txt").createNewFile();
            } catch (IOException e) {
                throw new InitializationException(e.getMessage(), e);
            }
        }

        listendir = fsManager.resolveFile(scriptDir.getAbsolutePath());
    } catch (FileSystemException e) {
        throw new InitializationException(e.getMessage(), e);
    }

    FileSelector selector = new FileSelector() {
        public boolean traverseDescendents(FileSelectInfo arg0) throws Exception {
            return true;
        }

        public boolean includeFile(FileSelectInfo arg0) throws Exception {
            return isScriptFile(arg0.getFile());
        }
    };

    try {
        FileObject[] availableScripts = listendir.findFiles(selector);
        for (FileObject fileObject : availableScripts) {
            updateScript(fileObject);
        }
    } catch (FileSystemException e) {
        getLogger().warn("Unable to perform initial directory scan.", e);
    }

    DefaultFileMonitor fm = new DefaultFileMonitor(this);
    fm.setRecursive(true);
    fm.addFile(listendir);
    fm.start();

    this.fileMonitor = fm;
}

From source file:com.panet.imeta.job.entries.unzip.JobEntryUnZip.java

private boolean unzipFile(LogWriter log, FileObject sourceFileObject, String realTargetdirectory,
        String realWildcard, String realWildcardExclude, Result result, Job parentJob, FileObject fileObject,
        FileObject movetodir, String realMovetodirectory) {
    boolean retval = false;

    try {//  www .jav a 2s. c o m

        if (log.isDetailed())
            log.logDetailed(toString(),
                    Messages.getString("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);
            if (!rootfolder.exists()) {
                try {
                    rootfolder.createFolder();
                    if (log.isDetailed())
                        log.logDetailed(toString(),
                                Messages.getString("JobUnZip.Log.RootFolderCreated", foldername));
                } catch (Exception e) {
                    throw new Exception(Messages.getString("JobUnZip.Error.CanNotCreateRootFolder", foldername),
                            e);
                }
            }
        }

        // Try to read the entries from the VFS object...
        //
        String zipFilename = "zip:" + sourceFileObject.getName().getFriendlyURI();
        FileObject zipFile = KettleVFS.getFileObject(zipFilename);
        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) {
                    log.logError(toString(),
                            Messages.getString("JobUnZip.Error.SuccessConditionbroken", "" + NrErrors));
                    successConditionBrokenExit = true;
                }
                return false;
            }

            try {
                if (log.isDetailed())
                    log.logDetailed(toString(), Messages.getString("JobUnZip.Log.ProcessingZipEntry",
                            item.getName().getURI(), sourceFileObject.toString()));

                // get real destination filename
                //
                String newFileName = realTargetdirectory + Const.FILE_SEPARATOR
                        + getTargetFilename(item.getName().getPath());
                FileObject newFileObject = KettleVFS.getFileObject(newFileName);

                if (item.getType().equals(FileType.FOLDER)) {
                    // Directory
                    //
                    if (log.isDetailed())
                        log.logDetailed(toString(),
                                Messages.getString("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(log, item, newFileName);

                    if (getIt && !getItexclude && take) {
                        if (log.isDetailed())
                            log.logDetailed(toString(), Messages.getString("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())
                                log.logDebug(toString(),
                                        Messages.getString("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();
                log.logError(toString(), Messages.getString("JobUnZip.Error.CanNotProcessZipEntry",
                        item.getName().getURI(), sourceFileObject.toString()), e);
            }
        } // End while

        // 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();
                log.logError(toString(),
                        Messages.getString("JobUnZip.Cant_Delete_File.Label", sourceFileObject.toString()));
            }
            // File deleted
            if (log.isDebug())
                log.logDebug(toString(),
                        Messages.getString("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);

                fileObject.moveTo(destFile);

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

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

    return retval;
}

From source file:com.panet.imeta.job.entries.addresultfilenames.JobEntryAddResultFilenames.java

private boolean ProcessFile(String filename, String wildcard, Job parentJob, Result result) {
    LogWriter log = LogWriter.getInstance();

    boolean rcode = false;
    FileObject filefolder = null;
    String realFilefoldername = environmentSubstitute(filename);
    String realwildcard = environmentSubstitute(wildcard);

    try {//from  w w w  .  ja  va2 s . co  m
        filefolder = KettleVFS.getFileObject(realFilefoldername);

        // 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();

        if (filefolder.exists()) {
            // the file or folder exists

            if (filefolder.getType() == FileType.FILE) {
                // Add filename to Resultfilenames ...
                if (log.isDetailed())
                    log.logDetailed(toString(), Messages
                            .getString("JobEntryAddResultFilenames.AddingFileToResult", filefolder.toString()));
                ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL,
                        KettleVFS.getFileObject(filefolder.toString()), parentJob.getJobname(), toString());
                result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
            } else {
                FileObject list[] = filefolder
                        .findFiles(new TextFileSelector(filefolder.toString(), realwildcard));

                for (int i = 0; i < list.length && !parentJob.isStopped(); i++) {
                    // Add filename to Resultfilenames ...
                    if (log.isDetailed())
                        log.logDetailed(toString(), Messages.getString(
                                "JobEntryAddResultFilenames.AddingFileToResult", list[i].toString()));
                    ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL,
                            KettleVFS.getFileObject(list[i].toString()), parentJob.getJobname(), toString());
                    result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
                }
            }

        } else {
            // File can not be found
            if (log.isBasic())
                log.logBasic(toString(),
                        Messages.getString("JobEntryAddResultFilenames.FileCanNotbeFound", realFilefoldername)); //$NON-NLS-1$
            rcode = true;
        }
    } catch (IOException e) {
        log.logError(toString(), Messages.getString("JobEntryAddResultFilenames.CouldNotProcess", //$NON-NLS-1$
                realFilefoldername, e.getMessage()));
    } finally {
        if (filefolder != null) {
            try {
                filefolder.close();
            } catch (IOException ex) {
            }
            ;
        }
    }

    return rcode;
}

From source file:com.panet.imeta.job.entries.xmlwellformed.JobEntryXMLWellFormed.java

private boolean ProcessFileFolder(String sourcefilefoldername, String wildcard, Job parentJob, Result result) {
    LogWriter log = LogWriter.getInstance();
    boolean entrystatus = false;
    FileObject sourcefilefolder = null;
    FileObject CurrentFile = null;

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

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

    try {
        sourcefilefolder = KettleVFS.getFileObject(realSourceFilefoldername);

        if (sourcefilefolder.exists()) {
            if (log.isDetailed())
                log.logDetailed(toString(),
                        Messages.getString("JobXMLWellFormed.Log.FileExists", sourcefilefolder.toString()));
            if (sourcefilefolder.getType() == FileType.FILE) {
                entrystatus = checkOneFile(sourcefilefolder, log, 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) {
                                }
                                ;
                            }

                        }
                        return true;
                    }
                });

                if (fileObjects != null) {
                    for (int j = 0; j < fileObjects.length && !parentJob.isStopped(); j++) {
                        if (successConditionBroken) {
                            if (!successConditionBrokenExit) {
                                log.logError(toString(), Messages.getString(
                                        "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, log, result, parentJob);
                                }
                            }

                        } else {
                            // In the base folder
                            if (GetFileWildcard(CurrentFile.toString(), realWildcard)) {
                                checkOneFile(CurrentFile, log, result, parentJob);
                            }
                        }
                    }
                }
            } else {
                log.logError(toString(), Messages.getString("JobXMLWellFormed.Error.UnknowFileFormat",
                        sourcefilefolder.toString()));
                // Update Errors
                updateErrors();
            }
        } else {
            log.logError(toString(),
                    Messages.getString("JobXMLWellFormed.Error.SourceFileNotExists", realSourceFilefoldername));
            // Update Errors
            updateErrors();
        }
    } // end try

    catch (IOException e) {
        log.logError(toString(), Messages.getString("JobXMLWellFormed.Error.Exception.Processing",
                realSourceFilefoldername.toString(), e.getMessage()));
        // Update Errors
        updateErrors();
    } finally {
        if (sourcefilefolder != null) {
            try {
                sourcefilefolder.close();
            } catch (IOException ex) {
            }
            ;

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

From source file:com.panet.imeta.trans.steps.mail.Mail.java

private void setAttachedFilesList(Object[] r, LogWriter log) throws Exception {
    String realSourceFileFoldername = null;
    String realSourceWildcard = null;
    FileObject sourcefile = null;
    FileObject file = null;/* ww  w.  j  ava 2 s. c o  m*/

    ZipOutputStream zipOutputStream = null;
    File masterZipfile = null;

    if (meta.isZipFilenameDynamic())
        data.ZipFilename = data.previousRowMeta.getString(r, data.indexOfDynamicZipFilename);

    try {

        if (meta.isDynamicFilename()) {
            // dynamic attached filenames
            if (data.indexOfSourceFilename > -1)
                realSourceFileFoldername = data.previousRowMeta.getString(r, data.indexOfSourceFilename);

            if (data.indexOfSourceWildcard > -1)
                realSourceWildcard = data.previousRowMeta.getString(r, data.indexOfSourceWildcard);

        } else {
            // static attached filenames
            realSourceFileFoldername = data.realSourceFileFoldername;
            realSourceWildcard = data.realSourceWildcard;
        }

        if (!Const.isEmpty(realSourceFileFoldername)) {
            sourcefile = KettleVFS.getFileObject(realSourceFileFoldername);
            if (sourcefile.exists()) {
                long FileSize = 0;
                FileObject list[] = null;
                if (sourcefile.getType() == FileType.FILE) {
                    list = new FileObject[1];
                    list[0] = sourcefile;
                } else
                    list = sourcefile
                            .findFiles(new TextFileSelector(sourcefile.toString(), realSourceWildcard));
                if (list.length > 0) {

                    boolean zipFiles = meta.isZipFiles();
                    if (zipFiles && data.zipFileLimit == 0) {
                        masterZipfile = new File(
                                System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR + data.ZipFilename);

                        zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));
                    }

                    for (int i = 0; i < list.length; i++) {

                        file = KettleVFS.getFileObject(KettleVFS.getFilename(list[i]));

                        if (zipFiles) {

                            if (data.zipFileLimit == 0) {
                                ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName());
                                zipOutputStream.putNextEntry(zipEntry);

                                // Now put the content of this file into this archive...
                                BufferedInputStream inputStream = new BufferedInputStream(
                                        file.getContent().getInputStream());
                                int c;
                                while ((c = inputStream.read()) >= 0) {
                                    zipOutputStream.write(c);
                                }
                                inputStream.close();
                                zipOutputStream.closeEntry();
                            } else
                                FileSize += file.getContent().getSize();
                        } else {
                            addAttachedFilePart(file);
                        }
                    } // end for
                    if (zipFiles) {
                        if (log.isDebug())
                            log.logDebug(toString(), Messages.getString("Mail.Log.FileSize", "" + FileSize));
                        if (log.isDebug())
                            log.logDebug(toString(),
                                    Messages.getString("Mail.Log.LimitSize", "" + data.zipFileLimit));

                        if (data.zipFileLimit > 0 && FileSize > data.zipFileLimit) {

                            masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR
                                    + data.ZipFilename);

                            zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));

                            for (int i = 0; i < list.length; i++) {

                                file = KettleVFS.getFileObject(KettleVFS.getFilename(list[i]));

                                ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName());
                                zipOutputStream.putNextEntry(zipEntry);

                                // Now put the content of this file into this archive...
                                BufferedInputStream inputStream = new BufferedInputStream(
                                        file.getContent().getInputStream());
                                int c;
                                while ((c = inputStream.read()) >= 0) {
                                    zipOutputStream.write(c);
                                }
                                inputStream.close();
                                zipOutputStream.closeEntry();

                            }

                        }
                        if (data.zipFileLimit > 0 && FileSize > data.zipFileLimit || data.zipFileLimit == 0) {
                            file = KettleVFS.getFileObject(masterZipfile.getAbsolutePath());
                            addAttachedFilePart(file);
                        }
                    }
                }
            } else {
                log.logError(toString(),
                        Messages.getString("Mail.Error.SourceFileFolderNotExists", realSourceFileFoldername));
            }
        }
    } catch (Exception e) {
        log.logError(toString(), e.getMessage());
    } finally {
        if (sourcefile != null) {
            try {
                sourcefile.close();
            } catch (Exception e) {
            }
        }
        if (file != null) {
            try {
                file.close();
            } catch (Exception e) {
            }
        }

        if (zipOutputStream != null) {
            try {
                zipOutputStream.finish();
                zipOutputStream.close();
            } catch (IOException e) {
                log.logError(toString(), "Unable to close attachement zip file archive : " + e.toString());
            }
        }
    }

}