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

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

Introduction

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

Prototype

public boolean delete() throws FileSystemException;

Source Link

Document

Deletes this file.

Usage

From source file:org.pentaho.di.job.entries.shell.JobEntryShell.java

private void executeShell(Result result, List<RowMetaAndData> cmdRows, String[] args) {
    FileObject fileObject = null;
    String realScript = null;//from w w w .  jav  a2s  .co  m
    FileObject tempFile = null;

    try {
        // What's the exact command?
        String[] base = null;
        List<String> cmds = new ArrayList<String>();

        if (log.isBasic()) {
            logBasic(BaseMessages.getString(PKG, "JobShell.RunningOn", Const.getOS()));
        }

        if (insertScript) {
            realScript = environmentSubstitute(script);
        } else {
            String realFilename = environmentSubstitute(getFilename());
            fileObject = KettleVFS.getFileObject(realFilename, this);
        }

        if (Const.getOS().equals("Windows 95")) {
            base = new String[] { "command.com", "/C" };
            if (insertScript) {
                tempFile = KettleVFS.createTempFile("kettle", "shell.bat", environmentSubstitute(workDirectory),
                        this);
                fileObject = createTemporaryShellFile(tempFile, realScript);
            }
        } else if (Const.getOS().startsWith("Windows")) {
            base = new String[] { "cmd.exe", "/C" };
            if (insertScript) {
                tempFile = KettleVFS.createTempFile("kettle", "shell.bat", environmentSubstitute(workDirectory),
                        this);
                fileObject = createTemporaryShellFile(tempFile, realScript);
            }
        } else {
            if (insertScript) {
                tempFile = KettleVFS.createTempFile("kettle", "shell", environmentSubstitute(workDirectory),
                        this);
                fileObject = createTemporaryShellFile(tempFile, realScript);
            }
            base = new String[] { KettleVFS.getFilename(fileObject) };
        }

        // Construct the arguments...
        if (argFromPrevious && cmdRows != null) {
            // Add the base command...
            for (int i = 0; i < base.length; i++) {
                cmds.add(base[i]);
            }

            if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows")) {
                // for windows all arguments including the command itself
                // need to be
                // included in 1 argument to cmd/command.

                StringBuffer cmdline = new StringBuffer(300);

                cmdline.append('"');
                cmdline.append(Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject)));
                // Add the arguments from previous results...
                for (int i = 0; i < cmdRows.size(); i++) {
                    // Normally just one row, but once in a while to remain compatible we have multiple.

                    RowMetaAndData r = cmdRows.get(i);
                    for (int j = 0; j < r.size(); j++) {
                        cmdline.append(' ');
                        cmdline.append(Const.optionallyQuoteStringByOS(r.getString(j, null)));
                    }
                }
                cmdline.append('"');
                cmds.add(cmdline.toString());
            } else {
                // Add the arguments from previous results...
                for (int i = 0; i < cmdRows.size(); i++) {
                    // Normally just one row, but once in a while to remain compatible we have multiple.

                    RowMetaAndData r = cmdRows.get(i);
                    for (int j = 0; j < r.size(); j++) {
                        cmds.add(Const.optionallyQuoteStringByOS(r.getString(j, null)));
                    }
                }
            }
        } else if (args != null) {
            // Add the base command...
            for (int i = 0; i < base.length; i++) {
                cmds.add(base[i]);
            }

            if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows")) {
                // for windows all arguments including the command itself
                // need to be
                // included in 1 argument to cmd/command.

                StringBuffer cmdline = new StringBuffer(300);

                cmdline.append('"');
                cmdline.append(Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject)));

                for (int i = 0; i < args.length; i++) {
                    cmdline.append(' ');
                    cmdline.append(Const.optionallyQuoteStringByOS(args[i]));
                }
                cmdline.append('"');
                cmds.add(cmdline.toString());
            } else {
                for (int i = 0; i < args.length; i++) {
                    cmds.add(args[i]);
                }
            }
        }

        StringBuffer command = new StringBuffer();

        Iterator<String> it = cmds.iterator();
        boolean first = true;
        while (it.hasNext()) {
            if (!first) {
                command.append(' ');
            } else {
                first = false;
            }
            command.append(it.next());
        }
        if (log.isBasic()) {
            logBasic(BaseMessages.getString(PKG, "JobShell.ExecCommand", command.toString()));
        }

        // Build the environment variable list...
        ProcessBuilder procBuilder = new ProcessBuilder(cmds);
        Map<String, String> env = procBuilder.environment();
        String[] variables = listVariables();
        for (int i = 0; i < variables.length; i++) {
            env.put(variables[i], getVariable(variables[i]));
        }

        if (getWorkDirectory() != null && !Const.isEmpty(Const.rtrim(getWorkDirectory()))) {
            String vfsFilename = environmentSubstitute(getWorkDirectory());
            File file = new File(KettleVFS.getFilename(KettleVFS.getFileObject(vfsFilename, this)));
            procBuilder.directory(file);
        }
        Process proc = procBuilder.start();

        // any error message?
        StreamLogger errorLogger = new StreamLogger(log, proc.getErrorStream(), "(stderr)", true);

        // any output?
        StreamLogger outputLogger = new StreamLogger(log, proc.getInputStream(), "(stdout)");

        // kick them off
        Thread errorLoggerThread = new Thread(errorLogger);
        errorLoggerThread.start();
        Thread outputLoggerThread = new Thread(outputLogger);
        outputLoggerThread.start();

        proc.waitFor();
        if (log.isDetailed()) {
            logDetailed(BaseMessages.getString(PKG, "JobShell.CommandFinished", command.toString()));
        }

        // What's the exit status?
        result.setExitStatus(proc.exitValue());
        if (result.getExitStatus() != 0) {
            if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobShell.ExitStatus",
                        environmentSubstitute(getFilename()), "" + result.getExitStatus()));
            }

            result.setNrErrors(1);
        }

        // wait until loggers read all data from stdout and stderr
        errorLoggerThread.join();
        outputLoggerThread.join();

        // close the streams
        // otherwise you get "Too many open files, java.io.IOException" after a lot of iterations
        proc.getErrorStream().close();
        proc.getOutputStream().close();

    } catch (IOException ioe) {
        logError(BaseMessages.getString(PKG, "JobShell.ErrorRunningShell", environmentSubstitute(getFilename()),
                ioe.toString()), ioe);
        result.setNrErrors(1);
    } catch (InterruptedException ie) {
        logError(BaseMessages.getString(PKG, "JobShell.Shellinterupted", environmentSubstitute(getFilename()),
                ie.toString()), ie);
        result.setNrErrors(1);
    } catch (Exception e) {
        logError(BaseMessages.getString(PKG, "JobShell.UnexpectedError", environmentSubstitute(getFilename()),
                e.toString()), e);
        result.setNrErrors(1);
    } finally {
        // If we created a temporary file, remove it...
        //
        if (tempFile != null) {
            try {
                tempFile.delete();
            } catch (Exception e) {
                BaseMessages.getString(PKG, "JobShell.UnexpectedError", tempFile.toString(), e.toString());
            }
        }
    }

    if (result.getNrErrors() > 0) {
        result.setResult(false);
    } else {
        result.setResult(true);
    }
}

