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.job.entries.copymoveresultfilenames.JobEntryCopyMoveResultFilenames.java

public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = previousResult;
    result.setNrErrors(1);//  w w w .jav  a2 s  .c  om
    result.setResult(false);
    String realdestinationFolder = environmentSubstitute(getDestinationFolder());

    if (!CreateDestinationFolder(realdestinationFolder, log)) {
        return result;
    }

    if (previousResult != null) {
        NrErrors = 0;
        limitFiles = Const.toInt(environmentSubstitute(getNrErrorsLessThan()), 10);
        NrErrors = 0;
        NrSuccess = 0;
        successConditionBroken = false;
        successConditionBrokenExit = false;

        FileObject file = null;

        try {
            int size = result.getResultFiles().size();
            if (log.isBasic())
                log.logBasic(toString(),
                        Messages.getString("JobEntryCopyMoveResultFilenames.log.FilesFound", "" + size));

            List<ResultFile> resultFiles = result.getResultFilesList();
            if (resultFiles != null && resultFiles.size() > 0) {
                for (Iterator<ResultFile> it = resultFiles.iterator(); it.hasNext()
                        && !parentJob.isStopped();) {
                    if (successConditionBroken) {
                        log.logError(toString(), Messages.getString(
                                "JobEntryCopyMoveResultFilenames.Error.SuccessConditionbroken", "" + NrErrors));
                        throw new Exception(Messages.getString(
                                "JobEntryCopyMoveResultFilenames.Error.SuccessConditionbroken", "" + NrErrors));
                    }

                    ResultFile resultFile = (ResultFile) it.next();
                    file = resultFile.getFile();
                    if (file != null && file.exists()) {
                        if (!specifywildcard || (CheckFileWildcard(file.getName().getBaseName(),
                                environmentSubstitute(wildcard), true)
                                && !CheckFileWildcard(file.getName().getBaseName(),
                                        environmentSubstitute(wildcardexclude), false)
                                && specifywildcard)) {
                            // Copy or Move file
                            if (!ProcessFile(file, realdestinationFolder, log, result, parentJob)) {
                                // Update Errors
                                updateErrors();
                            }
                        }

                    } else {
                        log.logError(toString(), Messages.getString(
                                "JobEntryCopyMoveResultFilenames.log.ErrorCanNotFindFile", file.toString()));
                        // Update Errors
                        updateErrors();
                    }
                } // end for
            }
        } catch (Exception e) {
            log.logError(toString(), Messages.getString("JobEntryCopyMoveResultFilenames.Error", e.toString()));
        } finally {
            if (file != null) {
                try {
                    file.close();
                } catch (Exception ex) {
                }
                ;
            }
        }
    }
    // Success Condition
    result.setNrErrors(NrErrors);
    result.setNrLinesWritten(NrSuccess);
    if (getSuccessStatus())
        result.setResult(true);

    return result;
}

From source file:com.panet.imeta.job.entries.xsdvalidator.JobEntryXSDValidator.java

