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

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

Introduction

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

Prototype

public boolean exists() throws FileSystemException;

Source Link

Document

Determines if this file exists.

Usage

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  va2  s  .  c  o m
    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: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);/*  www . j  av a 2s .c  o  m*/

    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.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 {//w  w w . j av a  2 s .  c  om
            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.thinkberg.moxo.dav.PropPatchHandler.java

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

    try {//from w  w w .  jav a  2s .  com
        LockManager.getInstance().checkCondition(object, getIf(request));
    } catch (LockException e) {
        if (e.getLocks() != null) {
            response.sendError(SC_LOCKED);
        } else {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        }
        return;
    }

    SAXReader saxReader = new SAXReader();
    try {
        Document propDoc = saxReader.read(request.getInputStream());
        //      log(propDoc);

        response.setContentType("text/xml");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(SC_MULTI_STATUS);

        if (object.exists()) {
            Document resultDoc = DocumentHelper.createDocument();
            Element multiStatusResponse = resultDoc.addElement("multistatus", "DAV:");
            Element responseEl = multiStatusResponse.addElement("response");
            try {
                URL url = new URL(getBaseUrl(request), URLEncoder.encode(object.getName().getPath(), "UTF-8"));
                log("!! " + url);
                responseEl.addElement("href").addText(url.toExternalForm());
            } catch (Exception e) {
                e.printStackTrace();
            }

            Element propstatEl = responseEl.addElement("propstat");
            Element propEl = propstatEl.addElement("prop");

            Element propertyUpdateEl = propDoc.getRootElement();
            for (Object elObject : propertyUpdateEl.elements()) {
                Element el = (Element) elObject;
                if ("set".equals(el.getName())) {
                    for (Object propObject : el.elements()) {
                        setProperty(propEl, object, (Element) propObject);
                    }
                } else if ("remove".equals(el.getName())) {
                    for (Object propObject : el.elements()) {
                        removeProperty(propEl, object, (Element) propObject);
                    }
                }
            }
            propstatEl.addElement("status").addText(DavResource.STATUS_403);

            //        log(resultDoc);

            // write the actual response
            XMLWriter writer = new XMLWriter(response.getWriter(), OutputFormat.createCompactFormat());
            writer.write(resultDoc);
            writer.flush();
            writer.close();
        } else {
            log("!! " + object.getName().getPath() + " NOT FOUND");
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (DocumentException e) {
        log("!! inavlid request: " + e.getMessage());
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
}

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

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

    try {//from  www  . ja va2 s  . c  om
        String fragment = new URI(request.getRequestURI()).getFragment();
        if (fragment != null) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
    } catch (URISyntaxException e) {
        throw new IOException(e.getMessage());
    }

    try {
        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;
    }

    if (object.exists()) {
        int deletedObjects = object.delete(ALL_FILES_SELECTOR);
        LOG.debug("deleted " + deletedObjects + " objects");
        if (deletedObjects > 0) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        }
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:com.panet.imeta.job.entries.sftp.JobEntrySFTP.java

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

    Result result = previousResult;
    List<RowMetaAndData> rows = result.getRows();
    RowMetaAndData resultRow = null;//from  w w w .j a v a2s.c  om

    result.setResult(false);
    long filesRetrieved = 0;

    if (log.isDetailed())
        log.logDetailed(toString(), Messages.getString("JobSFTP.Log.StartJobEntry"));
    HashSet<String> list_previous_filenames = new HashSet<String>();

    if (copyprevious) {
        if (rows.size() == 0) {
            if (log.isDetailed())
                log.logDetailed(toString(), Messages.getString("JobSFTP.ArgsFromPreviousNothing"));
            result.setResult(true);
            return result;
        }
        try {

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

                // Get file names
                String file_previous = resultRow.getString(0, null);
                if (!Const.isEmpty(file_previous)) {
                    list_previous_filenames.add(file_previous);
                    if (log.isDebug())
                        log.logDebug(toString(),
                                Messages.getString("JobSFTP.Log.FilenameFromResult", file_previous));
                }
            }
        } catch (Exception e) {
            log.logError(toString(), Messages.getString("JobSFTP.Error.ArgFromPrevious"));
            result.setNrErrors(1);
            return result;
        }
    }

    SFTPClient sftpclient = null;

    // String substitution..
    String realServerName = environmentSubstitute(serverName);
    String realServerPort = environmentSubstitute(serverPort);
    String realUsername = environmentSubstitute(userName);
    String realPassword = environmentSubstitute(password);
    String realSftpDirString = environmentSubstitute(sftpDirectory);
    String realWildcard = environmentSubstitute(wildcard);
    String realTargetDirectory = environmentSubstitute(targetDirectory);

    FileObject TargetFolder = null;

    try {
        // Let's perform some checks before starting
        if (!Const.isEmpty(realTargetDirectory)) {
            TargetFolder = KettleVFS.getFileObject(realTargetDirectory);
            boolean TargetFolderExists = TargetFolder.exists();
            if (TargetFolderExists) {
                if (log.isDetailed())
                    log.logDetailed(toString(),
                            Messages.getString("JobSFTP.Log.TargetFolderExists", realTargetDirectory));
            } else {
                log.logError(toString(),
                        Messages.getString("JobSFTP.Error.TargetFolderNotExists", realTargetDirectory));
                if (!createtargetfolder) {
                    // Error..Target folder can not be found !
                    result.setNrErrors(1);
                    return result;
                } else {
                    // create target folder
                    TargetFolder.createFolder();
                    if (log.isDetailed())
                        log.logDetailed(toString(),
                                Messages.getString("JobSFTP.Log.TargetFolderCreated", realTargetDirectory));
                }
            }
        }

        if (TargetFolder != null) {
            TargetFolder.close();
            TargetFolder = null;
        }

        // Create sftp client to host ...
        sftpclient = new SFTPClient(InetAddress.getByName(realServerName), Const.toInt(realServerPort, 22),
                realUsername);
        if (log.isDetailed())
            log.logDetailed(toString(), Messages.getString("JobSFTP.Log.OpenedConnection", realServerName,
                    realServerPort, realUsername));

        // login to ftp host ...
        sftpclient.login(realPassword);
        // Passwords should not appear in log files.
        //log.logDetailed(toString(), "logged in using password "+realPassword); // Logging this seems a bad idea! Oh well.

        // move to spool dir ...
        if (!Const.isEmpty(realSftpDirString)) {
            try {
                sftpclient.chdir(realSftpDirString);
            } catch (Exception e) {
                log.logError(toString(),
                        Messages.getString("JobSFTP.Error.CanNotFindRemoteFolder", realSftpDirString));
                throw new Exception(e);
            }
            if (log.isDetailed())
                log.logDetailed(toString(),
                        Messages.getString("JobSFTP.Log.ChangedDirectory", realSftpDirString));
        }
        Pattern pattern = null;
        // Get all the files in the current directory...
        String[] filelist = sftpclient.dir();
        if (filelist == null) {
            // Nothing was found !!! exit
            result.setResult(true);
            if (log.isDetailed())
                log.logDetailed(toString(), Messages.getString("JobSFTP.Log.Found", "" + 0));
            return result;
        }
        if (log.isDetailed())
            log.logDetailed(toString(), Messages.getString("JobSFTP.Log.Found", "" + filelist.length));

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

        // Get the files in the list...
        for (int i = 0; i < filelist.length && !parentJob.isStopped(); i++) {
            boolean getIt = true;
            // First see if the file matches the regular expression!
            if (!copyprevious && pattern != null) {
                Matcher matcher = pattern.matcher(filelist[i]);
                getIt = matcher.matches();
            }

            if (getIt || list_previous_filenames.contains(filelist[i])) {
                if (log.isDebug())
                    log.logDebug(toString(),
                            Messages.getString("JobSFTP.Log.GettingFiles", filelist[i], realTargetDirectory));

                String targetFilename = realTargetDirectory + Const.FILE_SEPARATOR + filelist[i];
                sftpclient.get(targetFilename, filelist[i]);
                filesRetrieved++;

                if (isaddresult) {
                    // Add to the result files...
                    ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL,
                            KettleVFS.getFileObject(targetFilename), parentJob.getJobname(), toString());
                    result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
                    if (log.isDetailed())
                        log.logDetailed(toString(),
                                Messages.getString("JobSFTP.Log.FilenameAddedToResultFilenames", filelist[i]));
                }
                if (log.isDetailed())
                    log.logDetailed(toString(), Messages.getString("JobSFTP.Log.TransferedFile", filelist[i]));

                // Delete the file if this is needed!
                if (remove) {
                    sftpclient.delete(filelist[i]);
                    if (log.isDetailed())
                        log.logDetailed(toString(), Messages.getString("JobSFTP.Log.DeletedFile", filelist[i]));
                }
            }
        }

        result.setResult(true);
        result.setNrFilesRetrieved(filesRetrieved);
    } catch (Exception e) {
        result.setNrErrors(1);
        log.logError(toString(), Messages.getString("JobSFTP.Error.GettingFiles", e.getMessage()));
        log.logError(toString(), Const.getStackTracker(e));
    } finally {
        // close connection, if possible
        try {
            if (sftpclient != null)
                sftpclient.disconnect();
        } catch (Exception e) {
            // just ignore this, makes no big difference
        }

        try {
            if (TargetFolder != null) {
                TargetFolder.close();
                TargetFolder = null;
            }
            if (list_previous_filenames != null)
                list_previous_filenames = null;
        } catch (Exception e) {
        }

    }

    return result;
}