From source file:org.pentaho.di.job.entries.ssh2put.JobEntrySSH2PUT.java

private boolean deleteOrMoveFiles(FileObject file, String destinationFolder) throws KettleException {
    try {/*from  w w w . ja  v a2  s. co m*/
        boolean retval = false;

        // Delete the file if this is needed!
        //
        if (afterFtpPut.equals("delete_file")) {
            file.delete();
            retval = true;
            if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobSSH2PUT.Log.DeletedFile", file.toString()));
            }
        } else if (afterFtpPut.equals("move_file")) {
            // Move File
            FileObject destination = null;
            FileObject source = null;
            try {
                destination = KettleVFS.getFileObject(
                        destinationFolder + Const.FILE_SEPARATOR + file.getName().getBaseName(), this);
                file.moveTo(destination);
                retval = true;
            } catch (Exception e) {
                logError(BaseMessages.getString(PKG, "JobSSH2PUT.Cant_Move_File.Label", file.toString(),
                        destinationFolder, e.getMessage()));
            } finally {
                if (destination != null) {
                    try {
                        destination.close();
                    } catch (Exception ex) { /* Ignore */
                    }
                }
                if (source != null) {
                    try {
                        source.close();
                    } catch (Exception ex) { /* Ignore */
                    }
                }
            }
            if (log.isDetailed()) {
                logDetailed(
                        BaseMessages.getString(PKG, "JobSSH2PUT.Log.MovedFile", file.toString(), ftpDirectory));
            }
        }
        return retval;
    } catch (Exception e) {
        throw new KettleException(e);
    }
}

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  ww w  .  j  a  va2  s .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.zipfile.JobEntryZipFile.java