public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = previousResult;
    result.setResult(false);/* ww w .  j av a  2s .co m*/

    String realxmlfilename = getRealxmlfilename();
    String realxsdfilename = getRealxsdfilename();

    FileObject xmlfile = null;
    FileObject xsdfile = null;

    try

    {

        if (xmlfilename != null && xsdfilename != null) {
            xmlfile = KettleVFS.getFileObject(realxmlfilename);
            xsdfile = KettleVFS.getFileObject(realxsdfilename);

            if (xmlfile.exists() && xsdfile.exists()) {

                SchemaFactory factorytXSDValidator_1 = SchemaFactory
                        .newInstance("http://www.w3.org/2001/XMLSchema");

                // Get XSD File
                File XSDFile = new File(KettleVFS.getFilename(xsdfile));
                Schema SchematXSD = factorytXSDValidator_1.newSchema(XSDFile);

                Validator XSDValidator = SchematXSD.newValidator();

                // Get XML File
                File xmlfiletXSDValidator_1 = new File(KettleVFS.getFilename(xmlfile));

                Source sourcetXSDValidator_1 = new StreamSource(xmlfiletXSDValidator_1);

                XSDValidator.validate(sourcetXSDValidator_1);

                // Everything is OK
                result.setResult(true);

            } else {

                if (!xmlfile.exists()) {
                    log.logError(toString(),
                            Messages.getString("JobEntryXSDValidator.FileDoesNotExist1.Label") + realxmlfilename
                                    + Messages.getString("JobEntryXSDValidator.FileDoesNotExist2.Label"));
                }
                if (!xsdfile.exists()) {
                    log.logError(toString(),
                            Messages.getString("JobEntryXSDValidator.FileDoesNotExist1.Label") + realxsdfilename
                                    + Messages.getString("JobEntryXSDValidator.FileDoesNotExist2.Label"));
                }
                result.setResult(false);
                result.setNrErrors(1);
            }

        } else {
            log.logError(toString(), Messages.getString("JobEntryXSDValidator.AllFilesNotNull.Label"));
            result.setResult(false);
            result.setNrErrors(1);
        }

    }

    catch (SAXException ex) {
        log.logError(toString(), "Error :" + ex.getMessage());
    } catch (Exception e) {

        log.logError(toString(),
                Messages.getString("JobEntryXSDValidator.ErrorXSDValidator.Label")
                        + Messages.getString("JobEntryXSDValidator.ErrorXML1.Label") + realxmlfilename
                        + Messages.getString("JobEntryXSDValidator.ErrorXML2.Label")
                        + Messages.getString("JobEntryXSDValidator.ErrorXSD1.Label") + realxsdfilename
                        + Messages.getString("JobEntryXSDValidator.ErrorXSD2.Label") + e.getMessage());
        result.setResult(false);
        result.setNrErrors(1);
    } finally {
        try {
            if (xmlfile != null)
                xmlfile.close();

            if (xsdfile != null)
                xsdfile.close();

        } catch (IOException e) {
        }
    }

    return result;
}

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

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

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

    try {/* w  w  w  .j  a v a2 s.c om*/
        filefolder = KettleVFS.getFileObject(realFilefoldername);

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

        System.gc();

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

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

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

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

    return rcode;
}

From source file:com.panet.imeta.job.entries.sql.JobEntrySQL.java

public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();

    Result result = previousResult;

    if (connection != null) {
        Database db = new Database(connection);
        FileObject SQLfile = null;
        db.shareVariablesWith(this);
        try {//from  ww w. j  a  va 2s. co m
            db.connect();
            if (sqlfromfile) {
                if (sqlfilename == null)
                    throw new KettleDatabaseException(Messages.getString("JobSQL.NoSQLFileSpecified"));

                try {
                    String realfilename = environmentSubstitute(sqlfilename);
                    SQLfile = KettleVFS.getFileObject(realfilename);
                    if (!SQLfile.exists()) {
                        log.logError(toString(), Messages.getString("JobSQL.SQLFileNotExist", realfilename));
                        throw new KettleDatabaseException(
                                Messages.getString("JobSQL.SQLFileNotExist", realfilename));
                    }
                    if (log.isDetailed())
                        log.logDetailed(toString(), Messages.getString("JobSQL.SQLFileExists", realfilename));

                    InputStream IS = KettleVFS.getInputStream(SQLfile);
                    InputStreamReader BIS = new InputStreamReader(new BufferedInputStream(IS, 500));

                    StringBuffer lineStringBuffer = new StringBuffer(256);
                    lineStringBuffer.setLength(0);

                    BufferedReader buff = new BufferedReader(BIS);
                    String sLine = null;
                    String SFullLine = Const.CR;
                    ;

                    while ((sLine = buff.readLine()) != null) {
                        if (Const.isEmpty(sLine)) {
                            SFullLine = SFullLine + Const.CR;
                        } else {
                            SFullLine = SFullLine + Const.CR + sLine;
                        }
                    }

                    if (!Const.isEmpty(SFullLine)) {
                        if (log.isDetailed())
                            log.logDetailed(toString(),
                                    Messages.getString("JobSQL.Log.SQlStatement", SFullLine));
                        db.execStatement(SFullLine);
                    }
                } catch (Exception e) {
                    throw new KettleDatabaseException(Messages.getString("JobSQL.ErrorRunningSQLfromFile"), e);
                }

            } else {
                String mySQL = null;
                if (useVariableSubstitution)
                    mySQL = environmentSubstitute(sql);
                else
                    mySQL = sql;
                db.execStatements(mySQL);
            }
        } catch (KettleDatabaseException je) {
            result.setNrErrors(1);
            log.logError(toString(), Messages.getString("JobSQL.ErrorRunJobEntry", je.getMessage()));
        } finally {
            db.disconnect();
            if (SQLfile != null) {
                try {
                    SQLfile.close();
                } catch (Exception e) {
                }
            }
        }
    } else {
        result.setNrErrors(1);
        log.logError(toString(), Messages.getString("JobSQL.NoDatabaseConnection"));
    }

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

    return result;
}

