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

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

Introduction

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

Prototype

public void moveTo(FileObject destFile) throws FileSystemException;

Source Link

Document

Move this file.

Usage

From source file:org.pentaho.di.job.entries.copymoveresultfilenames.JobEntryCopyMoveResultFilenames.java

private boolean processFile(FileObject sourcefile, String destinationFolder, Result result, Job parentJob,
        boolean deleteFile) {
    boolean retval = false;

    try {/*from  w w  w.  j  a v  a 2  s. co  m*/
        if (deleteFile) {
            // delete file
            if (sourcefile.delete()) {
                if (log.isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "JobEntryCopyMoveResultFilenames.log.DeletedFile",
                            sourcefile.toString()));
                }

                // Remove source file from result files list
                result.getResultFiles().remove(sourcefile.toString());
                if (log.isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG,
                            "JobEntryCopyMoveResultFilenames.RemovedFileFromResult", sourcefile.toString()));
                }

            } else {
                logError(BaseMessages.getString(PKG, "JobEntryCopyMoveResultFilenames.CanNotDeletedFile",
                        sourcefile.toString()));
            }
        } else {
            // return destination short filename
            String shortfilename = getDestinationFilename(sourcefile.getName().getBaseName());
            // build full destination filename
            String destinationFilename = destinationFolder + Const.FILE_SEPARATOR + shortfilename;
            FileObject destinationfile = KettleVFS.getFileObject(destinationFilename, this);
            boolean filexists = destinationfile.exists();
            if (filexists) {
                if (log.isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "JobEntryCopyMoveResultFilenames.Log.FileExists",
                            destinationFilename));
                }
            }
            if ((!filexists) || (filexists && isOverwriteFile())) {
                if (getAction().equals("copy")) {
                    // Copy file
                    FileUtil.copyContent(sourcefile, destinationfile);
                    if (log.isDetailed()) {
                        logDetailed(
                                BaseMessages.getString(PKG, "JobEntryCopyMoveResultFilenames.log.CopiedFile",
                                        sourcefile.toString(), destinationFolder));
                    }
                } else {
                    // Move file
                    sourcefile.moveTo(destinationfile);
                    if (log.isDetailed()) {
                        logDetailed(BaseMessages.getString(PKG, "JobEntryCopyMoveResultFilenames.log.MovedFile",
                                sourcefile.toString(), destinationFolder));
                    }
                }
                if (isRemovedSourceFilename()) {
                    // Remove source file from result files list
                    result.getResultFiles().remove(sourcefile.toString());
                    if (log.isDetailed()) {
                        logDetailed(BaseMessages.getString(PKG,
                                "JobEntryCopyMoveResultFilenames.RemovedFileFromResult",
                                sourcefile.toString()));
                    }
                }
                if (isAddDestinationFilename()) {
                    // Add destination filename to Resultfilenames ...
                    ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL,
                            KettleVFS.getFileObject(destinationfile.toString(), this), parentJob.getJobname(),
                            toString());
                    result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
                    if (log.isDetailed()) {
                        logDetailed(
                                BaseMessages.getString(PKG, "JobEntryCopyMoveResultFilenames.AddedFileToResult",
                                        destinationfile.toString()));
                    }
                }
            }
        }
        retval = true;
    } catch (Exception e) {
        logError(BaseMessages.getString(PKG, "JobEntryCopyMoveResultFilenames.Log.ErrorProcessing",
                e.toString()));
    }

    return retval;
}

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