public boolean processRowFile(Job parentJob, Result result, String realZipfilename, String realWildcard,
        String realWildcardExclude, String realSourceDirectoryOrFile, String realMovetodirectory,
        boolean createparentfolder) {
    boolean Fileexists = false;
    File tempFile = null;//  w ww . j ava2 s  .c  o m
    File fileZip = null;
    boolean resultat = false;
    boolean renameOk = false;
    boolean orginExist = false;

    // Check if target file/folder exists!
    FileObject originFile = null;
    ZipInputStream zin = null;
    byte[] buffer = null;
    OutputStream dest = null;
    BufferedOutputStream buff = null;
    ZipOutputStream out = null;
    ZipEntry entry = null;
    String localSourceFilename = realSourceDirectoryOrFile;

    try {
        originFile = KettleVFS.getFileObject(realSourceDirectoryOrFile, this);
        localSourceFilename = KettleVFS.getFilename(originFile);
        orginExist = originFile.exists();
    } catch (Exception e) {
        // Ignore errors
    } finally {
        if (originFile != null) {
            try {
                originFile.close();
            } catch (IOException ex) {
                logError("Error closing file '" + originFile.toString() + "'", ex);
            }
        }
    }

    String localrealZipfilename = realZipfilename;
    if (realZipfilename != null && orginExist) {

        FileObject fileObject = null;
        try {
            fileObject = KettleVFS.getFileObject(localrealZipfilename, this);
            localrealZipfilename = KettleVFS.getFilename(fileObject);
            // Check if Zip File exists
            if (fileObject.exists()) {
                Fileexists = true;
                if (log.isDebug()) {
                    logDebug(BaseMessages.getString(PKG, "JobZipFiles.Zip_FileExists1.Label")
                            + localrealZipfilename
                            + BaseMessages.getString(PKG, "JobZipFiles.Zip_FileExists2.Label"));
                }
            }
            // Let's see if we need to create parent folder of destination zip filename
            if (createparentfolder) {
                createParentFolder(localrealZipfilename);
            }

            // Let's start the process now
            if (ifZipFileExists == 3 && Fileexists) {
                // the zip file exists and user want to Fail
                resultat = false;
            } else if (ifZipFileExists == 2 && Fileexists) {
                // the zip file exists and user want to do nothing
                if (addFileToResult) {
                    // Add file to result files name
                    ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, fileObject,
                            parentJob.getJobname(), toString());
                    result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
                }
                resultat = true;
            } else if (afterZip == 2 && realMovetodirectory == null) {
                // After Zip, Move files..User must give a destination Folder
                resultat = false;
                logError(
                        BaseMessages.getString(PKG, "JobZipFiles.AfterZip_No_DestinationFolder_Defined.Label"));
            } else {
                // After Zip, Move files..User must give a destination Folder

                // Let's see if we deal with file or folder
                FileObject[] fileList = null;

                FileObject sourceFileOrFolder = KettleVFS.getFileObject(localSourceFilename);
                boolean isSourceDirectory = sourceFileOrFolder.getType().equals(FileType.FOLDER);
                final Pattern pattern;
                final Pattern patternexclude;

                if (isSourceDirectory) {
                    // Let's prepare the pattern matcher for performance reasons.
                    // We only do this if the target is a folder !
                    //
                    if (!Const.isEmpty(realWildcard)) {
                        pattern = Pattern.compile(realWildcard);
                    } else {
                        pattern = null;
                    }
                    if (!Const.isEmpty(realWildcardExclude)) {
                        patternexclude = Pattern.compile(realWildcardExclude);
                    } else {
                        patternexclude = null;
                    }

                    // Target is a directory
                    // Get all the files in the directory...
                    //
                    if (includingSubFolders) {
                        fileList = sourceFileOrFolder.findFiles(new FileSelector() {

                            public boolean traverseDescendents(FileSelectInfo fileInfo) throws Exception {
                                return true;
                            }

                            public boolean includeFile(FileSelectInfo fileInfo) throws Exception {
                                boolean include;

                                // Only include files in the sub-folders...
                                // When we include sub-folders we match the whole filename, not just the base-name
                                //
                                if (fileInfo.getFile().getType().equals(FileType.FILE)) {
                                    include = true;
                                    if (pattern != null) {
                                        String name = fileInfo.getFile().getName().getPath();
                                        include = pattern.matcher(name).matches();
                                    }
                                    if (include && patternexclude != null) {
                                        String name = fileInfo.getFile().getName().getPath();
                                        include = !pattern.matcher(name).matches();
                                    }
                                } else {
                                    include = false;
                                }
                                return include;
                            }
                        });
                    } else {
                        fileList = sourceFileOrFolder.getChildren();
                    }
                } else {
                    pattern = null;
                    patternexclude = null;

                    // Target is a file
                    fileList = new FileObject[] { sourceFileOrFolder };
                }

                if (fileList.length == 0) {
                    resultat = false;
                    logError(BaseMessages.getString(PKG, "JobZipFiles.Log.FolderIsEmpty", localSourceFilename));
                } else if (!checkContainsFile(localSourceFilename, fileList, isSourceDirectory)) {
                    resultat = false;
                    logError(BaseMessages.getString(PKG, "JobZipFiles.Log.NoFilesInFolder",
                            localSourceFilename));
                } else {
                    if (ifZipFileExists == 0 && Fileexists) {
                        // the zip file exists and user want to create new one with unique name
                        // Format Date

                        // do we have already a .zip at the end?
                        if (localrealZipfilename.toLowerCase().endsWith(".zip")) {
                            // strip this off
                            localrealZipfilename = localrealZipfilename.substring(0,
                                    localrealZipfilename.length() - 4);
                        }

                        localrealZipfilename += "_" + StringUtil.getFormattedDateTimeNow(true) + ".zip";
                        if (log.isDebug()) {
                            logDebug(BaseMessages.getString(PKG, "JobZipFiles.Zip_FileNameChange1.Label")
                                    + localrealZipfilename
                                    + BaseMessages.getString(PKG, "JobZipFiles.Zip_FileNameChange1.Label"));
                        }
                    } else if (ifZipFileExists == 1 && Fileexists) {
                        // the zip file exists and user want to append
                        // get a temp file
                        fileZip = getFile(localrealZipfilename);
                        tempFile = File.createTempFile(fileZip.getName(), null);

                        // delete it, otherwise we cannot rename existing zip to it.
                        tempFile.delete();

                        renameOk = fileZip.renameTo(tempFile);

                        if (!renameOk) {
                            logError(BaseMessages.getString(PKG, "JobZipFiles.Cant_Rename_Temp1.Label")
                                    + fileZip.getAbsolutePath()
                                    + BaseMessages.getString(PKG, "JobZipFiles.Cant_Rename_Temp2.Label")
                                    + tempFile.getAbsolutePath()
                                    + BaseMessages.getString(PKG, "JobZipFiles.Cant_Rename_Temp3.Label"));
                        }
                        if (log.isDebug()) {
                            logDebug(BaseMessages.getString(PKG, "JobZipFiles.Zip_FileAppend1.Label")
                                    + localrealZipfilename
                                    + BaseMessages.getString(PKG, "JobZipFiles.Zip_FileAppend2.Label"));
                        }
                    }

                    if (log.isDetailed()) {
                        logDetailed(
                                BaseMessages.getString(PKG, "JobZipFiles.Files_Found1.Label") + fileList.length
                                        + BaseMessages.getString(PKG, "JobZipFiles.Files_Found2.Label")
                                        + localSourceFilename
                                        + BaseMessages.getString(PKG, "JobZipFiles.Files_Found3.Label"));
                    }

                    // Prepare Zip File
                    buffer = new byte[18024];
                    dest = KettleVFS.getOutputStream(localrealZipfilename, false);
                    buff = new BufferedOutputStream(dest);
                    out = new ZipOutputStream(buff);

                    HashSet<String> fileSet = new HashSet<String>();

                    if (renameOk) {
                        // User want to append files to existing Zip file
                        // The idea is to rename the existing zip file to a temporary file
                        // and then adds all entries in the existing zip along with the new files,
                        // excluding the zip entries that have the same name as one of the new files.

                        zin = new ZipInputStream(new FileInputStream(tempFile));
                        entry = zin.getNextEntry();

                        while (entry != null) {
                            String name = entry.getName();

                            if (!fileSet.contains(name)) {

                                // Add ZIP entry to output stream.
                                out.putNextEntry(new ZipEntry(name));
                                // Transfer bytes from the ZIP file to the output file
                                int len;
                                while ((len = zin.read(buffer)) > 0) {
                                    out.write(buffer, 0, len);
                                }

                                fileSet.add(name);
                            }
                            entry = zin.getNextEntry();
                        }
                        // Close the streams
                        zin.close();
                    }

                    // Set the method
                    out.setMethod(ZipOutputStream.DEFLATED);
                    // Set the compression level
                    if (compressionRate == 0) {
                        out.setLevel(Deflater.NO_COMPRESSION);
                    } else if (compressionRate == 1) {
                        out.setLevel(Deflater.DEFAULT_COMPRESSION);
                    }
                    if (compressionRate == 2) {
                        out.setLevel(Deflater.BEST_COMPRESSION);
                    }
                    if (compressionRate == 3) {
                        out.setLevel(Deflater.BEST_SPEED);
                    }
                    // Specify Zipped files (After that we will move,delete them...)
                    FileObject[] zippedFiles = new FileObject[fileList.length];
                    int fileNum = 0;

                    // Get the files in the list...
                    for (int i = 0; i < fileList.length && !parentJob.isStopped(); i++) {
                        boolean getIt = true;
                        boolean getItexclude = false;

                        // First see if the file matches the regular expression!
                        // ..only if target is a folder !
                        if (isSourceDirectory) {
                            // If we include sub-folders, we match on the whole name, not just the basename
                            //
                            String filename;
                            if (includingSubFolders) {
                                filename = fileList[i].getName().getPath();
                            } else {
                                filename = fileList[i].getName().getBaseName();
                            }
                            if (pattern != null) {
                                // Matches the base name of the file (backward compatible!)
                                //
                                Matcher matcher = pattern.matcher(filename);
                                getIt = matcher.matches();
                            }

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

                        // Get processing File
                        String targetFilename = KettleVFS.getFilename(fileList[i]);
                        if (sourceFileOrFolder.getType().equals(FileType.FILE)) {
                            targetFilename = localSourceFilename;
                        }

                        FileObject file = KettleVFS.getFileObject(targetFilename);
                        boolean isTargetDirectory = file.exists() && file.getType().equals(FileType.FOLDER);

                        if (getIt && !getItexclude && !isTargetDirectory && !fileSet.contains(targetFilename)) {
                            // We can add the file to the Zip Archive
                            if (log.isDebug()) {
                                logDebug(BaseMessages.getString(PKG, "JobZipFiles.Add_FilesToZip1.Label")
                                        + fileList[i]
                                        + BaseMessages.getString(PKG, "JobZipFiles.Add_FilesToZip2.Label")
                                        + localSourceFilename
                                        + BaseMessages.getString(PKG, "JobZipFiles.Add_FilesToZip3.Label"));
                            }

                            // Associate a file input stream for the current file
                            InputStream in = KettleVFS.getInputStream(file);

                            // Add ZIP entry to output stream.
                            //
                            String relativeName;
                            String fullName = fileList[i].getName().getPath();
                            String basePath = sourceFileOrFolder.getName().getPath();
                            if (isSourceDirectory) {
                                if (fullName.startsWith(basePath)) {
                                    relativeName = fullName.substring(basePath.length() + 1);
                                } else {
                                    relativeName = fullName;
                                }
                            } else if (isFromPrevious) {
                                int depth = determineDepth(environmentSubstitute(storedSourcePathDepth));
                                relativeName = determineZipfilenameForDepth(fullName, depth);
                            } else {
                                relativeName = fileList[i].getName().getBaseName();
                            }
                            out.putNextEntry(new ZipEntry(relativeName));

                            int len;
                            while ((len = in.read(buffer)) > 0) {
                                out.write(buffer, 0, len);
                            }
                            out.flush();
                            out.closeEntry();

                            // Close the current file input stream
                            in.close();

                            // Get Zipped File
                            zippedFiles[fileNum] = fileList[i];
                            fileNum = fileNum + 1;
                        }
                    }
                    // Close the ZipOutPutStream
                    out.close();
                    buff.close();
                    dest.close();

                    if (log.isBasic()) {
                        logBasic(BaseMessages.getString(PKG, "JobZipFiles.Log.TotalZippedFiles",
                                "" + zippedFiles.length));
                    }
                    // Delete Temp File
                    if (tempFile != null) {
                        tempFile.delete();
                    }

                    // -----Get the list of Zipped Files and Move or Delete Them
                    if (afterZip == 1 || afterZip == 2) {
                        // iterate through the array of Zipped files
                        for (int i = 0; i < zippedFiles.length; i++) {
                            if (zippedFiles[i] != null) {
                                // Delete, Move File
                                FileObject fileObjectd = zippedFiles[i];
                                if (!isSourceDirectory) {
                                    fileObjectd = KettleVFS.getFileObject(localSourceFilename);
                                }

                                // Here we can move, delete files
                                if (afterZip == 1) {
                                    // Delete File
                                    boolean deleted = fileObjectd.delete();
                                    if (!deleted) {
                                        resultat = false;
                                        logError(BaseMessages.getString(PKG,
                                                "JobZipFiles.Cant_Delete_File1.Label") + localSourceFilename
                                                + Const.FILE_SEPARATOR + zippedFiles[i] + BaseMessages
                                                        .getString(PKG, "JobZipFiles.Cant_Delete_File2.Label"));

                                    }
                                    // File deleted
                                    if (log.isDebug()) {
                                        logDebug(BaseMessages.getString(PKG, "JobZipFiles.File_Deleted1.Label")
                                                + localSourceFilename + Const.FILE_SEPARATOR + zippedFiles[i]
                                                + BaseMessages.getString(PKG,
                                                        "JobZipFiles.File_Deleted2.Label"));
                                    }
                                } else if (afterZip == 2) {
                                    // Move File
                                    FileObject fileObjectm = null;
                                    try {
                                        fileObjectm = KettleVFS.getFileObject(realMovetodirectory
                                                + Const.FILE_SEPARATOR + fileObjectd.getName().getBaseName());
                                        fileObjectd.moveTo(fileObjectm);
                                    } catch (IOException e) {
                                        logError(
                                                BaseMessages.getString(PKG, "JobZipFiles.Cant_Move_File1.Label")
                                                        + zippedFiles[i]
                                                        + BaseMessages.getString(PKG,
                                                                "JobZipFiles.Cant_Move_File2.Label")
                                                        + e.getMessage());
                                        resultat = false;
                                    } finally {
                                        try {
                                            if (fileObjectm != null) {
                                                fileObjectm.close();
                                            }
                                        } catch (Exception e) {
                                            if (fileObjectm != null) {
                                                logError("Error closing file '" + fileObjectm.toString() + "'",
                                                        e);
                                            }
                                        }
                                    }
                                    // File moved
                                    if (log.isDebug()) {
                                        logDebug(BaseMessages.getString(PKG, "JobZipFiles.File_Moved1.Label")
                                                + zippedFiles[i]
                                                + BaseMessages.getString(PKG, "JobZipFiles.File_Moved2.Label"));
                                    }
                                }
                            }
                        }
                    }

                    if (addFileToResult) {
                        // Add file to result files name
                        ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, fileObject,
                                parentJob.getJobname(), toString());
                        result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
                    }

                    resultat = true;
                }
            }
        } catch (Exception e) {
            logError(BaseMessages.getString(PKG, "JobZipFiles.Cant_CreateZipFile1.Label") + localrealZipfilename
                    + BaseMessages.getString(PKG, "JobZipFiles.Cant_CreateZipFile2.Label"), e);
            resultat = false;
        } finally {
            if (fileObject != null) {
                try {
                    fileObject.close();
                    fileObject = null;
                } catch (IOException ex) {
                    logError("Error closing file '" + fileObject.toString() + "'", ex);
                }
            }

            try {
                if (out != null) {
                    out.close();
                }
                if (buff != null) {
                    buff.close();
                }
                if (dest != null) {
                    dest.close();
                }
                if (zin != null) {
                    zin.close();
                }
                if (entry != null) {
                    entry = null;
                }

            } catch (IOException ex) {
                logError("Error closing zip file entry for file '" + originFile.toString() + "'", ex);
            }
        }
    } else {
        resultat = true;
        if (localrealZipfilename == null) {
            logError(BaseMessages.getString(PKG, "JobZipFiles.No_ZipFile_Defined.Label"));
        }
        if (!orginExist) {
            logError(BaseMessages.getString(PKG, "JobZipFiles.No_FolderCible_Defined.Label",
                    localSourceFilename));
        }
    }
    // return a verifier
    return resultat;
}