From source file:com.panet.imeta.job.entries.deletefiles.JobEntryDeleteFiles.java

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

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

    try {//from w  w  w .  j  a v a2  s. c  o  m
        filefolder = KettleVFS.getFileObject(realFilefoldername);

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

        System.gc();

        if (filefolder.exists()) {
            // the file or folder exists
            if (filefolder.getType() == FileType.FOLDER) {
                // It's a folder
                if (log.isDetailed())
                    log.logDetailed(toString(),
                            Messages.getString("JobEntryDeleteFiles.ProcessingFolder", realFilefoldername)); //$NON-NLS-1$
                // Delete Files

                int Nr = filefolder
                        .delete(new TextFileSelector(filefolder.toString(), realwildcard, parentJob));

                if (log.isDetailed())
                    log.logDetailed(toString(),
                            Messages.getString("JobEntryDeleteFiles.TotalDeleted", String.valueOf(Nr))); //$NON-NLS-1$
                rcode = true;
            } else {
                // It's a file
                if (log.isDetailed())
                    log.logDetailed(toString(),
                            Messages.getString("JobEntryDeleteFiles.ProcessingFile", realFilefoldername)); //$NON-NLS-1$
                boolean deleted = filefolder.delete();
                if (!deleted) {
                    log.logError(toString(),
                            Messages.getString("JobEntryDeleteFiles.CouldNotDeleteFile", realFilefoldername)); //$NON-NLS-1$
                } else {
                    if (log.isBasic())
                        log.logBasic(toString(),
                                Messages.getString("JobEntryDeleteFiles.FileDeleted", filename)); //$NON-NLS-1$
                    rcode = true;
                }
            }
        } else {
            // File already deleted, no reason to try to delete it
            if (log.isBasic())
                log.logBasic(toString(),
                        Messages.getString("JobEntryDeleteFiles.FileAlreadyDeleted", realFilefoldername)); //$NON-NLS-1$
            rcode = true;
        }
    } catch (IOException e) {
        log.logError(toString(),
                Messages.getString("JobEntryDeleteFiles.CouldNotProcess", realFilefoldername, e.getMessage())); //$NON-NLS-1$
    } finally {
        if (filefolder != null) {
            try {
                filefolder.close();
            } catch (IOException ex) {
            }
            ;
        }
    }

    return rcode;
}

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

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

    try {// ww w. j av  a  2 s. c o m
        if (fileObject.getType().equals(FileType.FILE)) {
            // We have to unzip one zip file
            if (!unzipFile(log, fileObject, realTargetdirectory, realWildcard, realWildcardExclude, result,
                    parentJob, fileObject, movetodir, realMovetodirectory))
                updateErrors();
            else
                updateSuccess();
        } else {
            // Folder..let's see wildcard
            FileObject[] children = fileObject.getChildren();

            for (int i = 0; i < children.length && !parentJob.isStopped(); i++) {
                if (successConditionBroken) {
                    if (!successConditionBrokenExit) {
                        log.logError(toString(),
                                Messages.getString("JobUnZip.Error.SuccessConditionbroken", "" + NrErrors));
                        successConditionBrokenExit = true;
                    }
                    return false;
                }
                // Get only file!
                if (!children[i].getType().equals(FileType.FOLDER)) {
                    boolean unzip = true;

                    String filename = children[i].getName().getPath();

                    Pattern patternSource = null;

                    if (!Const.isEmpty(realWildcardSource))
                        patternSource = Pattern.compile(realWildcardSource);

                    // First see if the file matches the regular expression!
                    if (patternSource != null) {
                        Matcher matcher = patternSource.matcher(filename);
                        unzip = matcher.matches();
                    }
                    if (unzip) {
                        if (!unzipFile(log, children[i], realTargetdirectory, realWildcard, realWildcardExclude,
                                result, parentJob, fileObject, movetodir, realMovetodirectory))
                            updateErrors();
                        else
                            updateSuccess();
                    }
                }
            }
        }
    } catch (Exception e) {
        updateErrors();
        log.logError(toString(), Messages.getString("JobUnZip.Error.Label", e.getMessage()));
    } finally {
        if (fileObject != null) {
            try {
                fileObject.close();
            } catch (IOException ex) {
            }
            ;
        }
    }
    return retval;
}