private boolean MoveFile(String shortfilename, FileObject sourcefilename, FileObject destinationfilename,
        FileObject movetofolderfolder, Job parentJob, Result result) {

    FileObject destinationfile = null;
    boolean retval = false;
    try {/*from  w  w  w.j a  v  a2s .c o  m*/
        if (!destinationfilename.exists()) {
            if (!simulate) {
                sourcefilename.moveTo(destinationfilename);
            }
            if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobMoveFiles.Log.FileMoved",
                        sourcefilename.getName().toString(), destinationfilename.getName().toString()));
            }

            // add filename to result filename
            if (add_result_filesname && !iffileexists.equals("fail") && !iffileexists.equals("do_nothing")) {
                addFileToResultFilenames(destinationfilename.toString(), result, parentJob);
            }

            updateSuccess();
            retval = true;

        } else {
            if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobMoveFiles.Log.FileExists",
                        destinationfilename.toString()));
            }
            if (iffileexists.equals("overwrite_file")) {
                if (!simulate) {
                    sourcefilename.moveTo(destinationfilename);
                }
                if (log.isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "JobMoveFiles.Log.FileOverwrite",
                            destinationfilename.getName().toString()));
                }

                // add filename to result filename
                if (add_result_filesname && !iffileexists.equals("fail")
                        && !iffileexists.equals("do_nothing")) {
                    addFileToResultFilenames(destinationfilename.toString(), result, parentJob);
                }

                updateSuccess();
                retval = true;

            } else if (iffileexists.equals("unique_name")) {
                String short_filename = shortfilename;

                // return destination short filename
                try {
                    short_filename = getMoveDestinationFilename(short_filename, "ddMMyyyy_HHmmssSSS");
                } catch (Exception e) {
                    logError(BaseMessages.getString(PKG,
                            BaseMessages.getString(PKG, "JobMoveFiles.Error.GettingFilename", short_filename)),
                            e);
                    return retval;
                }

                String movetofilenamefull = destinationfilename.getParent().toString() + Const.FILE_SEPARATOR
                        + short_filename;
                destinationfile = KettleVFS.getFileObject(movetofilenamefull, this);

                if (!simulate) {
                    sourcefilename.moveTo(destinationfile);
                }
                if (log.isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "JobMoveFiles.Log.FileMoved",
                            sourcefilename.getName().toString(), destinationfile.getName().toString()));
                }

                // add filename to result filename
                if (add_result_filesname && !iffileexists.equals("fail")
                        && !iffileexists.equals("do_nothing")) {
                    addFileToResultFilenames(destinationfile.toString(), result, parentJob);
                }

                updateSuccess();
                retval = true;
            } else if (iffileexists.equals("delete_file")) {
                if (!simulate) {
                    destinationfilename.delete();
                }
                if (log.isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "JobMoveFiles.Log.FileDeleted",
                            destinationfilename.getName().toString()));
                }
            } else if (iffileexists.equals("move_file")) {
                String short_filename = shortfilename;
                // return destination short filename
                try {
                    short_filename = getMoveDestinationFilename(short_filename, null);
                } catch (Exception e) {
                    logError(BaseMessages.getString(PKG,
                            BaseMessages.getString(PKG, "JobMoveFiles.Error.GettingFilename", short_filename)),
                            e);
                    return retval;
                }

                String movetofilenamefull = movetofolderfolder.toString() + Const.FILE_SEPARATOR
                        + short_filename;
                destinationfile = KettleVFS.getFileObject(movetofilenamefull, this);
                if (!destinationfile.exists()) {
                    if (!simulate) {
                        sourcefilename.moveTo(destinationfile);
                    }
                    if (log.isDetailed()) {
                        logDetailed(BaseMessages.getString(PKG, "JobMoveFiles.Log.FileMoved",
                                sourcefilename.getName().toString(), destinationfile.getName().toString()));
                    }

                    // add filename to result filename
                    if (add_result_filesname && !iffileexists.equals("fail")
                            && !iffileexists.equals("do_nothing")) {
                        addFileToResultFilenames(destinationfile.toString(), result, parentJob);
                    }

                } else {
                    if (ifmovedfileexists.equals("overwrite_file")) {
                        if (!simulate) {
                            sourcefilename.moveTo(destinationfile);
                        }
                        if (log.isDetailed()) {
                            logDetailed(BaseMessages.getString(PKG, "JobMoveFiles.Log.FileOverwrite",
                                    destinationfile.getName().toString()));
                        }

                        // add filename to result filename
                        if (add_result_filesname && !iffileexists.equals("fail")
                                && !iffileexists.equals("do_nothing")) {
                            addFileToResultFilenames(destinationfile.toString(), result, parentJob);
                        }

                        updateSuccess();
                        retval = true;
                    } else if (ifmovedfileexists.equals("unique_name")) {
                        SimpleDateFormat daf = new SimpleDateFormat();
                        Date now = new Date();
                        daf.applyPattern("ddMMyyyy_HHmmssSSS");
                        String dt = daf.format(now);
                        short_filename += "_" + dt;

                        String destinationfilenamefull = movetofolderfolder.toString() + Const.FILE_SEPARATOR
                                + short_filename;
                        destinationfile = KettleVFS.getFileObject(destinationfilenamefull, this);

                        if (!simulate) {
                            sourcefilename.moveTo(destinationfile);
                        }
                        if (log.isDetailed()) {
                            logDetailed(BaseMessages.getString(PKG, "JobMoveFiles.Log.FileMoved",
                                    destinationfile.getName().toString()));
                        }

                        // add filename to result filename
                        if (add_result_filesname && !iffileexists.equals("fail")
                                && !iffileexists.equals("do_nothing")) {
                            addFileToResultFilenames(destinationfile.toString(), result, parentJob);
                        }

                        updateSuccess();
                        retval = true;
                    } else if (ifmovedfileexists.equals("fail")) {
                        // Update Errors
                        updateErrors();
                    }
                }

            } else if (iffileexists.equals("fail")) {
                // Update Errors
                updateErrors();
            }
        }
    } catch (Exception e) {
        logError(BaseMessages.getString(PKG, "JobMoveFiles.Error.Exception.MoveProcessError",
                sourcefilename.toString(), destinationfilename.toString(), e.getMessage()));
        updateErrors();
    } finally {
        if (destinationfile != null) {
            try {
                destinationfile.close();
            } catch (IOException ex) { /* Ignore */
            }
        }
    }
    return retval;
}

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