From source file:org.pentaho.di.repository.filerep.KettleFileRepository.java

public void deleteRootObject(String name, String extension) throws KettleException {
    try {// ww  w .  j  a v  a2s . c o  m
        String filename = calcDirectoryName(null) + name + extension;
        FileObject fileObject = KettleVFS.getFileObject(filename);
        fileObject.delete();
    } catch (Exception e) {
        throw new KettleException(
                "Unable to delete database with name [" + name + "] and extension [" + extension + "]", e);
    }
}

From source file:org.pentaho.di.repository.filerep.KettleFileRepository.java

public void deleteFile(String filename) throws KettleException {
    try {//from   ww w. jav a2 s . c om
        FileObject fileObject = KettleVFS.getFileObject(filename);
        fileObject.delete();
    } catch (Exception e) {
        throw new KettleException("Unable to delete file with name [" + filename + "]", e);
    }
}

From source file:org.pentaho.di.trans.steps.blockingstep.BlockingStep.java

private Object[] getBuffer() {
    Object[] retval;/*from   w  ww. jav a  2  s . c om*/

    // Open all files at once and read one row from each file...
    if (data.files.size() > 0 && (data.dis.size() == 0 || data.fis.size() == 0)) {
        if (log.isBasic()) {
            logBasic(BaseMessages.getString(PKG, "BlockingStep.Log.Openfiles"));
        }

        try {
            FileObject fileObject = data.files.get(0);
            String filename = KettleVFS.getFilename(fileObject);
            if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "BlockingStep.Log.Openfilename1") + filename
                        + BaseMessages.getString(PKG, "BlockingStep.Log.Openfilename2"));
            }
            InputStream fi = KettleVFS.getInputStream(fileObject);
            DataInputStream di;
            data.fis.add(fi);
            if (meta.getCompress()) {
                GZIPInputStream gzfi = new GZIPInputStream(new BufferedInputStream(fi));
                di = new DataInputStream(gzfi);
                data.gzis.add(gzfi);
            } else {
                di = new DataInputStream(fi);
            }
            data.dis.add(di);

            // How long is the buffer?
            int buffersize = di.readInt();

            if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "BlockingStep.Log.BufferSize1") + filename
                        + BaseMessages.getString(PKG, "BlockingStep.Log.BufferSize2") + buffersize + " "
                        + BaseMessages.getString(PKG, "BlockingStep.Log.BufferSize3"));
            }

            if (buffersize > 0) {
                // Read a row from temp-file
                data.rowbuffer.add(data.outputRowMeta.readData(di));
            }
        } catch (Exception e) {
            logError(BaseMessages.getString(PKG, "BlockingStepMeta.ErrorReadingFile") + e.toString());
            logError(Const.getStackTracker(e));
        }
    }

    if (data.files.size() == 0) {
        if (data.buffer.size() > 0) {
            retval = data.buffer.get(0);
            data.buffer.remove(0);
        } else {
            retval = null;
        }
    } else {
        if (data.rowbuffer.size() == 0) {
            retval = null;
        } else {
            retval = data.rowbuffer.get(0);

            data.rowbuffer.remove(0);

            // now get another
            FileObject file = data.files.get(0);
            DataInputStream di = data.dis.get(0);
            InputStream fi = data.fis.get(0);
            GZIPInputStream gzfi = (meta.getCompress()) ? data.gzis.get(0) : null;

            try {
                data.rowbuffer.add(0, data.outputRowMeta.readData(di));
            } catch (SocketTimeoutException e) {
                logError(BaseMessages.getString(PKG, "System.Log.UnexpectedError") + " : " + e.toString());
                logError(Const.getStackTracker(e));
                setErrors(1);
                stopAll();
            } catch (KettleFileException fe) {
                // empty file or EOF mostly
                try {
                    di.close();
                    fi.close();
                    if (gzfi != null) {
                        gzfi.close();
                    }
                    file.delete();
                } catch (IOException e) {
                    logError(
                            BaseMessages.getString(PKG, "BlockingStepMeta.UnableDeleteFile") + file.toString());
                    setErrors(1);
                    stopAll();
                    return null;
                }

                data.files.remove(0);
                data.dis.remove(0);
                data.fis.remove(0);
                if (gzfi != null) {
                    data.gzis.remove(0);
                }
            }
        }
    }
    return retval;
}