From source file:mondrian.olap.Util.java

/**
 * Gets content via Apache VFS. File must exist and have content
 *
 * @param url String//from  w  w w. ja v  a  2 s. co  m
 * @return Apache VFS FileContent for further processing
 * @throws FileSystemException on error
 */
public static InputStream readVirtualFile(String url) throws FileSystemException {
    // Treat catalogUrl as an Apache VFS (Virtual File System) URL.
    // VFS handles all of the usual protocols (http:, file:)
    // and then some.
    FileSystemManager fsManager = VFS.getManager();
    if (fsManager == null) {
        throw newError("Cannot get virtual file system manager");
    }

    // Workaround VFS bug.
    if (url.startsWith("file://localhost")) {
        url = url.substring("file://localhost".length());
    }
    if (url.startsWith("file:")) {
        url = url.substring("file:".length());
    }

    // work around for VFS bug not closing http sockets
    // (Mondrian-585)
    if (url.startsWith("http")) {
        try {
            return new URL(url).openStream();
        } catch (IOException e) {
            throw newError("Could not read URL: " + url);
        }
    }

    File userDir = new File("").getAbsoluteFile();
    FileObject file = fsManager.resolveFile(userDir, url);
    FileContent fileContent = null;
    try {
        // Because of VFS caching, make sure we refresh to get the latest
        // file content. This refresh may possibly solve the following
        // workaround for defect MONDRIAN-508, but cannot be tested, so we
        // will leave the work around for now.
        file.refresh();

        // Workaround to defect MONDRIAN-508. For HttpFileObjects, verifies
        // the URL of the file retrieved matches the URL passed in.  A VFS
        // cache bug can cause it to treat URLs with different parameters
        // as the same file (e.g. http://blah.com?param=A,
        // http://blah.com?param=B)
        if (file instanceof HttpFileObject && !file.getName().getURI().equals(url)) {
            fsManager.getFilesCache().removeFile(file.getFileSystem(), file.getName());

            file = fsManager.resolveFile(userDir, url);
        }

        if (!file.isReadable()) {
            throw newError("Virtual file is not readable: " + url);
        }

        fileContent = file.getContent();
    } finally {
        file.close();
    }

    if (fileContent == null) {
        throw newError("Cannot get virtual file content: " + url);
    }

    return fileContent.getInputStream();
}

From source file:com.panet.imeta.job.entries.movefiles.JobEntryMoveFiles.java