private boolean DecryptFile(String shortfilename, FileObject sourcefilename, String passPharse,
        FileObject destinationfilename, FileObject movetofolderfolder, Job parentJob, Result result) {

    FileObject destinationfile = null;
    boolean retval = false;
    try {//from w  w  w  . jav a2s .  com
        if (!destinationfilename.exists()) {
            gpg.decryptFile(sourcefilename, passPharse, destinationfilename);

            if (isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Log.FileDecrypted",
                        sourcefilename.getName().toString(), destinationfilename.getName().toString()));
            }

            // add filename to result filename
            if (add_result_filesname && !iffileexists.equals("fail") && !iffileexists.equals("do_nothing")) {
                addFileToResultFilenames(destinationfilename.toString(), result, parentJob);
            }

            updateSuccess();

        } else {
            if (isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Log.FileExists",
                        destinationfilename.toString()));
            }
            if (iffileexists.equals("overwrite_file")) {
                gpg.decryptFile(sourcefilename, passPharse, destinationfilename);

                if (isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Log.FileOverwrite",
                            destinationfilename.getName().toString()));
                }

                // add filename to result filename
                if (add_result_filesname && !iffileexists.equals("fail")
                        && !iffileexists.equals("do_nothing")) {
                    addFileToResultFilenames(destinationfilename.toString(), result, parentJob);
                }

                updateSuccess();

            } else if (iffileexists.equals("unique_name")) {
                String short_filename = shortfilename;

                // return destination short filename
                try {
                    short_filename = getMoveDestinationFilename(short_filename, "ddMMyyyy_HHmmssSSS");
                } catch (Exception e) {
                    logError(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Error.GettingFilename",
                            short_filename), e);
                    return retval;
                }

                String movetofilenamefull = destinationfilename.getParent().toString() + Const.FILE_SEPARATOR
                        + short_filename;
                destinationfile = KettleVFS.getFileObject(movetofilenamefull);

                gpg.decryptFile(sourcefilename, passPharse, destinationfile);

                if (isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Log.FileDecrypted",
                            sourcefilename.getName().toString(), destinationfile.getName().toString()));
                }

                // add filename to result filename
                if (add_result_filesname && !iffileexists.equals("fail")
                        && !iffileexists.equals("do_nothing")) {
                    addFileToResultFilenames(destinationfile.toString(), result, parentJob);
                }

                updateSuccess();
            } else if (iffileexists.equals("delete_file")) {
                destinationfilename.delete();
                if (isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Log.FileDeleted",
                            destinationfilename.getName().toString()));
                }
            } else if (iffileexists.equals("move_file")) {
                String short_filename = shortfilename;
                // return destination short filename
                try {
                    short_filename = getMoveDestinationFilename(short_filename, null);
                } catch (Exception e) {
                    logError(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Error.GettingFilename",
                            short_filename), e);
                    return retval;
                }

                String movetofilenamefull = movetofolderfolder.toString() + Const.FILE_SEPARATOR
                        + short_filename;
                destinationfile = KettleVFS.getFileObject(movetofilenamefull);
                if (!destinationfile.exists()) {
                    sourcefilename.moveTo(destinationfile);
                    if (isDetailed()) {
                        logDetailed(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Log.FileDecrypted",
                                sourcefilename.getName().toString(), destinationfile.getName().toString()));
                    }

                    // add filename to result filename
                    if (add_result_filesname && !iffileexists.equals("fail")
                            && !iffileexists.equals("do_nothing")) {
                        addFileToResultFilenames(destinationfile.toString(), result, parentJob);
                    }

                } else {
                    if (ifmovedfileexists.equals("overwrite_file")) {
                        sourcefilename.moveTo(destinationfile);
                        if (isDetailed()) {
                            logDetailed(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Log.FileOverwrite",
                                    destinationfile.getName().toString()));
                        }

                        // add filename to result filename
                        if (add_result_filesname && !iffileexists.equals("fail")
                                && !iffileexists.equals("do_nothing")) {
                            addFileToResultFilenames(destinationfile.toString(), result, parentJob);
                        }

                        updateSuccess();
                    } else if (ifmovedfileexists.equals("unique_name")) {
                        SimpleDateFormat daf = new SimpleDateFormat();
                        Date now = new Date();
                        daf.applyPattern("ddMMyyyy_HHmmssSSS");
                        String dt = daf.format(now);
                        short_filename += "_" + dt;

                        String destinationfilenamefull = movetofolderfolder.toString() + Const.FILE_SEPARATOR
                                + short_filename;
                        destinationfile = KettleVFS.getFileObject(destinationfilenamefull);

                        sourcefilename.moveTo(destinationfile);
                        if (isDetailed()) {
                            logDetailed(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Log.FileDecrypted",
                                    destinationfile.getName().toString()));
                        }

                        // add filename to result filename
                        if (add_result_filesname && !iffileexists.equals("fail")
                                && !iffileexists.equals("do_nothing")) {
                            addFileToResultFilenames(destinationfile.toString(), result, parentJob);
                        }

                        updateSuccess();
                    } else if (ifmovedfileexists.equals("fail")) {
                        // Update Errors
                        updateErrors();
                    }
                }

            } else if (iffileexists.equals("fail")) {
                // Update Errors
                updateErrors();
            }

        }
    } catch (Exception e) {
        updateErrors();
        logError(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Error.Exception.MoveProcessError",
                sourcefilename.toString(), destinationfilename.toString(), e.getMessage()));
    } finally {
        if (destinationfile != null) {
            try {
                destinationfile.close();
            } catch (IOException ex) { /* Ignore */
            }
        }
    }
    return retval;
}

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