From source file:com.panet.imeta.job.entries.xslt.JobEntryXSLT.java

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

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

    FileObject xmlfile = null;
    FileObject xslfile = null;
    FileObject outputfile = null;

    try

    {

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

            if (xmlfile.exists() && xslfile.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
                    if (log.isDebug())
                        log.logDebug(toString(),
                                Messages.getString("JobEntryXSLT.OuputFileExists1.Label") + realoutputfilename
                                        + Messages.getString("JobEntryXSLT.OuputFileExists2.Label"));
                    result.setResult(true);
                } else {
                    if (outputfile.exists() && iffileexists == 0) {
                        // the output file exists and user want to create new one with unique name
                        //Format Date

                        // 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) + "_"
                                    + StringUtil.getFormattedDateTimeNow(true) + wildcard;
                        } else {
                            // did not find wildcard
                            realoutputfilename = realoutputfilename + "_"
                                    + StringUtil.getFormattedDateTimeNow(true);
                        }
                        if (log.isDebug())
                            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"));
                    }

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

                    if (xsltfactory.equals(FACTORY_SAXON)) {
                        // Set the TransformerFactory to the SAXON implementation.
                        factory = new net.sf.saxon.TransformerFactoryImpl();
                    }

                    if (log.isDetailed())
                        log.logDetailed(Messages.getString("JobEntryXSL.Log.TransformerFactoryInfos"), Messages
                                .getString("JobEntryXSL.Log.TransformerFactory", factory.getClass().getName()));

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

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

                    if (log.isDetailed())
                        log.logDetailed(Messages.getString("JobEntryXSL.Log.TransformerClassInfos"), Messages
                                .getString("JobEntryXSL.Log.TransformerClass", xformer.getClass().getName()));

                    // Prepare the input and output files
                    Source source = new StreamSource(KettleVFS.getInputStream(xmlfile));
                    StreamResult resultat = new StreamResult(KettleVFS.getOutputStream(outputfile, false));

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

                    if (isAddFileToResult()) {
                        // Add output filename to output files
                        ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL,
                                KettleVFS.getFileObject(realoutputfilename), parentJob.getJobname(),
                                toString());
                        result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
                    }

                    // 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 (!xslfile.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 (xslfile != null)
                xslfile.close();
            if (outputfile != null)
                outputfile.close();

            // 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();
        } catch (IOException e) {
        }
    }

    return result;
}