private boolean MoveOneFile(FileObject Currentfile, FileObject sourcefilefolder,
        String realDestinationFilefoldername, String realWildcard, LogWriter log, Job parentJob, Result result,
        FileObject movetofolderfolder) {
    boolean entrystatus = false;
    FileObject file_name = null;

    try {//  ww w .j  a v a2 s  . com
        if (!Currentfile.toString().equals(sourcefilefolder.toString())) {
            // Pass over the Base folder itself

            // return destination short filename
            String sourceshortfilename = Currentfile.getName().getBaseName();
            String shortfilename = sourceshortfilename;
            try {
                shortfilename = getDestinationFilename(sourceshortfilename);
            } catch (Exception e) {
                log.logError(toString(),
                        Messages.getString(Messages.getString("JobMoveFiles.Error.GettingFilename",
                                Currentfile.getName().getBaseName(), e.toString())));
                return entrystatus;
            }

            int lenCurrent = sourceshortfilename.length();
            String short_filename_from_basefolder = shortfilename;
            if (!isDoNotKeepFolderStructure())
                short_filename_from_basefolder = Currentfile.toString()
                        .substring(sourcefilefolder.toString().length(), Currentfile.toString().length());
            short_filename_from_basefolder = short_filename_from_basefolder.substring(0,
                    short_filename_from_basefolder.length() - lenCurrent) + shortfilename;

            // Built destination filename
            file_name = KettleVFS.getFileObject(
                    realDestinationFilefoldername + Const.FILE_SEPARATOR + short_filename_from_basefolder);

            if (!Currentfile.getParent().toString().equals(sourcefilefolder.toString())) {

                // Not in the Base Folder..Only if include sub folders
                if (include_subfolders) {
                    // Folders..only if include subfolders
                    if (Currentfile.getType() == FileType.FOLDER) {
                        if (include_subfolders && move_empty_folders && Const.isEmpty(wildcard)) {
                            entrystatus = MoveFile(shortfilename, Currentfile, file_name, movetofolderfolder,
                                    log, parentJob, result);
                        }
                    } else {

                        if (GetFileWildcard(sourceshortfilename, realWildcard)) {
                            entrystatus = MoveFile(shortfilename, Currentfile, file_name, movetofolderfolder,
                                    log, parentJob, result);
                        }
                    }
                }
            } else {
                // In the Base Folder...
                // Folders..only if include subfolders
                if (Currentfile.getType() == FileType.FOLDER) {
                    if (include_subfolders && move_empty_folders && Const.isEmpty(wildcard)) {
                        entrystatus = MoveFile(shortfilename, Currentfile, file_name, movetofolderfolder, log,
                                parentJob, result);
                    }
                } else {

                    // file...Check if exists
                    if (GetFileWildcard(sourceshortfilename, realWildcard)) {
                        entrystatus = MoveFile(shortfilename, Currentfile, file_name, movetofolderfolder, log,
                                parentJob, result);

                    }
                }

            }

        }
        entrystatus = true;

    } catch (Exception e) {
        log.logError(toString(), Messages.getString("JobMoveFiles.Log.Error", e.toString()));
    } finally {
        if (file_name != null) {
            try {
                file_name.close();

            } catch (IOException ex) {
            }
            ;
        }

    }
    return entrystatus;
}

