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

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

Introduction

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

Prototype

public void close() throws FileSystemException;

Source Link

Document

Closes this file, and its content.

Usage

From source file:com.panet.imeta.trans.steps.xsdvalidator.XsdValidator.java

public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    meta = (XsdValidatorMeta) smi;//from  w w  w.j av a  2s. c  o m
    data = (XsdValidatorData) sdi;

    Object[] row = getRow();

    if (row == null) // no more input to be expected...
    {
        setOutputDone();
        return false;
    }

    if (first) {
        first = false;
        data.outputRowMeta = getInputRowMeta().clone();
        meta.getFields(data.outputRowMeta, getStepname(), null, null, this);

        // Check if XML stream is given
        if (meta.getXMLStream() != null) {
            // Try to get XML Field index
            data.xmlindex = getInputRowMeta().indexOfValue(meta.getXMLStream());
            // Let's check the Field
            if (data.xmlindex < 0) {
                // The field is unreachable !
                logError(Messages.getString("XsdValidator.Log.ErrorFindingField") + "[" + meta.getXMLStream() //$NON-NLS-1$//$NON-NLS-2$
                        + "]");
                throw new KettleStepException(
                        Messages.getString("XsdValidator.Exception.CouldnotFindField", meta.getXMLStream())); //$NON-NLS-1$ //$NON-NLS-2$
            }

            // Let's check that Result Field is given
            if (meta.getResultfieldname() == null) {
                //   Result field is missing !
                logError(Messages.getString("XsdValidator.Log.ErrorResultFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$
                throw new KettleStepException(
                        Messages.getString("XsdValidator.Exception.ErrorResultFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$
            }

            // Is XSD file is provided?
            if (meta.getXSDSource().equals(meta.SPECIFY_FILENAME)) {
                if (meta.getXSDFilename() == null) {
                    logError(Messages.getString("XsdValidator.Log.ErrorXSDFileMissing")); //$NON-NLS-1$ //$NON-NLS-2$
                    throw new KettleStepException(
                            Messages.getString("XsdValidator.Exception.ErrorXSDFileMissing")); //$NON-NLS-1$ //$NON-NLS-2$
                } else {
                    // Is XSD file exists ?
                    FileObject xsdfile = null;
                    try {
                        xsdfile = KettleVFS.getFileObject(environmentSubstitute(meta.getXSDFilename()));
                        if (!xsdfile.exists()) {
                            logError(Messages.getString("XsdValidator.Log.Error.XSDFileNotExists"));
                            throw new KettleStepException(
                                    Messages.getString("XsdValidator.Exception.XSDFileNotExists"));
                        }

                    } catch (Exception e) {
                        logError(Messages.getString("XsdValidator.Log.Error.GettingXSDFile"));
                        throw new KettleStepException(
                                Messages.getString("XsdValidator.Exception.GettingXSDFile"));
                    } finally {
                        try {
                            if (xsdfile != null)
                                xsdfile.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }

            // Is XSD field is provided?
            if (meta.getXSDSource().equals(meta.SPECIFY_FIELDNAME)) {
                if (meta.getXSDDefinedField() == null) {
                    logError(Messages.getString("XsdValidator.Log.Error.XSDFieldMissing"));
                    throw new KettleStepException(Messages.getString("XsdValidator.Exception.XSDFieldMissing"));
                } else {
                    // Let's check if the XSD field exist
                    // Try to get XML Field index
                    data.xsdindex = getInputRowMeta().indexOfValue(meta.getXSDDefinedField());

                    if (data.xsdindex < 0) {
                        // The field is unreachable !
                        logError(Messages.getString("XsdValidator.Log.ErrorFindingXSDField", //$NON-NLS-1$
                                meta.getXSDDefinedField())); //$NON-NLS-2$
                        throw new KettleStepException(Messages.getString(
                                "XsdValidator.Exception.ErrorFindingXSDField", meta.getXSDDefinedField())); //$NON-NLS-1$ //$NON-NLS-2$
                    }
                }
            }

        } else {
            // XML stream field is missing !
            logError(Messages.getString("XsdValidator.Log.Error.XmlStreamFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$
            throw new KettleStepException(Messages.getString("XsdValidator.Exception.XmlStreamFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }

    boolean sendToErrorRow = false;
    String errorMessage = null;

    try {

        // Get the XML field value
        String XMLFieldvalue = getInputRowMeta().getString(row, data.xmlindex);

        boolean isvalid = false;

        // XSD filename
        String xsdfilename = null;

        if (meta.getXSDSource().equals(meta.SPECIFY_FILENAME)) {
            xsdfilename = environmentSubstitute(meta.getXSDFilename());
        } else if (meta.getXSDSource().equals(meta.SPECIFY_FIELDNAME)) {
            // Get the XSD field value
            xsdfilename = getInputRowMeta().getString(row, data.xsdindex);
        }

        // Get XSD filename
        FileObject xsdfile = null;
        String validationmsg = null;
        try {

            SchemaFactory factoryXSDValidator = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            xsdfile = KettleVFS.getFileObject(xsdfilename);
            File XSDFile = new File(KettleVFS.getFilename(xsdfile));

            //   Get XML stream      
            Source sourceXML = new StreamSource(new StringReader(XMLFieldvalue));

            if (meta.getXMLSourceFile()) {

                // We deal with XML file
                // Get XML File
                File xmlfileValidator = new File(XMLFieldvalue);
                if (!xmlfileValidator.exists()) {
                    logError(Messages.getString("XsdValidator.Log.Error.XMLfileMissing", XMLFieldvalue)); //$NON-NLS-1$ //$NON-NLS-2$
                    throw new KettleStepException(
                            Messages.getString("XsdValidator.Exception.XMLfileMissing", XMLFieldvalue)); //$NON-NLS-1$ //$NON-NLS-2$
                }
                sourceXML = new StreamSource(xmlfileValidator);
            }

            // Create XSD schema
            Schema SchematXSD = factoryXSDValidator.newSchema(XSDFile);

            if (meta.getXSDSource().equals(meta.NO_NEED)) {
                // ---Some documents specify the schema they expect to be validated against, 
                // ---typically using xsi:noNamespaceSchemaLocation and/or xsi:schemaLocation attributes
                //---Schema SchematXSD = factoryXSDValidator.newSchema();
                SchematXSD = factoryXSDValidator.newSchema();
            }

            // Create XSDValidator
            Validator XSDValidator = SchematXSD.newValidator();
            // Validate XML / XSD      
            XSDValidator.validate(sourceXML);

            isvalid = true;

        } catch (SAXException ex) {
            validationmsg = ex.getMessage();
            logError("SAX Exception : " + ex);
        } catch (IOException ex) {
            validationmsg = ex.getMessage();
            logError("SAX Exception : " + ex);
        } finally {
            try {
                if (xsdfile != null)
                    xsdfile.close();

            } catch (IOException e) {
            }
        }

        Object[] outputRowData = null;
        Object[] outputRowData2 = null;

        if (meta.getOutputStringField()) {
            // Output type=String
            if (isvalid)
                outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(),
                        environmentSubstitute(meta.getIfXmlValid()));
            else
                outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(),
                        environmentSubstitute(meta.getIfXmlInvalid()));
        } else {
            outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(), isvalid);
        }

        if (meta.useAddValidationMessage())
            outputRowData2 = RowDataUtil.addValueData(outputRowData, getInputRowMeta().size() + 1,
                    validationmsg);
        else
            outputRowData2 = outputRowData;

        if (log.isRowLevel())
            logRowlevel(
                    Messages.getString("XsdValidator.Log.ReadRow") + " " + getInputRowMeta().getString(row));

        //   add new values to the row.
        putRow(data.outputRowMeta, outputRowData2); // copy row to output rowset(s);
    } catch (KettleException e) {
        if (getStepMeta().isDoingErrorHandling()) {
            sendToErrorRow = true;
            errorMessage = e.toString();
        }

        if (sendToErrorRow) {
            // Simply add this row to the error row
            putError(getInputRowMeta(), row, 1, errorMessage, null, "XSD001");
        } else {
            logError(Messages.getString("XsdValidator.ErrorProcesing" + " : " + e.getMessage()));
            throw new KettleStepException(Messages.getString("XsdValidator.ErrorProcesing"), e);
        }
    }

    return true;

}

From source file:com.panet.imeta.trans.steps.propertyoutput.PropertyOutput.java

private void createParentFolder() throws KettleException {
    // Do we need to create parent folder ?
    if (meta.isCreateParentFolder()) {
        // Check for parent folder
        FileObject parentfolder = null;
        try {/*from   ww  w. ja v a  2s .  c  o  m*/
            // Get parent folder
            parentfolder = KettleVFS.getFileObject(data.filename).getParent();
            if (!parentfolder.exists()) {
                if (log.isDetailed())
                    log.logDetailed(toString(), Messages.getString("PropertyOutput.Log.ParentFolderExists",
                            parentfolder.getName().toString()));
                parentfolder.createFolder();
                if (log.isDetailed())
                    log.logDetailed(toString(), Messages.getString(
                            "PropertyOutput.Log.CanNotCreateParentFolder", parentfolder.getName().toString()));
            }
        } catch (Exception e) {
            // The field is unreachable !
            logError(Messages.getString("PropertyOutput.Log.CanNotCreateParentFolder",
                    parentfolder.getName().toString()));
            throw new KettleException(Messages.getString("PropertyOutput.Log.CanNotCreateParentFolder",
                    parentfolder.getName().toString()));

        } finally {
            if (parentfolder != null) {
                try {
                    parentfolder.close();
                } catch (Exception ex) {
                }
                ;
            }
        }
    }
}

From source file:com.panet.imeta.job.entries.filesexist.JobEntryFilesExist.java

public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = previousResult;
    result.setResult(false);//  w ww . jav  a2 s . co  m
    int missingfiles = 0;

    if (arguments != null) {
        for (int i = 0; i < arguments.length && !parentJob.isStopped(); i++) {
            FileObject file = null;

            try {
                String realFilefoldername = environmentSubstitute(arguments[i]);
                file = KettleVFS.getFileObject(realFilefoldername);

                if (file.exists() && file.isReadable()) {
                    if (log.isDetailed())
                        log.logDetailed(toString(),
                                Messages.getString("JobEntryFilesExist.File_Exists", realFilefoldername)); //$NON-NLS-1$
                } else {
                    missingfiles++;
                    result.setNrErrors(missingfiles);
                    if (log.isDetailed())
                        log.logDetailed(toString(), Messages.getString("JobEntryFilesExist.File_Does_Not_Exist", //$NON-NLS-1$
                                realFilefoldername));
                }

            } catch (IOException e) {
                missingfiles++;
                result.setNrErrors(missingfiles);
                log.logError(toString(),
                        Messages.getString("JobEntryFilesExist.ERROR_0004_IO_Exception", e.toString())); //$NON-NLS-1$
            } finally {
                if (file != null) {
                    try {
                        file.close();
                    } catch (IOException ex) {
                    }
                    ;
                }
            }
        }

    }

    if (missingfiles == 0)
        result.setResult(true);

    return result;
}

From source file:be.ibridge.kettle.job.entry.createfile.JobEntryCreateFile.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 av  a  2  s. c o  m

    if (filename != null) {
        String realFilename = getRealFilename();
        FileObject fileObject = null;
        try {
            fileObject = KettleVFS.getFileObject(realFilename);

            if (fileObject.exists()) {
                if (isFailIfFileExists()) {
                    // File exists and fail flag is on.
                    result.setResult(false);
                    log.logError(toString(), "File [" + realFilename + "] exists, failing.");
                } else {
                    // File already exists, no reason to try to create it
                    result.setResult(true);
                    log.logBasic(toString(), "File [" + realFilename + "] already exists, not recreating.");
                }
            } else {
                //  No file yet, create an empty file.
                fileObject.createFile();
                log.logBasic(toString(), "File [" + realFilename + "] created!");
                result.setResult(true);
            }
        } catch (IOException e) {
            log.logError(toString(),
                    "Could not create file [" + realFilename + "], exception: " + e.getMessage());
            result.setResult(false);
            result.setNrErrors(1);
        } finally {
            if (fileObject != null) {
                try {
                    fileObject.close();
                } catch (IOException ex) {
                }
                ;
            }
        }
    } else {
        log.logError(toString(), "No filename is defined.");
    }

    return result;
}

From source file:com.thinkberg.webdav.PutHandler.java

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileObject object = VFSBackend.resolveFile(request.getPathInfo());

    try {//from  w w  w .ja v  a  2 s . com
        if (!LockManager.getInstance().evaluateCondition(object, getIf(request)).result) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
    } catch (LockException e) {
        response.sendError(SC_LOCKED);
        return;
    } catch (ParseException e) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }
    // it is forbidden to write data on a folder
    if (object.exists() && FileType.FOLDER.equals(object.getType())) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    FileObject parent = object.getParent();
    if (!parent.exists()) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    if (!FileType.FOLDER.equals(parent.getType())) {
        response.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    }

    InputStream is = request.getInputStream();
    OutputStream os = object.getContent().getOutputStream();
    long bytesCopied = Util.copyStream(is, os);
    String contentLengthHeader = request.getHeader("Content-length");
    LOG.debug(String.format("sent %d/%s bytes", bytesCopied,
            contentLengthHeader == null ? "unknown" : contentLengthHeader));
    os.flush();
    object.close();

    response.setStatus(HttpServletResponse.SC_CREATED);
}

From source file:be.ibridge.kettle.job.entry.filecompare.JobEntryFileCompare.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  ww w .ja va  2s .c  o m

    String realFilename1 = getRealFilename1();
    String realFilename2 = getRealFilename2();

    FileObject file1 = null;
    FileObject file2 = null;
    try {
        if (filename1 != null && filename2 != null) {
            file1 = KettleVFS.getFileObject(realFilename1);
            file2 = KettleVFS.getFileObject(realFilename2);

            if (file1.exists() && file2.exists()) {
                if (equalFileContents(file1, file2)) {
                    result.setResult(true);
                } else {
                    result.setResult(false);
                }
            } else {
                if (!file1.exists())
                    log.logError(toString(), "File 1 [" + realFilename1 + "] does not exist.");
                if (!file2.exists())
                    log.logError(toString(), "File 2 [" + realFilename2 + "] does not exist.");
                result.setResult(false);
                result.setNrErrors(1);
            }
        } else {
            log.logError(toString(), "Need 2 filenames to compare file contents.");
        }
    } catch (Exception e) {
        result.setResult(false);
        result.setNrErrors(1);
        log.logError(toString(), "Error occurred while comparing file [" + realFilename2 + "] and file ["
                + realFilename2 + "]: " + e.getMessage());
    } finally {
        try {
            if (file1 != null)
                file1.close();

            if (file2 != null)
                file2.close();
        } catch (IOException e) {
        }
    }

    return result;
}

From source file:be.ibridge.kettle.job.entry.deletefile.JobEntryDeleteFile.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  . jav  a  2  s  . c om*/

    if (filename != null) {
        String realFilename = getRealFilename();

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

            if (!fileObject.exists()) {
                if (isFailIfFileNotExists()) {
                    // File doesn't exist and fail flag is on.
                    result.setResult(false);
                    log.logError(toString(), "File [" + realFilename + "] doesn't exist, failing.");
                } else {
                    // File already deleted, no reason to try to delete it
                    result.setResult(true);
                    log.logBasic(toString(), "File [" + realFilename + "] already deleted.");
                }
            } else {
                boolean deleted = fileObject.delete();
                if (!deleted) {
                    log.logError(toString(), "Could not delete file [" + realFilename + "].");
                    result.setResult(false);
                    result.setNrErrors(1);
                }
                log.logBasic(toString(), "File [" + realFilename + "] deleted!");
                result.setResult(true);
            }
        } catch (IOException e) {
            log.logError(toString(),
                    "Could not delete file [" + realFilename + "], exception: " + e.getMessage());
            result.setResult(false);
            result.setNrErrors(1);
        } finally {
            if (fileObject != null) {
                try {
                    fileObject.close();
                } catch (IOException ex) {
                }
                ;
            }
        }
    } else {
        log.logError(toString(), "No filename is defined.");
    }

    return result;
}

From source file:com.panet.imeta.job.entries.ssh2put.JobEntrySSH2PUT.java

private boolean deleteOrMoveFiles(FileObject file, String destinationFolder) throws KettleException {
    try {/*from   w w  w . ja  v a2s . c o m*/
        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.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;/*from  ww w.  j a v a2  s. c  o  m*/
    File fileZip = null;
    boolean resultat = false;
    boolean renameOk = false;
    boolean orginexist = false;

    // Check if target file/folder exists!
    FileObject OriginFile = null;
    ZipInputStream zin = null;
    byte[] buffer = null;
    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.copymoveresultfilenames.JobEntryCopyMoveResultFilenames.java

private boolean CreateDestinationFolder(String foldername, LogWriter log) {
    FileObject folder = null;
    try {/*from  w w w.  j a v a 2s.  c  o  m*/
        folder = KettleVFS.getFileObject(foldername);

        if (!folder.exists()) {
            log.logError(toString(),
                    Messages.getString("JobEntryCopyMoveResultFilenames.Log.FolderNotExists", foldername));
            if (isCreateDestinationFolder())
                folder.createFolder();
            else
                return false;
            if (log.isBasic())
                log.logBasic(toString(),
                        Messages.getString("JobEntryCopyMoveResultFilenames.Log.FolderCreated", foldername));
        } else {
            if (log.isDetailed())
                log.logDetailed(toString(),
                        Messages.getString("JobEntryCopyMoveResultFilenames.Log.FolderExists", foldername));
        }
        return true;
    } catch (Exception e) {
        log.logError(toString(), Messages.getString("JobEntryCopyMoveResultFilenames.Log.CanNotCreatedFolder",
                foldername, e.toString()));

    } finally {
        if (folder != null) {
            try {
                folder.close();
            } catch (Exception ex) {
            }
            ;
        }
    }
    return false;
}