From source file:org.pentaho.di.trans.steps.blockingstep.BlockingStep.java

public void dispose(StepMetaInterface smi, StepDataInterface sdi) {
    if ((data.dis != null) && (data.dis.size() > 0)) {
        for (DataInputStream is : data.dis) {
            BaseStep.closeQuietly(is);/*from w  w w  . j  a  v  a 2 s. c om*/
        }
    }
    // remove temp files
    for (int f = 0; f < data.files.size(); f++) {
        FileObject fileToDelete = data.files.get(f);
        try {
            if (fileToDelete != null && fileToDelete.exists()) {
                fileToDelete.delete();
            }
        } catch (FileSystemException e) {
            logError(e.getLocalizedMessage(), e);
        }
    }
    super.dispose(smi, sdi);
}

From source file:org.pentaho.di.trans.steps.gpbulkloader.GPBulkLoader.java

public void dispose(StepMetaInterface smi, StepDataInterface sdi) {
    meta = (GPBulkLoaderMeta) smi;//  w  w w  . ja v  a  2  s . co m
    data = (GPBulkLoaderData) sdi;

    super.dispose(smi, sdi);

    if (!preview && meta.isEraseFiles()) {
        // Erase the created cfg/dat files if requested. We don't erase
        // the rest of the files because it would be "stupid" to erase them
        // right after creation. If you don't want them, don't fill them in.
        FileObject fileObject = null;

        String method = meta.getLoadMethod();

        // GPBulkLoaderMeta.METHOD_AUTO_CONCURRENT.equals(method) ||
        if (GPBulkLoaderMeta.METHOD_AUTO_END.equals(method)) {

            if (meta.getControlFile() != null) {
                try {
                    fileObject = KettleVFS.getFileObject(environmentSubstitute(meta.getControlFile()),
                            getTransMeta());
                    fileObject.delete();
                    fileObject.close();
                } catch (Exception ex) {
                    logError("Error deleting control file \'" + KettleVFS.getFilename(fileObject) + "\': "
                            + ex.getMessage());
                }
            }
        }

        if (GPBulkLoaderMeta.METHOD_AUTO_END.equals(method)) {
            // In concurrent mode the data is written to the control file.
            if (meta.getDataFile() != null) {
                try {
                    fileObject = KettleVFS.getFileObject(environmentSubstitute(meta.getDataFile()),
                            getTransMeta());
                    fileObject.delete();
                    fileObject.close();
                } catch (Exception ex) {
                    logError("Error deleting data file \'" + KettleVFS.getFilename(fileObject) + "\': "
                            + ex.getMessage(), ex);
                }
            }
        }

        if (GPBulkLoaderMeta.METHOD_MANUAL.equals(method)) {
            logBasic("Deletion of files is not compatible with \'manual load method\'");
        }
    }
}