From source file:be.ibridge.kettle.job.entry.xslt.JobEntryXSLT.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  va2s.  c  om

    String realxmlfilename = getRealxmlfilename();
    String realxslfilename = getRealxslfilename();
    String realoutputfilename = getRealoutputfilename();

    FileObject xmlfile = null;
    FileObject xlsfile = null;
    FileObject outputfile = null;

    try

    {

        if (xmlfilename != null && xslfilename != null && outputfilename != null) {
            xmlfile = KettleVFS.getFileObject(realxmlfilename);
            xlsfile = KettleVFS.getFileObject(realxslfilename);
            outputfile = KettleVFS.getFileObject(realoutputfilename);

            if (xmlfile.exists() && xlsfile.exists()) {
                if (outputfile.exists() && iffileexists == 2) {
                    //Output file exists
                    // User want to fail
                    log.logError(toString(), Messages.getString("JobEntryXSLT.OuputFileExists1.Label")
                            + realoutputfilename + Messages.getString("JobEntryXSLT.OuputFileExists2.Label"));
                    result.setResult(false);
                    result.setNrErrors(1);

                }

                else if (outputfile.exists() && iffileexists == 1) {
                    // Do nothing
                    log.logDebug(toString(), Messages.getString("JobEntryXSLT.OuputFileExists1.Label")
                            + realoutputfilename + Messages.getString("JobEntryXSLT.OuputFileExists2.Label"));
                    result.setResult(true);
                } else {

                    if (outputfile.exists() && iffileexists == 0) {
                        // the zip file exists and user want to create new one with unique name
                        //Format Date

                        DateFormat dateFormat = new SimpleDateFormat("mmddyyyy_hhmmss");
                        // Try to clean filename (without wildcard)
                        String wildcard = realoutputfilename.substring(realoutputfilename.length() - 4,
                                realoutputfilename.length());
                        if (wildcard.substring(0, 1).equals(".")) {
                            // Find wildcard         
                            realoutputfilename = realoutputfilename.substring(0,
                                    realoutputfilename.length() - 4) + "_" + dateFormat.format(new Date())
                                    + wildcard;
                        } else {
                            // did not find wilcard
                            realoutputfilename = realoutputfilename + "_" + dateFormat.format(new Date());
                        }
                        log.logDebug(toString(),
                                Messages.getString("JobEntryXSLT.OuputFileExists1.Label") + realoutputfilename
                                        + Messages.getString("JobEntryXSLT.OuputFileExists2.Label"));
                        log.logDebug(toString(),
                                Messages.getString("JobEntryXSLT.OuputFileNameChange1.Label")
                                        + realoutputfilename
                                        + Messages.getString("JobEntryXSLT.OuputFileNameChange2.Label"));

                    }

                    //String xmlSystemXML = new File(realxmlfilename).toURL().toExternalForm(  );
                    //String xsltSystemXSL = new File(realxslfilename).toURL().toExternalForm(  );

                    // Create transformer factory
                    TransformerFactory factory = TransformerFactory.newInstance();

                    // Use the factory to create a template containing the xsl file
                    Templates template = factory
                            .newTemplates(new StreamSource(new FileInputStream(realxslfilename)));

                    // Use the template to create a transformer
                    Transformer xformer = template.newTransformer();

                    // Prepare the input and output files
                    Source source = new StreamSource(new FileInputStream(realxmlfilename));
                    StreamResult resultat = new StreamResult(new FileOutputStream(realoutputfilename));

                    // Apply the xsl file to the source file and write the result to the output file
                    xformer.transform(source, resultat);

                    // Everything is OK
                    result.setResult(true);
                }
            } else {

                if (!xmlfile.exists()) {
                    log.logError(toString(), Messages.getString("JobEntryXSLT.FileDoesNotExist1.Label")
                            + realxmlfilename + Messages.getString("JobEntryXSLT.FileDoesNotExist2.Label"));
                }
                if (!xlsfile.exists()) {
                    log.logError(toString(), Messages.getString("JobEntryXSLT.FileDoesNotExist1.Label")
                            + realxslfilename + Messages.getString("JobEntryXSLT.FileDoesNotExist2.Label"));
                }
                result.setResult(false);
                result.setNrErrors(1);
            }

        } else {
            log.logError(toString(), Messages.getString("JobEntryXSLT.AllFilesNotNull.Label"));
            result.setResult(false);
            result.setNrErrors(1);
        }

    }

    catch (Exception e) {

        log.logError(toString(),
                Messages.getString("JobEntryXSLT.ErrorXLST.Label")
                        + Messages.getString("JobEntryXSLT.ErrorXLSTXML1.Label") + realxmlfilename
                        + Messages.getString("JobEntryXSLT.ErrorXLSTXML2.Label")
                        + Messages.getString("JobEntryXSLT.ErrorXLSTXSL1.Label") + realxslfilename
                        + Messages.getString("JobEntryXSLT.ErrorXLSTXSL2.Label") + e.getMessage());
        result.setResult(false);
        result.setNrErrors(1);
    } finally {
        try {
            if (xmlfile != null)
                xmlfile.close();

            if (xlsfile != null)
                xlsfile.close();
            if (outputfile != null)
                outputfile.close();

        } catch (IOException e) {
        }
    }

    return result;
}

From source file:com.panet.imeta.job.entries.dtdvalidator.JobEntryDTDValidator.java

