List of usage examples for org.apache.commons.vfs FileObject getName
public FileName getName();
From source file:org.pentaho.di.job.entries.pgpdecryptfiles.JobEntryPGPDecryptFiles.java
private boolean CreateDestinationFolder(FileObject filefolder) { FileObject folder = null; try {/*from w w w. ja va 2 s .co m*/ if (destination_is_a_file) { folder = filefolder.getParent(); } else { folder = filefolder; } if (!folder.exists()) { if (create_destination_folder) { if (isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Log.FolderNotExist", folder.getName().toString())); } folder.createFolder(); if (isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Log.FolderWasCreated", folder.getName().toString())); } } else { logError(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Log.FolderNotExist", folder.getName().toString())); return false; } } return true; } catch (Exception e) { logError(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Log.CanNotCreateParentFolder", folder.getName().toString()), e); } finally { if (folder != null) { try { folder.close(); } catch (Exception ex) { /* Ignore */ } } } return false; }
From source file:org.pentaho.di.job.entries.pgpencryptfiles.JobEntryPGPEncryptFiles.java
private boolean ProcessFileFolder(int actionType, String sourcefilefoldername, String userID, String destinationfilefoldername, String wildcard, Job parentJob, Result result, String MoveToFolder) { boolean entrystatus = false; FileObject sourcefilefolder = null; FileObject destinationfilefolder = null; FileObject movetofolderfolder = null; FileObject Currentfile = null; // Get real source, destination file and wildcard String realSourceFilefoldername = environmentSubstitute(sourcefilefoldername); String realuserID = environmentSubstitute(userID); String realDestinationFilefoldername = environmentSubstitute(destinationfilefoldername); String realWildcard = environmentSubstitute(wildcard); try {// w ww . j a v a2 s . c o m sourcefilefolder = KettleVFS.getFileObject(realSourceFilefoldername); destinationfilefolder = KettleVFS.getFileObject(realDestinationFilefoldername); if (!Const.isEmpty(MoveToFolder)) { movetofolderfolder = KettleVFS.getFileObject(MoveToFolder); } if (sourcefilefolder.exists()) { // Check if destination folder/parent folder exists ! // If user wanted and if destination folder does not exist // PDI will create it if (CreateDestinationFolder(destinationfilefolder)) { // Basic Tests if (sourcefilefolder.getType().equals(FileType.FOLDER) && destination_is_a_file) { // Source is a folder, destination is a file // WARNING !!! CAN NOT MOVE FOLDER TO FILE !!! logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.Forbidden"), BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.CanNotMoveFolderToFile", realSourceFilefoldername, realDestinationFilefoldername)); // Update Errors updateErrors(); } else { if (destinationfilefolder.getType().equals(FileType.FOLDER) && sourcefilefolder.getType().equals(FileType.FILE)) { // Source is a file, destination is a folder // return destination short filename String shortfilename = sourcefilefolder.getName().getBaseName(); try { shortfilename = getDestinationFilename(sourcefilefolder.getName().getBaseName()); } catch (Exception e) { logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Error.GettingFilename", sourcefilefolder.getName().getBaseName(), e.toString())); return entrystatus; } // Move the file to the destination folder String destinationfilenamefull = destinationfilefolder.toString() + Const.FILE_SEPARATOR + shortfilename; FileObject destinationfile = KettleVFS.getFileObject(destinationfilenamefull); entrystatus = EncryptFile(actionType, shortfilename, sourcefilefolder, realuserID, destinationfile, movetofolderfolder, parentJob, result); } else if (sourcefilefolder.getType().equals(FileType.FILE) && destination_is_a_file) { // Source is a file, destination is a file FileObject destinationfile = KettleVFS.getFileObject(realDestinationFilefoldername); // return destination short filename String shortfilename = destinationfile.getName().getBaseName(); try { shortfilename = getDestinationFilename(destinationfile.getName().getBaseName()); } catch (Exception e) { logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Error.GettingFilename", sourcefilefolder.getName().getBaseName(), e.toString())); return entrystatus; } String destinationfilenamefull = destinationfilefolder.getParent().toString() + Const.FILE_SEPARATOR + shortfilename; destinationfile = KettleVFS.getFileObject(destinationfilenamefull); entrystatus = EncryptFile(actionType, shortfilename, sourcefilefolder, realuserID, destinationfile, movetofolderfolder, parentJob, result); } else { // Both source and destination are folders if (isDetailed()) { logDetailed(" "); logDetailed(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.FetchFolder", sourcefilefolder.toString())); } FileObject[] fileObjects = sourcefilefolder.findFiles(new AllFileSelector() { public boolean traverseDescendents(FileSelectInfo info) { return info.getDepth() == 0 || include_subfolders; } public boolean includeFile(FileSelectInfo info) { FileObject fileObject = info.getFile(); try { if (fileObject == null) { return false; } } catch (Exception ex) { // Upon error don't process the file. return false; } finally { if (fileObject != null) { try { fileObject.close(); fileObject = null; } catch (IOException ex) { /* Ignore */ } } } return true; } }); if (fileObjects != null) { for (int j = 0; j < fileObjects.length && !parentJob.isStopped(); j++) { // Success condition broken? if (successConditionBroken) { if (!successConditionBrokenExit) { logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Error.SuccessConditionbroken", "" + NrErrors)); successConditionBrokenExit = true; } return false; } // Fetch files in list one after one ... Currentfile = fileObjects[j]; if (!EncryptOneFile(actionType, Currentfile, sourcefilefolder, realuserID, realDestinationFilefoldername, realWildcard, parentJob, result, movetofolderfolder)) { // Update Errors updateErrors(); } } } } } entrystatus = true; } else { // Destination Folder or Parent folder is missing logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Error.DestinationFolderNotFound", realDestinationFilefoldername)); } } else { logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Error.SourceFileNotExists", realSourceFilefoldername)); } } catch (Exception e) { logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Error.Exception.MoveProcess", realSourceFilefoldername.toString(), destinationfilefolder.toString(), e.getMessage())); // Update Errors updateErrors(); } finally { if (sourcefilefolder != null) { try { sourcefilefolder.close(); } catch (IOException ex) { /* Ignore */ } } if (destinationfilefolder != null) { try { destinationfilefolder.close(); } catch (IOException ex) { /* Ignore */ } } if (Currentfile != null) { try { Currentfile.close(); } catch (IOException ex) { /* Ignore */ } } if (movetofolderfolder != null) { try { movetofolderfolder.close(); } catch (IOException ex) { /* Ignore */ } } } return entrystatus; }
From source file:org.pentaho.di.job.entries.pgpencryptfiles.JobEntryPGPEncryptFiles.java
private boolean EncryptFile(int actionType, String shortfilename, FileObject sourcefilename, String userID, FileObject destinationfilename, FileObject movetofolderfolder, Job parentJob, Result result) { FileObject destinationfile = null; boolean retval = false; try {/*w ww. j av a 2 s . c o m*/ if (!destinationfilename.exists()) { doJob(actionType, sourcefilename, userID, destinationfilename); if (isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.FileEncrypted", sourcefilename.getName().toString(), destinationfilename.getName().toString())); } // add filename to result filename if (add_result_filesname && !iffileexists.equals("fail") && !iffileexists.equals("do_nothing")) { addFileToResultFilenames(destinationfilename.toString(), result, parentJob); } updateSuccess(); } else { if (isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.FileExists", destinationfilename.toString())); } if (iffileexists.equals("overwrite_file")) { doJob(actionType, sourcefilename, userID, destinationfilename); if (isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.FileOverwrite", destinationfilename.getName().toString())); } // add filename to result filename if (add_result_filesname && !iffileexists.equals("fail") && !iffileexists.equals("do_nothing")) { addFileToResultFilenames(destinationfilename.toString(), result, parentJob); } updateSuccess(); } else if (iffileexists.equals("unique_name")) { String short_filename = shortfilename; // return destination short filename try { short_filename = getMoveDestinationFilename(short_filename, "ddMMyyyy_HHmmssSSS"); } catch (Exception e) { logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Error.GettingFilename", short_filename), e); return retval; } String movetofilenamefull = destinationfilename.getParent().toString() + Const.FILE_SEPARATOR + short_filename; destinationfile = KettleVFS.getFileObject(movetofilenamefull); doJob(actionType, sourcefilename, userID, destinationfilename); if (isDetailed()) { logDetailed(toString(), BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.FileEncrypted", sourcefilename.getName().toString(), destinationfile.getName().toString())); } // add filename to result filename if (add_result_filesname && !iffileexists.equals("fail") && !iffileexists.equals("do_nothing")) { addFileToResultFilenames(destinationfile.toString(), result, parentJob); } updateSuccess(); } else if (iffileexists.equals("delete_file")) { destinationfilename.delete(); if (isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.FileDeleted", destinationfilename.getName().toString())); } } else if (iffileexists.equals("move_file")) { String short_filename = shortfilename; // return destination short filename try { short_filename = getMoveDestinationFilename(short_filename, null); } catch (Exception e) { logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Error.GettingFilename", short_filename), e); return retval; } String movetofilenamefull = movetofolderfolder.toString() + Const.FILE_SEPARATOR + short_filename; destinationfile = KettleVFS.getFileObject(movetofilenamefull); if (!destinationfile.exists()) { sourcefilename.moveTo(destinationfile); if (isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.FileEncrypted", sourcefilename.getName().toString(), destinationfile.getName().toString())); } // add filename to result filename if (add_result_filesname && !iffileexists.equals("fail") && !iffileexists.equals("do_nothing")) { addFileToResultFilenames(destinationfile.toString(), result, parentJob); } } else { if (ifmovedfileexists.equals("overwrite_file")) { sourcefilename.moveTo(destinationfile); if (isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.FileOverwrite", destinationfile.getName().toString())); } // add filename to result filename if (add_result_filesname && !iffileexists.equals("fail") && !iffileexists.equals("do_nothing")) { addFileToResultFilenames(destinationfile.toString(), result, parentJob); } updateSuccess(); } else if (ifmovedfileexists.equals("unique_name")) { SimpleDateFormat daf = new SimpleDateFormat(); Date now = new Date(); daf.applyPattern("ddMMyyyy_HHmmssSSS"); String dt = daf.format(now); short_filename += "_" + dt; String destinationfilenamefull = movetofolderfolder.toString() + Const.FILE_SEPARATOR + short_filename; destinationfile = KettleVFS.getFileObject(destinationfilenamefull); sourcefilename.moveTo(destinationfile); if (isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.FileEncrypted", destinationfile.getName().toString())); } // add filename to result filename if (add_result_filesname && !iffileexists.equals("fail") && !iffileexists.equals("do_nothing")) { addFileToResultFilenames(destinationfile.toString(), result, parentJob); } updateSuccess(); } else if (ifmovedfileexists.equals("fail")) { // Update Errors updateErrors(); } } } else if (iffileexists.equals("fail")) { // Update Errors updateErrors(); } } } catch (Exception e) { updateErrors(); logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Error.Exception.MoveProcessError", sourcefilename.toString(), destinationfilename.toString(), e.getMessage())); } finally { if (destinationfile != null) { try { destinationfile.close(); } catch (IOException ex) { /* Ignore */ } } } return retval; }
From source file:org.pentaho.di.job.entries.pgpencryptfiles.JobEntryPGPEncryptFiles.java
private boolean EncryptOneFile(int actionType, FileObject Currentfile, FileObject sourcefilefolder, String userID, String realDestinationFilefoldername, String realWildcard, Job parentJob, Result result, FileObject movetofolderfolder) { boolean entrystatus = false; FileObject file_name = null;// w w w . j av a2s. c o m try { 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) { logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.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 (GetFileWildcard(sourceshortfilename, realWildcard)) { entrystatus = EncryptFile(actionType, shortfilename, Currentfile, userID, file_name, movetofolderfolder, parentJob, result); } } } } else { // In the Base Folder... // Folders..only if include subfolders if (Currentfile.getType() != FileType.FOLDER) { // file...Check if exists if (GetFileWildcard(sourceshortfilename, realWildcard)) { entrystatus = EncryptFile(actionType, shortfilename, Currentfile, userID, file_name, movetofolderfolder, parentJob, result); } } } } entrystatus = true; } catch (Exception e) { logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.Error", e.toString())); } finally { if (file_name != null) { try { file_name.close(); } catch (IOException ex) { /* Ignore */ } } } return entrystatus; }
From source file:org.pentaho.di.job.entries.pgpencryptfiles.JobEntryPGPEncryptFiles.java
private boolean CreateDestinationFolder(FileObject filefolder) { FileObject folder = null; try {/* w ww. j av a2 s . co m*/ if (destination_is_a_file) { folder = filefolder.getParent(); } else { folder = filefolder; } if (!folder.exists()) { if (create_destination_folder) { if (isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.FolderNotExist", folder.getName().toString())); } folder.createFolder(); if (isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.FolderWasCreated", folder.getName().toString())); } } else { logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.FolderNotExist", folder.getName().toString())); return false; } } return true; } catch (Exception e) { logError(BaseMessages.getString(PKG, "JobPGPEncryptFiles.Log.CanNotCreateParentFolder", folder.getName().toString()), e); } finally { if (folder != null) { try { folder.close(); } catch (Exception ex) { /* Ignore */ } } } return false; }
From source file:org.pentaho.di.job.entries.sftpput.JobEntrySFTPPUT.java
public Result execute(Result previousResult, int nr) throws KettleException { Result result = previousResult; List<RowMetaAndData> rows = result.getRows(); result.setResult(false);/* w ww . j a v a2s . co m*/ if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobSFTPPUT.Log.StartJobEntry")); } ArrayList<FileObject> myFileList = new ArrayList<FileObject>(); if (copyprevious) { if (rows.size() == 0) { if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobSFTPPUT.ArgsFromPreviousNothing")); } result.setResult(true); return result; } try { RowMetaAndData resultRow = null; // Copy the input row to the (command line) arguments for (int iteration = 0; iteration < rows.size(); iteration++) { resultRow = rows.get(iteration); // Get file names String file_previous = resultRow.getString(0, null); if (!Const.isEmpty(file_previous)) { FileObject file = KettleVFS.getFileObject(file_previous, this); if (!file.exists()) { logError(BaseMessages.getString(PKG, "JobSFTPPUT.Log.FilefromPreviousNotFound", file_previous)); } else { myFileList.add(file); if (log.isDebug()) { logDebug(BaseMessages.getString(PKG, "JobSFTPPUT.Log.FilenameFromResult", file_previous)); } } } } } catch (Exception e) { logError(BaseMessages.getString(PKG, "JobSFTPPUT.Error.ArgFromPrevious")); result.setNrErrors(1); // free resource myFileList = null; return result; } } if (copypreviousfiles) { List<ResultFile> resultFiles = result.getResultFilesList(); if (resultFiles == null || resultFiles.size() == 0) { if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobSFTPPUT.ArgsFromPreviousNothingFiles")); } result.setResult(true); return result; } try { for (Iterator<ResultFile> it = resultFiles.iterator(); it.hasNext() && !parentJob.isStopped();) { ResultFile resultFile = it.next(); FileObject file = resultFile.getFile(); if (file != null) { if (!file.exists()) { logError(BaseMessages.getString(PKG, "JobSFTPPUT.Log.FilefromPreviousNotFound", file.toString())); } else { myFileList.add(file); if (log.isDebug()) { logDebug(BaseMessages.getString(PKG, "JobSFTPPUT.Log.FilenameFromResult", file.toString())); } } } } } catch (Exception e) { logError(BaseMessages.getString(PKG, "JobSFTPPUT.Error.ArgFromPrevious")); result.setNrErrors(1); // free resource myFileList = null; return result; } } SFTPClient sftpclient = null; // String substitution.. String realServerName = environmentSubstitute(serverName); String realServerPort = environmentSubstitute(serverPort); String realUsername = environmentSubstitute(userName); String realPassword = Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(password)); String realSftpDirString = environmentSubstitute(sftpDirectory); String realWildcard = environmentSubstitute(wildcard); String realLocalDirectory = environmentSubstitute(localDirectory); String realKeyFilename = null; String realPassPhrase = null; // Destination folder (Move to) String realDestinationFolder = environmentSubstitute(getDestinationFolder()); try { // Let's perform some checks before starting if (getAfterFTPS() == AFTER_FTPSPUT_MOVE) { if (Const.isEmpty(realDestinationFolder)) { logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.DestinatFolderMissing")); result.setNrErrors(1); return result; } else { FileObject folder = null; try { folder = KettleVFS.getFileObject(realDestinationFolder, this); // Let's check if folder exists... if (!folder.exists()) { // Do we need to create it? if (createDestinationFolder) { folder.createFolder(); } else { logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.DestinatFolderNotExist", realDestinationFolder)); result.setNrErrors(1); return result; } } realDestinationFolder = KettleVFS.getFilename(folder); } catch (Exception e) { throw new KettleException(e); } finally { if (folder != null) { try { folder.close(); } catch (Exception e) { /* Ignore */ } } } } } if (isUseKeyFile()) { // We must have here a private keyfilename realKeyFilename = environmentSubstitute(getKeyFilename()); if (Const.isEmpty(realKeyFilename)) { // Error..Missing keyfile logError(BaseMessages.getString(PKG, "JobSFTP.Error.KeyFileMissing")); result.setNrErrors(1); return result; } if (!KettleVFS.fileExists(realKeyFilename)) { // Error.. can not reach keyfile logError(BaseMessages.getString(PKG, "JobSFTP.Error.KeyFileNotFound")); result.setNrErrors(1); return result; } realPassPhrase = environmentSubstitute(getKeyPassPhrase()); } // Create sftp client to host ... sftpclient = new SFTPClient(InetAddress.getByName(realServerName), Const.toInt(realServerPort, 22), realUsername, realKeyFilename, realPassPhrase); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobSFTPPUT.Log.OpenedConnection", realServerName, "" + realServerPort, realUsername)); } // Set compression sftpclient.setCompression(getCompression()); // Set proxy? String realProxyHost = environmentSubstitute(getProxyHost()); if (!Const.isEmpty(realProxyHost)) { // Set proxy sftpclient.setProxy(realProxyHost, environmentSubstitute(getProxyPort()), environmentSubstitute(getProxyUsername()), environmentSubstitute(getProxyPassword()), getProxyType()); } // login to ftp host ... sftpclient.login(realPassword); // Don't show the password in the logs, it's not good for security audits // logDetailed("logged in using password "+realPassword); // Logging this seems a bad idea! Oh well. // move to spool dir ... if (!Const.isEmpty(realSftpDirString)) { boolean existfolder = sftpclient.folderExists(realSftpDirString); if (!existfolder) { if (!isCreateRemoteFolder()) { throw new KettleException(BaseMessages.getString(PKG, "JobSFTPPUT.Error.CanNotFindRemoteFolder", realSftpDirString)); } if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobSFTPPUT.Error.CanNotFindRemoteFolder", realSftpDirString)); } // Let's create folder sftpclient.createFolder(realSftpDirString); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobSFTPPUT.Log.RemoteFolderCreated", realSftpDirString)); } } sftpclient.chdir(realSftpDirString); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobSFTPPUT.Log.ChangedDirectory", realSftpDirString)); } } // end if if (!copyprevious && !copypreviousfiles) { // Get all the files in the local directory... myFileList = new ArrayList<FileObject>(); FileObject localFiles = KettleVFS.getFileObject(realLocalDirectory, this); FileObject[] children = localFiles.getChildren(); if (children != null) { for (int i = 0; i < children.length; i++) { // Get filename of file or directory if (children[i].getType().equals(FileType.FILE)) { // myFileList.add(children[i].getAbsolutePath()); myFileList.add(children[i]); } } // end for } } if (myFileList == null || myFileList.size() == 0) { if (isSuccessWhenNoFile()) { // Just warn user if (isBasic()) { logBasic(BaseMessages.getString(PKG, "JobSFTPPUT.Error.NoFileToSend")); } } else { // Fail logError(BaseMessages.getString(PKG, "JobSFTPPUT.Error.NoFileToSend")); result.setNrErrors(1); return result; } } if (log.isDetailed()) { logDetailed( BaseMessages.getString(PKG, "JobSFTPPUT.Log.RowsFromPreviousResult", myFileList.size())); } Pattern pattern = null; if (!copyprevious && !copypreviousfiles) { if (!Const.isEmpty(realWildcard)) { pattern = Pattern.compile(realWildcard); } } // Get the files in the list and execute sftp.put() for each file Iterator<FileObject> it = myFileList.iterator(); while (it.hasNext() && !parentJob.isStopped()) { FileObject myFile = it.next(); try { String localFilename = myFile.toString(); String destinationFilename = myFile.getName().getBaseName(); boolean getIt = true; // First see if the file matches the regular expression! if (pattern != null) { Matcher matcher = pattern.matcher(destinationFilename); getIt = matcher.matches(); } if (getIt) { if (log.isDebug()) { logDebug(BaseMessages.getString(PKG, "JobSFTPPUT.Log.PuttingFile", localFilename, realSftpDirString)); } sftpclient.put(myFile, destinationFilename); if (log.isDetailed()) { logDetailed( BaseMessages.getString(PKG, "JobSFTPPUT.Log.TransferedFile", localFilename)); } // We successfully uploaded the file // what's next ... switch (getAfterFTPS()) { case AFTER_FTPSPUT_DELETE: myFile.delete(); if (log.isDetailed()) { logDetailed( BaseMessages.getString(PKG, "JobSFTPPUT.Log.DeletedFile", localFilename)); } break; case AFTER_FTPSPUT_MOVE: FileObject destination = null; try { destination = KettleVFS.getFileObject(realDestinationFolder + Const.FILE_SEPARATOR + myFile.getName().getBaseName(), this); myFile.moveTo(destination); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobSFTPPUT.Log.FileMoved", myFile, destination)); } } finally { if (destination != null) { destination.close(); } } break; default: if (addFilenameResut) { // Add to the result files... ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, myFile, parentJob.getJobname(), toString()); result.getResultFiles().put(resultFile.getFile().toString(), resultFile); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobSFTPPUT.Log.FilenameAddedToResultFilenames", localFilename)); } } break; } } } finally { if (myFile != null) { myFile.close(); } } } // end for result.setResult(true); // JKU: no idea if this is needed...! // result.setNrFilesRetrieved(filesRetrieved); } catch (Exception e) { result.setNrErrors(1); logError(BaseMessages.getString(PKG, "JobSFTPPUT.Exception", e.getMessage())); logError(Const.getStackTracker(e)); } finally { // close connection, if possible try { if (sftpclient != null) { sftpclient.disconnect(); } } catch (Exception e) { // just ignore this, makes no big difference } // end catch myFileList = null; } // end finally return result; }
From source file:org.pentaho.di.job.entries.ssh2put.JobEntrySSH2PUT.java
public Result execute(Result previousResult, int nr) { Result result = previousResult; result.setResult(false);/*w w w. j a v a 2 s . c om*/ try { // Get real variable value String realServerName = environmentSubstitute(serverName); int realServerPort = Const.toInt(environmentSubstitute(serverPort), 22); String realUserName = environmentSubstitute(userName); String realServerPassword = Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(password)); // Proxy Host String realProxyHost = environmentSubstitute(httpproxyhost); int realProxyPort = Const.toInt(environmentSubstitute(httpproxyport), 22); String realproxyUserName = environmentSubstitute(httpproxyusername); String realProxyPassword = Encr .decryptPasswordOptionallyEncrypted(environmentSubstitute(httpProxyPassword)); // Key file String realKeyFilename = environmentSubstitute(keyFilename); String relKeyFilepass = environmentSubstitute(keyFilePass); // Source files String realLocalDirectory = environmentSubstitute(localDirectory); String realwildcard = environmentSubstitute(wildcard); // Remote destination String realftpDirectory = environmentSubstitute(ftpDirectory); // Destination folder (Move to) String realDestinationFolder = environmentSubstitute(destinationfolder); try { // Remote source realftpDirectory = FTPUtils.normalizePath(realftpDirectory); // Destination folder (Move to) realDestinationFolder = FTPUtils.normalizePath(realDestinationFolder); } catch (Exception e) { logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.CanNotNormalizePath", e.getMessage())); result.setNrErrors(1); return result; } // Check for mandatory fields boolean mandatoryok = true; if (Const.isEmpty(realServerName)) { mandatoryok = false; logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.ServernameMissing")); } if (usehttpproxy) { if (Const.isEmpty(realProxyHost)) { mandatoryok = false; logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.HttpProxyhostMissing")); } } if (publicpublickey) { if (Const.isEmpty(realKeyFilename)) { mandatoryok = false; logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.KeyFileMissing")); } else { // Let's check if folder exists... if (!KettleVFS.fileExists(realKeyFilename, this)) { mandatoryok = false; logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.KeyFileNotExist")); } } } if (Const.isEmpty(realLocalDirectory)) { mandatoryok = false; logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.LocalFolderMissing")); } if (afterFtpPut.equals("move_file")) { if (Const.isEmpty(realDestinationFolder)) { mandatoryok = false; logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.DestinatFolderMissing")); } else { FileObject folder = null; try { folder = KettleVFS.getFileObject(realDestinationFolder, this); // Let's check if folder exists... if (!folder.exists()) { // Do we need to create it? if (createDestinationFolder) { folder.createFolder(); } else { logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.DestinatFolderNotExist", realDestinationFolder)); } } } catch (Exception e) { throw new KettleException(e); } finally { if (folder != null) { try { folder.close(); folder = null; } catch (Exception e) { /* Ignore */ } } } } } if (mandatoryok) { Connection conn = null; SFTPv3Client client = null; boolean good = true; int nbfilestoput = 0; int nbput = 0; int nbrerror = 0; try { // Create a connection instance conn = getConnection(realServerName, realServerPort, realProxyHost, realProxyPort, realproxyUserName, realProxyPassword); if (timeout > 0) { // Use timeout // Cache Host Key if (cachehostkey) { conn.connect(new SimpleVerifier(database), 0, timeout * 1000); } else { conn.connect(null, 0, timeout * 1000); } } else { // Cache Host Key if (cachehostkey) { conn.connect(new SimpleVerifier(database)); } else { conn.connect(); } } // Authenticate boolean isAuthenticated = false; if (publicpublickey) { String keyContent = KettleVFS.getTextFileContent(realKeyFilename, this, Const.XML_ENCODING); isAuthenticated = conn.authenticateWithPublicKey(realUserName, keyContent.toCharArray(), relKeyFilepass); } else { isAuthenticated = conn.authenticateWithPassword(realUserName, realServerPassword); } // LET'S CHECK AUTHENTICATION ... if (isAuthenticated == false) { logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.AuthenticationFailed")); } else { if (log.isBasic()) { logBasic(BaseMessages.getString(PKG, "JobSSH2PUT.Log.Connected", serverName, userName)); } client = new SFTPv3Client(conn); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobSSH2PUT.Log.ProtocolVersion", "" + client.getProtocolVersion())); } // Check if remote directory exists if (!Const.isEmpty(realftpDirectory)) { if (!sshDirectoryExists(client, realftpDirectory)) { good = false; if (createRemoteFolder) { good = CreateRemoteFolder(client, realftpDirectory); if (good) { logBasic(BaseMessages.getString(PKG, "JobSSH2PUT.Log.RemoteDirectoryCreated")); } } else { logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.RemoteDirectoryNotExist", realftpDirectory)); } } else if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobSSH2PUT.Log.RemoteDirectoryExist", realftpDirectory)); } } if (good) { // Get files list from local folder (source) List<FileObject> myFileList = getFiles(realLocalDirectory); // Prepare Pattern for wildcard Pattern pattern = null; if (!Const.isEmpty(realwildcard)) { pattern = Pattern.compile(realwildcard); } // Let's put files now ... // Get the files in the list for (int i = 0; i < myFileList.size() && !parentJob.isStopped(); i++) { FileObject myFile = myFileList.get(i); String localFilename = myFile.toString(); String remoteFilename = myFile.getName().getBaseName(); boolean getIt = true; // First see if the file matches the regular expression! if (pattern != null) { Matcher matcher = pattern.matcher(remoteFilename); getIt = matcher.matches(); } // do we have a target directory? if (!Const.isEmpty(realftpDirectory)) { remoteFilename = realftpDirectory + FTPUtils.FILE_SEPARATOR + remoteFilename; } if (onlyGettingNewFiles) { // We get only new files // ie not exist on the remote server getIt = !sshFileExists(client, remoteFilename); } if (getIt) { nbfilestoput++; boolean putok = putFile(myFile, remoteFilename, client); if (!putok) { nbrerror++; logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.Error.CanNotPutFile", localFilename)); } else { nbput++; } if (putok && !afterFtpPut.equals("do_nothing")) { deleteOrMoveFiles(myFile, realDestinationFolder); } } } /******************************** RESULT ********************/ if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobSSH2PUT.Log.Result.JobEntryEnd1")); logDetailed(BaseMessages.getString(PKG, "JobSSH2PUT.Log.Result.TotalFiles", "" + nbfilestoput)); logDetailed(BaseMessages.getString(PKG, "JobSSH2PUT.Log.Result.TotalFilesPut", "" + nbput)); logDetailed(BaseMessages.getString(PKG, "JobSSH2PUT.Log.Result.TotalFilesError", "" + nbrerror)); logDetailed(BaseMessages.getString(PKG, "JobSSH2PUT.Log.Result.JobEntryEnd2")); } if (nbrerror == 0) { result.setResult(true); /******************************** RESULT ********************/ } } } } catch (Exception e) { result.setNrErrors(nbrerror); logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.Error.ErrorFTP", e.getMessage())); } finally { if (conn != null) { conn.close(); } if (client != null) { client.close(); } } } } catch (Exception e) { result.setResult(false); result.setNrErrors(1L); logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.Error.UnexpectedError"), e); } return result; }
From source file:org.pentaho.di.job.entries.ssh2put.JobEntrySSH2PUT.java
private boolean deleteOrMoveFiles(FileObject file, String destinationFolder) throws KettleException { try {/*from w ww. j a v a 2s . co m*/ boolean retval = false; // Delete the file if this is needed! // if (afterFtpPut.equals("delete_file")) { file.delete(); retval = true; if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobSSH2PUT.Log.DeletedFile", file.toString())); } } else if (afterFtpPut.equals("move_file")) { // Move File FileObject destination = null; FileObject source = null; try { destination = KettleVFS.getFileObject( destinationFolder + Const.FILE_SEPARATOR + file.getName().getBaseName(), this); file.moveTo(destination); retval = true; } catch (Exception e) { logError(BaseMessages.getString(PKG, "JobSSH2PUT.Cant_Move_File.Label", file.toString(), destinationFolder, e.getMessage())); } finally { if (destination != null) { try { destination.close(); } catch (Exception ex) { /* Ignore */ } } if (source != null) { try { source.close(); } catch (Exception ex) { /* Ignore */ } } } if (log.isDetailed()) { logDetailed( BaseMessages.getString(PKG, "JobSSH2PUT.Log.MovedFile", file.toString(), ftpDirectory)); } } return retval; } catch (Exception e) { throw new KettleException(e); } }
From source file:org.pentaho.di.job.entries.talendjobexec.JobEntryTalendJobExec.java
private URL[] prepareJarFiles(FileObject zipFile) throws Exception { // zip:file:///tmp/foo.zip FileInputList fileList = FileInputList.createFileList(this, new String[] { "zip:" + zipFile.toString(), }, new String[] { ".*\\.jar$", }, // Include mask: only jar files new String[] { ".*classpath\\.jar$", }, // Exclude mask: only jar files new String[] { "Y", }, // File required new boolean[] { true, }); // Search sub-directories List<URL> files = new ArrayList<URL>(); // Copy the jar files in the temp folder... ////from w ww . ja va 2s . c o m for (FileObject file : fileList.getFiles()) { FileObject jarfilecopy = KettleVFS.createTempFile(file.getName().getBaseName(), ".jar", environmentSubstitute("${java.io.tmpdir}")); jarfilecopy.copyFrom(file, new AllFileSelector()); files.add(jarfilecopy.getURL()); } return files.toArray(new URL[files.size()]); }
From source file:org.pentaho.di.job.entries.unzip.JobEntryUnZip.java
private boolean unzipFile(FileObject sourceFileObject, String realTargetdirectory, String realWildcard, String realWildcardExclude, Result result, Job parentJob, FileObject fileObject, FileObject movetodir, String realMovetodirectory) { boolean retval = false; String unzipToFolder = realTargetdirectory; try {//from w w w . j ava 2 s . c o m if (log.isDetailed()) { logDetailed( BaseMessages.getString(PKG, "JobUnZip.Log.ProcessingFile", sourceFileObject.toString())); } // Do you create a root folder? // if (rootzip) { String shortSourceFilename = sourceFileObject.getName().getBaseName(); int lenstring = shortSourceFilename.length(); int lastindexOfDot = shortSourceFilename.lastIndexOf('.'); if (lastindexOfDot == -1) { lastindexOfDot = lenstring; } String foldername = realTargetdirectory + "/" + shortSourceFilename.substring(0, lastindexOfDot); FileObject rootfolder = KettleVFS.getFileObject(foldername, this); if (!rootfolder.exists()) { try { rootfolder.createFolder(); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobUnZip.Log.RootFolderCreated", foldername)); } } catch (Exception e) { throw new Exception( BaseMessages.getString(PKG, "JobUnZip.Error.CanNotCreateRootFolder", foldername), e); } } unzipToFolder = foldername; } // Try to read the entries from the VFS object... // String zipFilename = "zip:" + sourceFileObject.getName().getFriendlyURI(); FileObject zipFile = KettleVFS.getFileObject(zipFilename, this); FileObject[] items = zipFile.findFiles(new AllFileSelector() { public boolean traverseDescendents(FileSelectInfo info) { return true; } public boolean includeFile(FileSelectInfo info) { // Never return the parent directory of a file list. if (info.getDepth() == 0) { return false; } FileObject fileObject = info.getFile(); return fileObject != null; } }); Pattern pattern = null; if (!Const.isEmpty(realWildcard)) { pattern = Pattern.compile(realWildcard); } Pattern patternexclude = null; if (!Const.isEmpty(realWildcardExclude)) { patternexclude = Pattern.compile(realWildcardExclude); } for (FileObject item : items) { if (successConditionBroken) { if (!successConditionBrokenExit) { logError(BaseMessages.getString(PKG, "JobUnZip.Error.SuccessConditionbroken", "" + NrErrors)); successConditionBrokenExit = true; } return false; } synchronized (KettleVFS.getInstance().getFileSystemManager()) { FileObject newFileObject = null; try { if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobUnZip.Log.ProcessingZipEntry", item.getName().getURI(), sourceFileObject.toString())); } // get real destination filename // String newFileName = unzipToFolder + Const.FILE_SEPARATOR + getTargetFilename(item); newFileObject = KettleVFS.getFileObject(newFileName, this); if (item.getType().equals(FileType.FOLDER)) { // Directory // if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobUnZip.CreatingDirectory.Label", newFileName)); } // Create Directory if necessary ... // if (!newFileObject.exists()) { newFileObject.createFolder(); } } else { // File // boolean getIt = true; boolean getItexclude = false; // First see if the file matches the regular expression! // if (pattern != null) { Matcher matcher = pattern.matcher(item.getName().getURI()); getIt = matcher.matches(); } if (patternexclude != null) { Matcher matcherexclude = patternexclude.matcher(item.getName().getURI()); getItexclude = matcherexclude.matches(); } boolean take = takeThisFile(item, newFileName); if (getIt && !getItexclude && take) { if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobUnZip.ExtractingEntry.Label", item.getName().getURI(), newFileName)); } if (iffileexist == IF_FILE_EXISTS_UNIQ) { // Create file with unique name int lenstring = newFileName.length(); int lastindexOfDot = newFileName.lastIndexOf('.'); if (lastindexOfDot == -1) { lastindexOfDot = lenstring; } newFileName = newFileName.substring(0, lastindexOfDot) + StringUtil.getFormattedDateTimeNow(true) + newFileName.substring(lastindexOfDot, lenstring); if (log.isDebug()) { logDebug(BaseMessages.getString(PKG, "JobUnZip.Log.CreatingUniqFile", newFileName)); } } // See if the folder to the target file exists... // if (!newFileObject.getParent().exists()) { newFileObject.getParent().createFolder(); // creates the whole path. } InputStream is = null; OutputStream os = null; try { is = KettleVFS.getInputStream(item); os = KettleVFS.getOutputStream(newFileObject, false); if (is != null) { byte[] buff = new byte[2048]; int len; while ((len = is.read(buff)) > 0) { os.write(buff, 0, len); } // Add filename to result filenames addFilenameToResultFilenames(result, parentJob, newFileName); } } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } } // end if take } } catch (Exception e) { updateErrors(); logError(BaseMessages.getString(PKG, "JobUnZip.Error.CanNotProcessZipEntry", item.getName().getURI(), sourceFileObject.toString()), e); } finally { if (newFileObject != null) { try { newFileObject.close(); if (setOriginalModificationDate) { // Change last modification date newFileObject.getContent() .setLastModifiedTime(item.getContent().getLastModifiedTime()); } } catch (Exception e) { /* Ignore */ } // ignore this } // Close file object // close() does not release resources! KettleVFS.getInstance().getFileSystemManager().closeFileSystem(item.getFileSystem()); if (items != null) { items = null; } } } // Synchronized block on KettleVFS.getInstance().getFileSystemManager() } // End for // Here gc() is explicitly called if e.g. createfile is used in the same // job for the same file. The problem is that after creating the file the // file object is not properly garbaged collected and thus the file cannot // be deleted anymore. This is a known problem in the JVM. // System.gc(); // Unzip done... if (afterunzip == 1) { // delete zip file boolean deleted = fileObject.delete(); if (!deleted) { updateErrors(); logError(BaseMessages.getString(PKG, "JobUnZip.Cant_Delete_File.Label", sourceFileObject.toString())); } // File deleted if (log.isDebug()) { logDebug(BaseMessages.getString(PKG, "JobUnZip.File_Deleted.Label", sourceFileObject.toString())); } } else if (afterunzip == 2) { FileObject destFile = null; // Move File try { String destinationFilename = movetodir + Const.FILE_SEPARATOR + fileObject.getName().getBaseName(); destFile = KettleVFS.getFileObject(destinationFilename, this); fileObject.moveTo(destFile); // File moved if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobUnZip.Log.FileMovedTo", sourceFileObject.toString(), realMovetodirectory)); } } catch (Exception e) { updateErrors(); logError(BaseMessages.getString(PKG, "JobUnZip.Cant_Move_File.Label", sourceFileObject.toString(), realMovetodirectory, e.getMessage())); } finally { if (destFile != null) { try { destFile.close(); } catch (IOException ex) { /* Ignore */ } } } } retval = true; } catch (Exception e) { updateErrors(); log.logError(BaseMessages.getString(PKG, "JobUnZip.Error.Label"), BaseMessages.getString(PKG, "JobUnZip.ErrorUnzip.Label", sourceFileObject.toString(), e.getMessage()), e); } return retval; }