private boolean EncryptFile(int actionType, String shortfilename, FileObject sourcefilename, String userID,
        FileObject destinationfilename, FileObject movetofolderfolder, Job parentJob, Result result) {

    FileObject destinationfile = null;
    boolean retval = false;
    try {//w  w w.  j a va2s.co m
        if (!destinationfilename.exists()) {

            doJob(actionType, sourcefilename, userID, destinationfilename);
            if (isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.FileEncrypted",
                        sourcefilename.getName().toString(), destinationfilename.getName().toString()));
            }

            // add filename to result filename
            if (add_result_filesname && !iffileexists.equals("fail") && !iffileexists.equals("do_nothing")) {
                addFileToResultFilenames(destinationfilename.toString(), result, parentJob);
            }

            updateSuccess();

        } else {
            if (isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.FileExists",
                        destinationfilename.toString()));
            }
            if (iffileexists.equals("overwrite_file")) {
                doJob(actionType, sourcefilename, userID, destinationfilename);
                if (isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.FileOverwrite",
                            destinationfilename.getName().toString()));
                }

                // add filename to result filename
                if (add_result_filesname && !iffileexists.equals("fail")
                        && !iffileexists.equals("do_nothing")) {
                    addFileToResultFilenames(destinationfilename.toString(), result, parentJob);
                }

                updateSuccess();

            } else if (iffileexists.equals("unique_name")) {
                String short_filename = shortfilename;

                // return destination short filename
                try {
                    short_filename = getMoveDestinationFilename(short_filename, "ddMMyyyy_HHmmssSSS");
                } catch (Exception e) {
                    logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Error.GettingFilename",
                            short_filename), e);
                    return retval;
                }

                String movetofilenamefull = destinationfilename.getParent().toString() + Const.FILE_SEPARATOR
                        + short_filename;
                destinationfile = KettleVFS.getFileObject(movetofilenamefull);

                doJob(actionType, sourcefilename, userID, destinationfilename);
                if (isDetailed()) {
                    logDetailed(toString(), BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.FileEncrypted",
                            sourcefilename.getName().toString(), destinationfile.getName().toString()));
                }

                // add filename to result filename
                if (add_result_filesname && !iffileexists.equals("fail")
                        && !iffileexists.equals("do_nothing")) {
                    addFileToResultFilenames(destinationfile.toString(), result, parentJob);
                }

                updateSuccess();
            } else if (iffileexists.equals("delete_file")) {
                destinationfilename.delete();
                if (isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.FileDeleted",
                            destinationfilename.getName().toString()));
                }
            } else if (iffileexists.equals("move_file")) {
                String short_filename = shortfilename;
                // return destination short filename
                try {
                    short_filename = getMoveDestinationFilename(short_filename, null);
                } catch (Exception e) {
                    logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Error.GettingFilename",
                            short_filename), e);
                    return retval;
                }

                String movetofilenamefull = movetofolderfolder.toString() + Const.FILE_SEPARATOR
                        + short_filename;
                destinationfile = KettleVFS.getFileObject(movetofilenamefull);
                if (!destinationfile.exists()) {
                    sourcefilename.moveTo(destinationfile);
                    if (isDetailed()) {
                        logDetailed(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.FileEncrypted",
                                sourcefilename.getName().toString(), destinationfile.getName().toString()));
                    }

                    // add filename to result filename
                    if (add_result_filesname && !iffileexists.equals("fail")
                            && !iffileexists.equals("do_nothing")) {
                        addFileToResultFilenames(destinationfile.toString(), result, parentJob);
                    }

                } else {
                    if (ifmovedfileexists.equals("overwrite_file")) {
                        sourcefilename.moveTo(destinationfile);
                        if (isDetailed()) {
                            logDetailed(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.FileOverwrite",
                                    destinationfile.getName().toString()));
                        }

                        // add filename to result filename
                        if (add_result_filesname && !iffileexists.equals("fail")
                                && !iffileexists.equals("do_nothing")) {
                            addFileToResultFilenames(destinationfile.toString(), result, parentJob);
                        }

                        updateSuccess();
                    } else if (ifmovedfileexists.equals("unique_name")) {
                        SimpleDateFormat daf = new SimpleDateFormat();
                        Date now = new Date();
                        daf.applyPattern("ddMMyyyy_HHmmssSSS");
                        String dt = daf.format(now);
                        short_filename += "_" + dt;

                        String destinationfilenamefull = movetofolderfolder.toString() + Const.FILE_SEPARATOR
                                + short_filename;
                        destinationfile = KettleVFS.getFileObject(destinationfilenamefull);

                        sourcefilename.moveTo(destinationfile);
                        if (isDetailed()) {
                            logDetailed(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.FileEncrypted",
                                    destinationfile.getName().toString()));
                        }

                        // add filename to result filename
                        if (add_result_filesname && !iffileexists.equals("fail")
                                && !iffileexists.equals("do_nothing")) {
                            addFileToResultFilenames(destinationfile.toString(), result, parentJob);
                        }

                        updateSuccess();
                    } else if (ifmovedfileexists.equals("fail")) {
                        // Update Errors
                        updateErrors();
                    }
                }

            } else if (iffileexists.equals("fail")) {
                // Update Errors
                updateErrors();
            }

        }
    } catch (Exception e) {
        updateErrors();
        logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Error.Exception.MoveProcessError",
                sourcefilename.toString(), destinationfilename.toString(), e.getMessage()));
    } finally {
        if (destinationfile != null) {
            try {
                destinationfile.close();
            } catch (IOException ex) { /* Ignore */
            }
        }
    }
    return retval;
}