public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = previousResult;
    result.setResult(false);//from  ww w.ja v a 2  s  . co  m

    String realxmlfilename = getRealxmlfilename();
    String realDTDfilename = getRealDTDfilename();

    FileObject xmlfile = null;
    FileObject DTDfile = null;

    try

    {

        if (xmlfilename != null && ((dtdfilename != null && !dtdintern) || (dtdintern))) {
            xmlfile = KettleVFS.getFileObject(realxmlfilename);

            if (xmlfile.exists())

            {

                //URL xmlFile = new URL (KettleVFS.getFilename(xmlfile));
                URL xmlFile = new File(KettleVFS.getFilename(xmlfile)).toURI().toURL();

                // open XML File
                BufferedReader xmlBufferedReader = new BufferedReader(
                        new InputStreamReader(xmlFile.openStream()));
                StringBuffer xmlStringbuffer = new StringBuffer("");

                char[] buffertXML = new char[1024];
                int LenXML = -1;
                while ((LenXML = xmlBufferedReader.read(buffertXML)) != -1)
                    xmlStringbuffer.append(buffertXML, 0, LenXML);

                // Prepare parsing ...
                DocumentBuilderFactory DocBuilderFactory = DocumentBuilderFactory.newInstance();
                Document xmlDocDTD = null;
                DocumentBuilder DocBuilder = DocBuilderFactory.newDocumentBuilder();

                // Let's try to get XML document encoding
                DocBuilderFactory.setValidating(false);
                xmlDocDTD = DocBuilder
                        .parse(new ByteArrayInputStream(xmlStringbuffer.toString().getBytes("UTF-8")));

                String encoding = null;
                if (xmlDocDTD.getXmlEncoding() == null) {
                    encoding = "UTF-8";
                } else {
                    encoding = xmlDocDTD.getXmlEncoding();
                }

                int xmlStartDTD = xmlStringbuffer.indexOf("<!DOCTYPE");

                if (dtdintern) {
                    // DTD find in the XML document
                    if (xmlStartDTD != -1) {
                        if (log.isBasic())
                            log.logBasic(toString(), Messages
                                    .getString("JobEntryDTDValidator.ERRORDTDFound.Label", realxmlfilename));
                    } else {
                        if (log.isBasic())
                            log.logBasic(toString(), Messages
                                    .getString("JobEntryDTDValidator.ERRORDTDNotFound.Label", realxmlfilename));
                    }

                } else {
                    // DTD in external document
                    // If we find an intern declaration, we remove it
                    DTDfile = KettleVFS.getFileObject(realDTDfilename);

                    if (DTDfile.exists()) {
                        if (xmlStartDTD != -1) {
                            int EndDTD = xmlStringbuffer.indexOf(">", xmlStartDTD);
                            //String DocTypeDTD = xmlStringbuffer.substring(xmlStartDTD, EndDTD + 1);
                            xmlStringbuffer.replace(xmlStartDTD, EndDTD + 1, "");

                        }

                        String xmlRootnodeDTD = xmlDocDTD.getDocumentElement().getNodeName();

                        String RefDTD = "<?xml version='" + xmlDocDTD.getXmlVersion() + "' encoding='"
                                + encoding + "'?>\n<!DOCTYPE " + xmlRootnodeDTD + " SYSTEM '"
                                + KettleVFS.getFilename(DTDfile) + "'>\n";

                        int xmloffsetDTD = xmlStringbuffer.indexOf("<" + xmlRootnodeDTD);
                        xmlStringbuffer.replace(0, xmloffsetDTD, RefDTD);
                    } else {
                        log.logError(Messages.getString("JobEntryDTDValidator.ERRORDTDFileNotExists.Subject"),
                                Messages.getString("JobEntryDTDValidator.ERRORDTDFileNotExists.Msg",
                                        realDTDfilename));
                    }
                }

                if ((dtdintern && xmlStartDTD == -1 || (!dtdintern && !DTDfile.exists()))) {
                    result.setResult(false);
                    result.setNrErrors(1);
                } else {
                    DocBuilderFactory.setValidating(true);

                    // Let's parse now ...

                    xmlDocDTD = DocBuilder
                            .parse(new ByteArrayInputStream(xmlStringbuffer.toString().getBytes(encoding)));
                    if (log.isDetailed())
                        log.logDetailed(Messages.getString("JobEntryDTDValidator.DTDValidatorOK.Subject"),
                                Messages.getString("JobEntryDTDValidator.DTDValidatorOK.Label",
                                        realxmlfilename));

                    // Everything is OK
                    result.setResult(true);
                }

            } else {

                if (!xmlfile.exists()) {
                    log.logError(toString(),
                            Messages.getString("JobEntryDTDValidator.FileDoesNotExist.Label", realxmlfilename));
                }

                result.setResult(false);
                result.setNrErrors(1);
            }

        } else {
            log.logError(toString(), Messages.getString("JobEntryDTDValidator.AllFilesNotNull.Label"));
            result.setResult(false);
            result.setNrErrors(1);
        }

    }

    catch (Exception e) {
        log.logError(Messages.getString("JobEntryDTDValidator.ErrorDTDValidator.Subject"),
                Messages.getString("JobEntryDTDValidator.ErrorDTDValidator.Label", realxmlfilename,
                        realDTDfilename, e.getMessage()));

        result.setResult(false);
        result.setNrErrors(1);
    } finally {
        try {
            if (xmlfile != null)
                xmlfile.close();

            if (DTDfile != null)
                DTDfile.close();

        } catch (IOException e) {
        }
    }

    return result;
}