From source file:com.panet.imeta.job.entries.deletefolders.JobEntryDeleteFolders.java

private boolean deleteFolder(String foldername) {
    LogWriter log = LogWriter.getInstance();

    boolean rcode = false;
    FileObject filefolder = null;

    try {//from w  w w . j ava2 s.  c  o m
        filefolder = KettleVFS.getFileObject(foldername);

        // 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("JobEntryDeleteFolders.ProcessingFolder", foldername)); //$NON-NLS-1$
                // Delete Files
                int Nr = filefolder.delete(new TextFileSelector());

                if (log.isDetailed())
                    log.logDetailed(toString(), Messages.getString("JobEntryDeleteFolders.TotalDeleted", //$NON-NLS-1$
                            foldername, String.valueOf(Nr)));
                rcode = true;
            } else {
                // Error...This file is not a folder!
                log.logError(toString(), Messages.getString("JobEntryDeleteFolders.Error.NotFolder"));
            }
        } else {
            // File already deleted, no reason to try to delete it
            if (log.isBasic())
                log.logBasic(toString(),
                        Messages.getString("JobEntryDeleteFolders.FolderAlreadyDeleted", foldername)); //$NON-NLS-1$
            rcode = true;
        }
    } catch (IOException e) {
        log.logError(toString(),
                Messages.getString("JobEntryDeleteFolders.CouldNotDelete", foldername, e.getMessage())); //$NON-NLS-1$
    } finally {
        if (filefolder != null) {
            try {
                filefolder.close();
            } catch (IOException ex) {
            }
            ;
        }
    }

    return rcode;
}