From source file:org.pentaho.di.job.entries.sftpput.JobEntrySFTPPUT.java

public Result execute(Result previousResult, int nr) throws KettleException {
    Result result = previousResult;
    List<RowMetaAndData> rows = result.getRows();
    result.setResult(false);// ww  w. ja v  a 2 s.c om

    if (log.isDetailed()) {
        logDetailed(BaseMessages.getString(PKG, "JobSFTPPUT.Log.StartJobEntry"));
    }
    ArrayList<FileObject> myFileList = new ArrayList<FileObject>();

    if (copyprevious) {
        if (rows.size() == 0) {
            if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobSFTPPUT.ArgsFromPreviousNothing"));
            }
            result.setResult(true);
            return result;
        }

        try {
            RowMetaAndData resultRow = null;
            // Copy the input row to the (command line) arguments
            for (int iteration = 0; iteration < rows.size(); iteration++) {
                resultRow = rows.get(iteration);

                // Get file names
                String file_previous = resultRow.getString(0, null);
                if (!Const.isEmpty(file_previous)) {
                    FileObject file = KettleVFS.getFileObject(file_previous, this);
                    if (!file.exists()) {
                        logError(BaseMessages.getString(PKG, "JobSFTPPUT.Log.FilefromPreviousNotFound",
                                file_previous));
                    } else {
                        myFileList.add(file);
                        if (log.isDebug()) {
                            logDebug(BaseMessages.getString(PKG, "JobSFTPPUT.Log.FilenameFromResult",
                                    file_previous));
                        }
                    }
                }
            }
        } catch (Exception e) {
            logError(BaseMessages.getString(PKG, "JobSFTPPUT.Error.ArgFromPrevious"));
            result.setNrErrors(1);
            // free resource
            myFileList = null;
            return result;
        }
    }

    if (copypreviousfiles) {
        List<ResultFile> resultFiles = result.getResultFilesList();
        if (resultFiles == null || resultFiles.size() == 0) {
            if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobSFTPPUT.ArgsFromPreviousNothingFiles"));
            }
            result.setResult(true);
            return result;
        }

        try {
            for (Iterator<ResultFile> it = resultFiles.iterator(); it.hasNext() && !parentJob.isStopped();) {
                ResultFile resultFile = it.next();
                FileObject file = resultFile.getFile();
                if (file != null) {
                    if (!file.exists()) {
                        logError(BaseMessages.getString(PKG, "JobSFTPPUT.Log.FilefromPreviousNotFound",
                                file.toString()));
                    } else {
                        myFileList.add(file);
                        if (log.isDebug()) {
                            logDebug(BaseMessages.getString(PKG, "JobSFTPPUT.Log.FilenameFromResult",
                                    file.toString()));
                        }
                    }
                }
            }
        } catch (Exception e) {
            logError(BaseMessages.getString(PKG, "JobSFTPPUT.Error.ArgFromPrevious"));
            result.setNrErrors(1);
            // free resource
            myFileList = null;
            return result;
        }
    }

    SFTPClient sftpclient = null;

    // String substitution..
    String realServerName = environmentSubstitute(serverName);
    String realServerPort = environmentSubstitute(serverPort);
    String realUsername = environmentSubstitute(userName);
    String realPassword = Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(password));
    String realSftpDirString = environmentSubstitute(sftpDirectory);
    String realWildcard = environmentSubstitute(wildcard);
    String realLocalDirectory = environmentSubstitute(localDirectory);
    String realKeyFilename = null;
    String realPassPhrase = null;
    // Destination folder (Move to)
    String realDestinationFolder = environmentSubstitute(getDestinationFolder());

    try {
        // Let's perform some checks before starting

        if (getAfterFTPS() == AFTER_FTPSPUT_MOVE) {
            if (Const.isEmpty(realDestinationFolder)) {
                logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.DestinatFolderMissing"));
                result.setNrErrors(1);
                return result;
            } else {
                FileObject folder = null;
                try {
                    folder = KettleVFS.getFileObject(realDestinationFolder, this);
                    // Let's check if folder exists...
                    if (!folder.exists()) {
                        // Do we need to create it?
                        if (createDestinationFolder) {
                            folder.createFolder();
                        } else {
                            logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.DestinatFolderNotExist",
                                    realDestinationFolder));
                            result.setNrErrors(1);
                            return result;
                        }
                    }
                    realDestinationFolder = KettleVFS.getFilename(folder);
                } catch (Exception e) {
                    throw new KettleException(e);
                } finally {
                    if (folder != null) {
                        try {
                            folder.close();
                        } catch (Exception e) { /* Ignore */
                        }
                    }
                }
            }
        }

        if (isUseKeyFile()) {
            // We must have here a private keyfilename
            realKeyFilename = environmentSubstitute(getKeyFilename());
            if (Const.isEmpty(realKeyFilename)) {
                // Error..Missing keyfile
                logError(BaseMessages.getString(PKG, "JobSFTP.Error.KeyFileMissing"));
                result.setNrErrors(1);
                return result;
            }
            if (!KettleVFS.fileExists(realKeyFilename)) {
                // Error.. can not reach keyfile
                logError(BaseMessages.getString(PKG, "JobSFTP.Error.KeyFileNotFound"));
                result.setNrErrors(1);
                return result;
            }
            realPassPhrase = environmentSubstitute(getKeyPassPhrase());
        }

        // Create sftp client to host ...
        sftpclient = new SFTPClient(InetAddress.getByName(realServerName), Const.toInt(realServerPort, 22),
                realUsername, realKeyFilename, realPassPhrase);
        if (log.isDetailed()) {
            logDetailed(BaseMessages.getString(PKG, "JobSFTPPUT.Log.OpenedConnection", realServerName,
                    "" + realServerPort, realUsername));
        }

        // Set compression
        sftpclient.setCompression(getCompression());

        // Set proxy?
        String realProxyHost = environmentSubstitute(getProxyHost());
        if (!Const.isEmpty(realProxyHost)) {
            // Set proxy
            sftpclient.setProxy(realProxyHost, environmentSubstitute(getProxyPort()),
                    environmentSubstitute(getProxyUsername()), environmentSubstitute(getProxyPassword()),
                    getProxyType());
        }

        // login to ftp host ...
        sftpclient.login(realPassword);
        // Don't show the password in the logs, it's not good for security audits
        // logDetailed("logged in using password "+realPassword); // Logging this seems a bad idea! Oh well.

        // move to spool dir ...
        if (!Const.isEmpty(realSftpDirString)) {
            boolean existfolder = sftpclient.folderExists(realSftpDirString);
            if (!existfolder) {
                if (!isCreateRemoteFolder()) {
                    throw new KettleException(BaseMessages.getString(PKG,
                            "JobSFTPPUT.Error.CanNotFindRemoteFolder", realSftpDirString));
                }
                if (log.isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "JobSFTPPUT.Error.CanNotFindRemoteFolder",
                            realSftpDirString));
                }

                // Let's create folder
                sftpclient.createFolder(realSftpDirString);
                if (log.isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "JobSFTPPUT.Log.RemoteFolderCreated",
                            realSftpDirString));
                }
            }
            sftpclient.chdir(realSftpDirString);
            if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobSFTPPUT.Log.ChangedDirectory", realSftpDirString));
            }
        } // end if

        if (!copyprevious && !copypreviousfiles) {
            // Get all the files in the local directory...
            myFileList = new ArrayList<FileObject>();

            FileObject localFiles = KettleVFS.getFileObject(realLocalDirectory, this);
            FileObject[] children = localFiles.getChildren();
            if (children != null) {
                for (int i = 0; i < children.length; i++) {
                    // Get filename of file or directory
                    if (children[i].getType().equals(FileType.FILE)) {
                        // myFileList.add(children[i].getAbsolutePath());
                        myFileList.add(children[i]);
                    }
                } // end for
            }
        }

        if (myFileList == null || myFileList.size() == 0) {
            if (isSuccessWhenNoFile()) {
                // Just warn user
                if (isBasic()) {
                    logBasic(BaseMessages.getString(PKG, "JobSFTPPUT.Error.NoFileToSend"));
                }
            } else {
                // Fail
                logError(BaseMessages.getString(PKG, "JobSFTPPUT.Error.NoFileToSend"));
                result.setNrErrors(1);
                return result;
            }
        }

        if (log.isDetailed()) {
            logDetailed(
                    BaseMessages.getString(PKG, "JobSFTPPUT.Log.RowsFromPreviousResult", myFileList.size()));
        }

        Pattern pattern = null;
        if (!copyprevious && !copypreviousfiles) {
            if (!Const.isEmpty(realWildcard)) {
                pattern = Pattern.compile(realWildcard);
            }
        }

        // Get the files in the list and execute sftp.put() for each file
        Iterator<FileObject> it = myFileList.iterator();
        while (it.hasNext() && !parentJob.isStopped()) {
            FileObject myFile = it.next();
            try {
                String localFilename = myFile.toString();
                String destinationFilename = myFile.getName().getBaseName();
                boolean getIt = true;

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

                if (getIt) {
                    if (log.isDebug()) {
                        logDebug(BaseMessages.getString(PKG, "JobSFTPPUT.Log.PuttingFile", localFilename,
                                realSftpDirString));
                    }

                    sftpclient.put(myFile, destinationFilename);

                    if (log.isDetailed()) {
                        logDetailed(
                                BaseMessages.getString(PKG, "JobSFTPPUT.Log.TransferedFile", localFilename));
                    }

                    // We successfully uploaded the file
                    // what's next ...
                    switch (getAfterFTPS()) {
                    case AFTER_FTPSPUT_DELETE:
                        myFile.delete();
                        if (log.isDetailed()) {
                            logDetailed(
                                    BaseMessages.getString(PKG, "JobSFTPPUT.Log.DeletedFile", localFilename));
                        }
                        break;
                    case AFTER_FTPSPUT_MOVE:
                        FileObject destination = null;
                        try {
                            destination = KettleVFS.getFileObject(realDestinationFolder + Const.FILE_SEPARATOR
                                    + myFile.getName().getBaseName(), this);
                            myFile.moveTo(destination);
                            if (log.isDetailed()) {
                                logDetailed(BaseMessages.getString(PKG, "JobSFTPPUT.Log.FileMoved", myFile,
                                        destination));
                            }
                        } finally {
                            if (destination != null) {
                                destination.close();
                            }
                        }
                        break;
                    default:
                        if (addFilenameResut) {
                            // Add to the result files...
                            ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, myFile,
                                    parentJob.getJobname(), toString());
                            result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
                            if (log.isDetailed()) {
                                logDetailed(BaseMessages.getString(PKG,
                                        "JobSFTPPUT.Log.FilenameAddedToResultFilenames", localFilename));
                            }
                        }
                        break;
                    }

                }
            } finally {
                if (myFile != null) {
                    myFile.close();
                }
            }
        } // end for

        result.setResult(true);
        // JKU: no idea if this is needed...!
        // result.setNrFilesRetrieved(filesRetrieved);
    } catch (Exception e) {
        result.setNrErrors(1);
        logError(BaseMessages.getString(PKG, "JobSFTPPUT.Exception", e.getMessage()));
        logError(Const.getStackTracker(e));
    } finally {
        // close connection, if possible
        try {
            if (sftpclient != null) {
                sftpclient.disconnect();
            }
        } catch (Exception e) {
            // just ignore this, makes no big difference
        } // end catch
        myFileList = null;
    } // end finally

    return result;
}

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

