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:com.panet.imeta.job.entries.ssh2put.JobEntrySSH2PUT.java

private boolean deleteOrMoveFiles(FileObject file, String destinationFolder) throws KettleException {
    try {/*from  ww  w  .  jav a 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())
                log.logDetailed(toString(), Messages.getString("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());
                file.moveTo(destination);
                retval = true;
            } catch (Exception e) {
                log.logError(toString(), Messages.getString("JobSSH2PUT.Cant_Move_File.Label", file.toString(),
                        destinationFolder, e.getMessage()));
            } finally {
                if (destination != null) {
                    try {
                        destination.close();
                    } catch (Exception ex) {
                    }
                    ;
                }
                if (source != null) {
                    try {
                        source.close();
                    } catch (Exception ex) {
                    }
                    ;
                }
            }
            if (log.isDetailed())
                log.logDetailed(toString(),
                        Messages.getString("JobSSH2PUT.Log.MovedFile", file.toString(), ftpDirectory));
        }
        return retval;
    } catch (Exception e) {
        throw new KettleException(e);
    }
}

From source file:com.panet.imeta.job.entries.copymoveresultfilenames.JobEntryCopyMoveResultFilenames.java

private boolean ProcessFile(FileObject sourcefile, String destinationFolder, LogWriter log, Result result,
        Job parentJob) {//from w w  w  . j  a va  2  s .c  om
    boolean retval = false;
    boolean filexists = false;
    try {
        // 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);
        filexists = destinationfile.exists();
        if (filexists) {
            if (log.isDetailed())
                log.logDetailed(toString(), Messages.getString("JobEntryCopyMoveResultFilenames.Log.FileExists",
                        destinationFilename));
        }
        if ((!filexists) || (filexists && isOverwriteFile())) {
            if (getAction().equals("copy")) {
                // Copy file
                FileUtil.copyContent(sourcefile, destinationfile);
                if (log.isDetailed())
                    log.logDetailed(toString(),
                            Messages.getString("JobEntryCopyMoveResultFilenames.log.CopiedFile",
                                    sourcefile.toString(), destinationFolder));
            } else {
                // Move file
                sourcefile.moveTo(destinationfile);
                if (log.isDetailed())
                    log.logDetailed(toString(),
                            Messages.getString("JobEntryCopyMoveResultFilenames.log.MovedFile",
                                    sourcefile.toString(), destinationFolder));
            }

            if (isRemovedSourceFilename()) {
                // Remove source file from result files list
                result.getResultFiles().remove(sourcefile.toString());
                if (log.isDetailed())
                    log.logDetailed(toString(), Messages.getString(
                            "JobEntryCopyMoveResultFilenames.RemovedFileFromResult", sourcefile.toString()));
            }
            if (isAddDestinationFilename()) {
                // Add destination filename to Resultfilenames ...
                ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL,
                        KettleVFS.getFileObject(destinationfile.toString()), parentJob.getJobname(),
                        toString());
                result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
                if (log.isDetailed())
                    log.logDetailed(toString(), Messages.getString(
                            "JobEntryCopyMoveResultFilenames.AddedFileToResult", destinationfile.toString()));
            }
        }
        retval = true;
    } catch (Exception e) {
        log.logError(toString(),
                Messages.getString("JobEntryCopyMoveResultFilenames.Log.ErrorProcessing", e.toString()));
    }

    return retval;
}

From source file:com.akretion.kettle.steps.terminatooor.ScriptValuesAddedFunctions.java

public static void moveFile(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {

    try {//from www  .j a  v  a 2 s  .  c  o  m
        if (ArgList.length == 3 && !isNull(ArgList[0]) && !isNull(ArgList[1]) && !isUndefined(ArgList[0])
                && !isUndefined(ArgList[1])) {
            FileObject fileSource = null, fileDestination = null;

            try {
                // Source file to move
                fileSource = KettleVFS.getFileObject((String) ArgList[0]);
                // Destination filename
                fileDestination = KettleVFS.getFileObject((String) ArgList[1]);
                if (fileSource.exists()) {
                    // Source file exists...
                    if (fileSource.getType() == FileType.FILE) {
                        // Great..source is a file ...
                        boolean overwrite = false;
                        if (!ArgList[1].equals(null))
                            overwrite = (Boolean) ArgList[2];
                        boolean destinationExists = fileDestination.exists();
                        // Let's move the file...
                        if ((destinationExists && overwrite) || !destinationExists)
                            fileSource.moveTo(fileDestination);

                    }
                } else {
                    new RuntimeException("file to move [" + (String) ArgList[0] + "] can not be found!");
                }
            } catch (IOException e) {
                throw new RuntimeException("The function call moveFile throw an error : " + e.toString());
            } finally {
                if (fileSource != null)
                    try {
                        fileSource.close();
                    } catch (Exception e) {
                    }
                if (fileDestination != null)
                    try {
                        fileDestination.close();
                    } catch (Exception e) {
                    }
            }

        } else {
            throw new RuntimeException("The function call copyFile is not valid.");
        }
    } catch (Exception e) {
        throw new RuntimeException(e.toString());
    }
}

From source file:com.panet.imeta.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java

public static void moveFile(Context actualContext, Scriptable actualObject, Object[] ArgList,
        Function FunctionContext) {

    try {//www .  java  2s .co  m
        if (ArgList.length == 3 && !isNull(ArgList[0]) && !isNull(ArgList[1]) && !isUndefined(ArgList[0])
                && !isUndefined(ArgList[1])) {
            FileObject fileSource = null, fileDestination = null;

            try {
                // Source file to move
                fileSource = KettleVFS.getFileObject(Context.toString(ArgList[0]));
                // Destination filename
                fileDestination = KettleVFS.getFileObject(Context.toString(ArgList[1]));
                if (fileSource.exists()) {
                    // Source file exists...
                    if (fileSource.getType() == FileType.FILE) {
                        // Great..source is a file ...
                        boolean overwrite = false;
                        if (!ArgList[1].equals(null))
                            overwrite = Context.toBoolean(ArgList[2]);
                        boolean destinationExists = fileDestination.exists();
                        // Let's move the file...
                        if ((destinationExists && overwrite) || !destinationExists)
                            fileSource.moveTo(fileDestination);

                    }
                } else {
                    Context.reportRuntimeError(
                            "file to move [" + Context.toString(ArgList[0]) + "] can not be found!");
                }
            } catch (IOException e) {
                throw Context.reportRuntimeError("The function call moveFile throw an error : " + e.toString());
            } finally {
                if (fileSource != null)
                    try {
                        fileSource.close();
                    } catch (Exception e) {
                    }
                if (fileDestination != null)
                    try {
                        fileDestination.close();
                    } catch (Exception e) {
                    }
            }

        } else {
            throw Context.reportRuntimeError("The function call copyFile is not valid.");
        }
    } catch (Exception e) {
        throw Context.reportRuntimeError(e.toString());
    }
}

From source file:be.ibridge.kettle.job.entry.zipfile.JobEntryZipFile.java

public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = new Result(nr);
    result.setResult(false);//from   w  w  w .j  a v  a  2 s  .c  om
    boolean Fileexists = false;

    String realZipfilename = StringUtil.environmentSubstitute(zipFilename);
    String realWildcard = StringUtil.environmentSubstitute(wildcard);
    String realWildcardExclude = StringUtil.environmentSubstitute(wildcardexclude);
    String realTargetdirectory = StringUtil.environmentSubstitute(sourcedirectory);
    String realMovetodirectory = StringUtil.environmentSubstitute(movetodirectory);

    if (realZipfilename != null) {
        FileObject fileObject = null;
        try {
            fileObject = KettleVFS.getFileObject(realZipfilename);
            // Check if Zip File exists
            if (fileObject.exists()) {
                Fileexists = true;
                log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileExists1.Label")
                        + realZipfilename + Messages.getString("JobZipFiles.Zip_FileExists2.Label"));
            } else {
                Fileexists = false;
            }

            // Let's start the process now
            if (ifzipfileexists == 3 && Fileexists) {
                // the zip file exists and user want to Fail
                result.setResult(false);
                result.setNrErrors(1);

            } else if (ifzipfileexists == 2 && Fileexists) {
                // the zip file exists and user want to do nothing
                result.setResult(true);

            } else if (afterzip == 2 && realMovetodirectory == null) {
                // After Zip, Move files..User must give a destination Folder
                result.setResult(false);
                result.setNrErrors(1);
                log.logError(toString(),
                        Messages.getString("JobZipFiles.AfterZip_No_DestinationFolder_Defined.Label"));

            } else
            // After Zip, Move files..User must give a destination Folder
            {

                if (ifzipfileexists == 0 && Fileexists) {

                    // the zip file exists and user want to create new one with unique name
                    //Format Date

                    DateFormat dateFormat = new SimpleDateFormat("hhmmss_mmddyyyy");
                    realZipfilename = realZipfilename + "_" + dateFormat.format(new Date()) + ".zip";
                    log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileNameChange1.Label")
                            + realZipfilename + Messages.getString("JobZipFiles.Zip_FileNameChange1.Label"));

                } else if (ifzipfileexists == 1 && Fileexists) {
                    log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileAppend1.Label")
                            + realZipfilename + Messages.getString("JobZipFiles.Zip_FileAppend2.Label"));
                }

                // Get all the files in the directory...

                File f = new File(realTargetdirectory);

                String[] filelist = f.list();

                log.logDetailed(toString(),
                        Messages.getString("JobZipFiles.Files_Found1.Label") + filelist.length
                                + Messages.getString("JobZipFiles.Files_Found2.Label") + realTargetdirectory
                                + Messages.getString("JobZipFiles.Files_Found3.Label"));

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

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

                }

                // Prepare Zip File
                byte[] buffer = new byte[18024];

                FileOutputStream dest = new FileOutputStream(realZipfilename);
                BufferedOutputStream buff = new BufferedOutputStream(dest);
                ZipOutputStream out = new ZipOutputStream(buff);

                // 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...)
                String[] ZippedFiles = new String[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!
                    if (pattern != null) {
                        Matcher matcher = pattern.matcher(filelist[i]);
                        getIt = matcher.matches();
                    }

                    if (patternexclude != null) {
                        Matcher matcherexclude = patternexclude.matcher(filelist[i]);
                        getItexclude = matcherexclude.matches();
                    }

                    // Get processing File
                    String targetFilename = realTargetdirectory + Const.FILE_SEPARATOR + filelist[i];
                    File file = new File(targetFilename);

                    if (getIt && !getItexclude && !file.isDirectory()) {

                        // We can add the file to the Zip Archive

                        log.logDebug(toString(),
                                Messages.getString("JobZipFiles.Add_FilesToZip1.Label") + filelist[i]
                                        + Messages.getString("JobZipFiles.Add_FilesToZip2.Label")
                                        + realTargetdirectory
                                        + Messages.getString("JobZipFiles.Add_FilesToZip3.Label"));

                        // Associate a file input stream for the current file
                        FileInputStream in = new FileInputStream(targetFilename);

                        // Add ZIP entry to output stream.
                        out.putNextEntry(new ZipEntry(filelist[i]));

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

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

                //-----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 File
                            FileObject fileObjectd = KettleVFS
                                    .getFileObject(realTargetdirectory + Const.FILE_SEPARATOR + ZippedFiles[i]);

                            // Here we can move, delete files
                            if (afterzip == 1) {
                                // Delete File
                                boolean deleted = fileObjectd.delete();
                                if (!deleted) {
                                    result.setResult(false);
                                    result.setNrErrors(1);
                                    log.logError(toString(),
                                            Messages.getString("JobZipFiles.Cant_Delete_File1.Label")
                                                    + realTargetdirectory + Const.FILE_SEPARATOR
                                                    + ZippedFiles[i] + Messages
                                                            .getString("JobZipFiles.Cant_Delete_File2.Label"));

                                }
                                // File deleted
                                log.logDebug(toString(),
                                        Messages.getString("JobZipFiles.File_Deleted1.Label")
                                                + realTargetdirectory + Const.FILE_SEPARATOR + ZippedFiles[i]
                                                + Messages.getString("JobZipFiles.File_Deleted2.Label"));
                            } else if (afterzip == 2) {
                                // Move File   
                                try {
                                    FileObject fileObjectm = KettleVFS.getFileObject(
                                            realMovetodirectory + Const.FILE_SEPARATOR + ZippedFiles[i]);
                                    fileObjectd.moveTo(fileObjectm);
                                } catch (IOException e) {
                                    log.logError(toString(),
                                            Messages.getString("JobZipFiles.Cant_Move_File1.Label")
                                                    + ZippedFiles[i]
                                                    + Messages.getString("JobZipFiles.Cant_Move_File2.Label")
                                                    + e.getMessage());
                                    result.setResult(false);
                                    result.setNrErrors(1);
                                }
                                // File moved
                                log.logDebug(toString(), Messages.getString("JobZipFiles.File_Moved1.Label")
                                        + ZippedFiles[i] + Messages.getString("JobZipFiles.File_Moved2.Label"));
                            }
                        }
                    }
                }
                result.setResult(true);
            }
        } catch (IOException e) {
            log.logError(toString(),
                    Messages.getString("JobZipFiles.Cant_CreateZipFile1.Label") + realZipfilename
                            + Messages.getString("JobZipFiles.Cant_CreateZipFile2.Label") + e.getMessage());
            result.setResult(false);
            result.setNrErrors(1);
        } finally {
            if (fileObject != null) {
                try {
                    fileObject.close();
                } catch (IOException ex) {
                }
                ;
            }
        }
    } else {
        result.setResult(false);
        result.setNrErrors(1);
        log.logError(toString(), Messages.getString("JobZipFiles.No_ZipFile_Defined.Label"));
    }

    return result;
}

From source file:com.panet.imeta.job.entries.zipfile.JobEntryZipFile.java

public boolean processRowFile(Job parentJob, Result result, String realZipfilename, String realWildcard,
        String realWildcardExclude, String realTargetdirectory, String realMovetodirectory,
        boolean createparentfolder) {
    LogWriter log = LogWriter.getInstance();
    boolean Fileexists = false;
    File tempFile = null;/*  www.j a  v a  2  s.co 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;
    FileOutputStream dest = null;
    BufferedOutputStream buff = null;
    org.apache.tools.zip.ZipOutputStream out = null;
    org.apache.tools.zip.ZipEntry entry = null;

    try {
        OriginFile = KettleVFS.getFileObject(realTargetdirectory);
        orginexist = OriginFile.exists();
    } catch (Exception e) {
    } finally {
        if (OriginFile != null) {
            try {
                OriginFile.close();
            } catch (IOException ex) {
            }
            ;
        }
    }

    if (realZipfilename != null && orginexist) {

        FileObject fileObject = null;
        try {
            fileObject = KettleVFS.getFileObject(realZipfilename);

            // Check if Zip File exists
            if (fileObject.exists()) {
                Fileexists = true;
                if (log.isDebug())
                    log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileExists1.Label")
                            + realZipfilename + Messages.getString("JobZipFiles.Zip_FileExists2.Label"));
            }
            // Let's see if we need to create parent folder of destination
            // zip filename
            if (createparentfolder) {
                createParentFolder(realZipfilename);
            }

            // 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,
                            KettleVFS.getFileObject(realZipfilename), 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;
                log.logError(toString(),
                        Messages.getString("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
                String[] filelist = null;

                File f = new File(realTargetdirectory);
                if (f.isDirectory()) {
                    // Target is a directory
                    // Get all the files in the directory...
                    filelist = f.list();
                } else {
                    // Target is a file
                    filelist = new String[1];
                    filelist[0] = f.getName();
                }
                if (filelist.length == 0) {
                    resultat = false;
                    log.logError(toString(),
                            Messages.getString("JobZipFiles.Log.FolderIsEmpty", realTargetdirectory));
                } else if (!checkContainsFile(realTargetdirectory, filelist)) {
                    resultat = false;
                    log.logError(toString(),
                            Messages.getString("JobZipFiles.Log.NoFilesInFolder", realTargetdirectory));
                } 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 (realZipfilename.toLowerCase().endsWith(".zip")) {
                            // strip this off
                            realZipfilename = realZipfilename.substring(0, realZipfilename.length() - 4);
                        }

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

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

                        renameOk = fileZip.renameTo(tempFile);

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

                    if (log.isDetailed())
                        log.logDetailed(toString(), Messages.getString("JobZipFiles.Files_Found1.Label")
                                + filelist.length + Messages.getString("JobZipFiles.Files_Found2.Label")
                                + realTargetdirectory + Messages.getString("JobZipFiles.Files_Found3.Label"));

                    Pattern pattern = null;
                    Pattern patternexclude = null;
                    // Let's prepare pattern..only if target is a folder !
                    if (f.isDirectory()) {
                        if (!Const.isEmpty(realWildcard)) {
                            pattern = Pattern.compile(realWildcard);
                        }

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

                    // Prepare Zip File
                    buffer = new byte[18024];
                    dest = new FileOutputStream(realZipfilename);
                    buff = new BufferedOutputStream(dest);
                    out = new org.apache.tools.zip.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 = (ZipEntry) 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 = (ZipEntry) zin.getNextEntry();
                        }
                        // Close the streams
                        zin.close();
                    }

                    // Set the method
                    out.setMethod(org.apache.tools.zip.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...)
                    String[] ZippedFiles = new String[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 (f.isDirectory()) {
                            if (pattern != null) {
                                Matcher matcher = pattern.matcher(filelist[i]);
                                getIt = matcher.matches();
                            }

                            if (patternexclude != null) {
                                Matcher matcherexclude = patternexclude.matcher(filelist[i]);
                                getItexclude = matcherexclude.matches();
                            }
                        }
                        // Get processing File
                        String targetFilename = realTargetdirectory + Const.FILE_SEPARATOR + filelist[i];
                        if (f.isFile())
                            targetFilename = realTargetdirectory;

                        File file = new File(targetFilename);

                        if (getIt && !getItexclude && !file.isDirectory() && !fileSet.contains(filelist[i])) {

                            // We can add the file to the Zip Archive
                            if (log.isDebug())
                                log.logDebug(toString(),
                                        Messages.getString("JobZipFiles.Add_FilesToZip1.Label") + filelist[i]
                                                + Messages.getString("JobZipFiles.Add_FilesToZip2.Label")
                                                + realTargetdirectory
                                                + Messages.getString("JobZipFiles.Add_FilesToZip3.Label"));

                            // Associate a file input stream for the current
                            // file
                            FileInputStream in = new FileInputStream(targetFilename);
                            // Add ZIP entry to output stream.
                            out.putNextEntry(new ZipEntry(filelist[i]));

                            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())
                        log.logBasic(toString(), Messages.getString("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 File
                                FileObject fileObjectd = KettleVFS.getFileObject(
                                        realTargetdirectory + Const.FILE_SEPARATOR + ZippedFiles[i]);
                                if (f.isFile())
                                    fileObjectd = KettleVFS.getFileObject(realTargetdirectory);

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

                                // Here we can move, delete files
                                if (afterzip == 1) {

                                    // Delete File
                                    boolean deleted = fileObjectd.delete();
                                    if (!deleted) {
                                        resultat = false;
                                        log.logError(toString(), Messages
                                                .getString("JobZipFiles.Cant_Delete_File1.Label")
                                                + realTargetdirectory + Const.FILE_SEPARATOR + ZippedFiles[i]
                                                + Messages.getString("JobZipFiles.Cant_Delete_File2.Label"));

                                    }
                                    // File deleted
                                    if (log.isDebug())
                                        log.logDebug(toString(),
                                                Messages.getString("JobZipFiles.File_Deleted1.Label")
                                                        + realTargetdirectory + Const.FILE_SEPARATOR
                                                        + ZippedFiles[i] + Messages
                                                                .getString("JobZipFiles.File_Deleted2.Label"));
                                } else if (afterzip == 2) {
                                    // Move File
                                    try {
                                        FileObject fileObjectm = KettleVFS.getFileObject(
                                                realMovetodirectory + Const.FILE_SEPARATOR + ZippedFiles[i]);
                                        fileObjectd.moveTo(fileObjectm);
                                    } catch (IOException e) {
                                        log.logError(toString(),
                                                Messages.getString("JobZipFiles.Cant_Move_File1.Label")
                                                        + ZippedFiles[i]
                                                        + Messages
                                                                .getString("JobZipFiles.Cant_Move_File2.Label")
                                                        + e.getMessage());
                                        resultat = false;
                                    }
                                    // File moved
                                    if (log.isDebug())
                                        log.logDebug(toString(),
                                                Messages.getString("JobZipFiles.File_Moved1.Label")
                                                        + ZippedFiles[i]
                                                        + Messages.getString("JobZipFiles.File_Moved2.Label"));
                                }
                            }
                        }
                    }

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

                    resultat = true;
                }
            }
        } catch (Exception e) {
            log.logError(toString(),
                    Messages.getString("JobZipFiles.Cant_CreateZipFile1.Label") + realZipfilename
                            + Messages.getString("JobZipFiles.Cant_CreateZipFile2.Label") + e.getMessage());
            // result.setResult( false );
            // result.setNrErrors(1);
            resultat = false;
        } finally {
            if (fileObject != null) {
                try {
                    fileObject.close();
                } catch (IOException ex) {
                }
                ;
            }
            // Close the ZipOutPutStream
            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) {
            }
            ;
        }
    } else {
        resultat = true;
        if (realZipfilename == null)
            log.logError(toString(), Messages.getString("JobZipFiles.No_ZipFile_Defined.Label"));
        if (!orginexist)
            log.logError(toString(),
                    Messages.getString("JobZipFiles.No_FolderCible_Defined.Label", realTargetdirectory));
    }
    // return a verifier
    return resultat;
}

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

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

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

        if (log.isDetailed())
            log.logDetailed(toString(),
                    Messages.getString("JobUnZip.Log.ProcessingFile", sourceFileObject.toString()));

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

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

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

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

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

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

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

        }

        for (FileObject item : items) {

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

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

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

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

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

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

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

                    boolean take = takeThisFile(log, item, newFileName);

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

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

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

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

                            if (log.isDebug())
                                log.logDebug(toString(),
                                        Messages.getString("JobUnZip.Log.CreatingUniqFile", newFileName));
                        }

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

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

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

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

                                // Add filename to result filenames
                                addFilenameToResultFilenames(result, parentJob, newFileName);
                            }
                        } finally {
                            if (is != null)
                                is.close();
                            if (os != null)
                                os.close();
                        }
                    } // end if take
                }
            } catch (Exception e) {
                updateErrors();
                log.logError(toString(), Messages.getString("JobUnZip.Error.CanNotProcessZipEntry",
                        item.getName().getURI(), sourceFileObject.toString()), e);
            }
        } // End while

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

        // System.gc();

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

                fileObject.moveTo(destFile);

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

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

    return retval;
}

From source file:org.efaps.webdav4vfs.handler.MoveHandler.java

@Override()
protected void copyOrMove(final FileObject _object, final FileObject _target, final int _depth)
        throws FileSystemException {
    _object.moveTo(_target);
}

From source file:org.jahia.services.content.impl.vfs.VFSSessionImpl.java

public void move(String source, String dest) throws ItemExistsException, PathNotFoundException,
        VersionException, ConstraintViolationException, LockException, RepositoryException {
    try {/*from   www .  j  a v a  2s . c  o  m*/
        FileObject object1 = repository.getFile(source);
        if (!object1.exists()) {
            throw new PathNotFoundException(source);
        }
        FileObject object2 = repository.getFile(dest);
        if (object2.exists()) {
            throw new ItemExistsException(dest);
        }
        object1.moveTo(object2);
    } catch (FileSystemException e) {
        throw new RepositoryException(e);
    }

}

From source file:org.pentaho.di.job.entries.checkfilelocked.LockFile.java

/**
 * Checks if a file is locked In order to check is a file is locked we will use a dummy renaming exercise
 *
 * @param filename//  www .j  a v a 2s .c  om
 * @throws KettleException
 */
public LockFile(String filename) throws KettleException {
    setFilename(filename);
    setLocked(false);

    // In order to check is a file is locked
    // we will use a dummy renaming exercise
    FileObject file = null;
    FileObject dummyfile = null;

    try {

        file = KettleVFS.getFileObject(filename);
        if (file.exists()) {
            dummyfile = KettleVFS.getFileObject(filename);
            // move file to itself!
            file.moveTo(dummyfile);
        }
    } catch (Exception e) {
        // We got an exception
        // The is locked by another process
        setLocked(true);
    } finally {
        if (file != null) {
            try {
                file.close();
            } catch (Exception e) { /* Ignore */
            }
        }
        if (dummyfile != null) {
            try {
                file.close();
            } catch (Exception e) { /* Ignore */
            }
        }
    }

}