From source file:org.pentaho.di.trans.steps.gpload.GPLoad.java

public void dispose(StepMetaInterface smi, StepDataInterface sdi) {
    meta = (GPLoadMeta) smi;/*from w  ww.  j  av a  2  s.  c  o m*/
    data = (GPLoadData) sdi;

    super.dispose(smi, sdi);

    if (!preview && meta.isEraseFiles()) {
        // Erase the created cfg/dat files if requested. We don't erase
        // the rest of the files because it would be "stupid" to erase them
        // right after creation. If you don't want them, don't fill them in.
        FileObject fileObject = null;

        String method = meta.getLoadMethod();
        if (GPLoadMeta.METHOD_AUTO_END.equals(method)) {
            if (meta.getControlFile() != null) {
                try {
                    fileObject = KettleVFS.getFileObject(environmentSubstitute(meta.getControlFile()),
                            getTransMeta());
                    fileObject.delete();
                    fileObject.close();
                } catch (Exception ex) {
                    logError("Error deleting control file \'" + KettleVFS.getFilename(fileObject) + "\': "
                            + ex.getMessage());
                }
            }
        }

        if (GPLoadMeta.METHOD_AUTO_END.equals(method)) {
            // In concurrent mode the data is written to the control file.
            if (meta.getDataFile() != null) {
                try {
                    fileObject = KettleVFS.getFileObject(environmentSubstitute(meta.getDataFile()),
                            getTransMeta());
                    fileObject.delete();
                    fileObject.close();
                } catch (Exception ex) {
                    logError("Error deleting data file \'" + KettleVFS.getFilename(fileObject) + "\': "
                            + ex.getMessage(), ex);
                }
            }
        }

        if (GPLoadMeta.METHOD_MANUAL.equals(method)) {
            logBasic("Deletion of files is not compatible with \'manual load method\'");
        }
    }
}