private boolean deleteOrMoveFiles(FileObject file, String destinationFolder) throws KettleException {
    try {/*from  w ww.j a va 2s.  c om*/
        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  w  ww . java  2s .  com*/

        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;/*from  w w w. j a v  a  2s .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

private ObjectId renameObject(ObjectId id, RepositoryDirectoryInterface newDirectory, String newName,
        String extension) throws KettleException {
    try {/*w ww .  ja  v a 2s.  c  o m*/
        // In case of a root object, the ID is the same as the relative filename...
        //
        FileObject fileObject = KettleVFS.getFileObject(calcDirectoryName(null) + id.getId());

        // Same name, different folder?
        if (Const.isEmpty(newName)) {
            newName = calcObjectName(id);
        }
        // The new filename can be anywhere so we re-calculate a new ID...
        //
        String newFilename = calcDirectoryName(newDirectory) + newName + extension;

        FileObject newObject = KettleVFS.getFileObject(newFilename);
        fileObject.moveTo(newObject);

        return new StringObjectId(calcObjectId(newDirectory, newName, extension));
    } catch (Exception e) {
        throw new KettleException("Unable to rename object with ID [" + id + "] to [" + newName + "]", e);
    }

}

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

public ObjectId renameRepositoryDirectory(ObjectId id, RepositoryDirectoryInterface newParentDir,
        String newName) throws KettleException {
    if (newParentDir != null || newName != null) {
        try {/*from  w  w  w .  j ava 2  s  .c o  m*/
            // In case of a root object, the ID is the same as the relative filename...
            RepositoryDirectoryInterface tree = loadRepositoryDirectoryTree();
            RepositoryDirectoryInterface dir = tree.findDirectory(id);

            if (dir == null) {
                throw new KettleException("Could not find folder [" + id + "]");
            }

            // If newName is null, keep the current name
            newName = (newName != null) ? newName : dir.getName();

            FileObject folder = KettleVFS.getFileObject(dir.getPath());

            String newFolderName = null;

            if (newParentDir != null) {
                FileObject newParentFolder = KettleVFS.getFileObject(newParentDir.getPath());

                newFolderName = newParentFolder.toString() + "/" + newName;
            } else {
                newFolderName = folder.getParent().toString() + "/" + newName;
            }

            FileObject newFolder = KettleVFS.getFileObject(newFolderName);
            folder.moveTo(newFolder);

            return new StringObjectId(dir.getObjectId());
        } catch (Exception e) {
            throw new KettleException("Unable to rename directory folder to [" + id + "]");
        }
    }
    return (id);
}