From source file:com.huawei.unibi.molap.csvreaderstep.CsvInputMeta.java

/**
 * Since the exported transformation that runs this will reside in a ZIP file, we can't reference files relatively.
 * So what this does is turn the name of files into absolute paths OR it simply includes the resource in the ZIP file.
 * For now, we'll simply turn it into an absolute path and pray that the file is on a shared drive or something like that.
        /*  w ww.j a  v a2 s  .  c om*/
 * HANDLER: create options to configure this behavior 
 */
public String exportResources(VariableSpace space, Map<String, ResourceDefinition> definitions,
        ResourceNamingInterface resourceNamingInterface, Repository repository) throws KettleException {
    try {
        // The object that we're modifying here is a copy of the original!
        // So let's change the filename from relative to absolute by grabbing the file object...
        // In case the name of the file comes from previous steps, forget about this!
        //
        if (Const.isEmpty(filenameField)) {
            // From : ${Internal.Transformation.Filename.Directory}/../foo/bar.csv
            // To   : /home/matt/test/files/foo/bar.csv
            //
            FileObject fileObject = KettleVFS.getFileObject(space.environmentSubstitute(filename), space);

            // If the file doesn't exist, forget about this effort too!
            //
            if (fileObject.exists()) {
                // Convert to an absolute path...
                // 
                filename = resourceNamingInterface.nameResource(fileObject, space, true);

                return filename;
            }
        }
        return null;
    } catch (Exception e) {
        throw new KettleException(e); //$NON-NLS-1$
    }
}

From source file:com.thinkberg.moxo.dav.CopyMoveBase.java

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    boolean overwrite = getOverwrite(request);
    FileObject object = getResourceManager().getFileObject(request.getPathInfo());
    FileObject targetObject = getDestination(request);

    try {//from  www. j a v a2 s . c o  m
        // check that we can write the target
        LockManager.getInstance().checkCondition(targetObject, getIf(request));
        // if we move, check that we can actually write on the source
        if ("MOVE".equals(request.getMethod())) {
            LockManager.getInstance().checkCondition(object, getIf(request));
        }
    } catch (LockException e) {
        if (e.getLocks() != null) {
            response.sendError(SC_LOCKED);
        } else {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        }
        return;
    }

    if (null == targetObject) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    if (object.equals(targetObject)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    if (targetObject.exists()) {
        if (!overwrite) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else {
        FileObject targetParent = targetObject.getParent();
        if (!targetParent.exists() || !FileType.FOLDER.equals(targetParent.getType())) {
            response.sendError(HttpServletResponse.SC_CONFLICT);
        }
        response.setStatus(HttpServletResponse.SC_CREATED);
    }

    copyOrMove(object, targetObject, getDepth(request));
}