List of usage examples for org.apache.commons.vfs FileObject toString
public String toString()
From source file:org.cfeclipse.cfml.views.explorer.vfs.view.VFSView.java
/** * Creates the Drag & Drop DragSource for items being dragged from the table. * //w w w. java 2s . co m * @return the DragSource for the table */ private DragSource createTableDragSource(final Table table) { DragSource dragSource = new DragSource(table, DND.DROP_COPY); // | DND.DROP_MOVE // transfer type is text data (file URI) dragSource.setTransfer(new Transfer[] { FileTransfer.getInstance() }); dragSource.addDragListener(new DragSourceListener() { TableItem[] dndSelection = null; String[] sourceNames = null; public void dragStart(DragSourceEvent event) { dndSelection = table.getSelection(); sourceNames = null; event.doit = dndSelection.length > 0; isDragging = true; } public void dragFinished(DragSourceEvent event) { dragSourceHandleDragFinished(event, sourceNames); dndSelection = null; sourceNames = null; isDragging = false; //TODO try { // handleDeferredRefresh(); // } catch (Exception e) { // debug("createTableDragSource.dragFinished " + e); // } } public void dragSetData(DragSourceEvent event) { if (dndSelection == null || dndSelection.length == 0) return; if (!FileTransfer.getInstance().isSupportedType(event.dataType)) { error("createTableDragSource.dragSetData File Transfer data type text is required."); return; } // Cannot put Objects in the transfer event data field, they must be path // and begin with / in UNIX sourceNames = new String[dndSelection.length + 1]; String connectionId = ""; for (int i = 1; i < dndSelection.length; i++) { FileObject file = (FileObject) dndSelection[i].getData(TABLEITEMDATA_FILE); connectionId = (String) dndSelection[i].getData(TABLEITEMDATA_CONNECTIONID); /* * In Order for FileTransfer to Work, the name must begin w/ * / in UNIX systems */ sourceNames[i] = Os.isFamily(Os.OS_FAMILY_UNIX) ? FileName.SEPARATOR + file.toString() : file.toString(); System.out.println( "createTableDragSource::dragSetData: sourceNames [" + i + "] path= " + sourceNames[i]); } sourceNames[0] = connectionId; event.data = sourceNames; } }); return dragSource; }
From source file:org.cfeclipse.cfml.views.explorer.vfs.view.VFSView.java
/** * Notifies the application components that a new current directory has been selected * /*from w w w . j a v a 2 s. c o m*/ * @param dir the directory that was selected, null is ignored */ public void notifySelectedDirectory(FileObject dir, String connectionId) throws FileSystemException { if (dir == null || connectionId == null) return; if (getCurrentDirectory() != null && dir.equals(getCurrentDirectory())) return; setCurrentDirectory(dir); setCurrentConnectionId(connectionId); //System.err.println("notifySelectedDirectory currentDirectory:" // + currentDirectory + " notify dir:" + dir ); // Processing... VFSUtil.setUiStateListContents(shell, getCurrentDirectory().getName().toString()); notifySelectedFiles(null); /* Table view: * Displays the contents of the selected directory. */ workerUpdate(dir, connectionId, false); /* Combo view: * Sets the combo box to point to the selected directory. */ final FileObject[] comboRoots = (FileObject[]) combo.getData(COMBODATA_ROOTS); int comboEntry = -1; if (comboRoots != null) { for (int i = 0; i < comboRoots.length; ++i) { if (dir.equals(comboRoots[i])) { comboEntry = i; break; } } } if (comboEntry == -1) combo.setText(dir.getName().toString()); else combo.select(comboEntry); /* Tree view: * If not already expanded, recursively expands the parents of the specified * directory until it is visible. */ Vector /* of FileObject */ path = new Vector(); // Build a stack of paths from the root of the tree while (dir != null) { path.add(dir); //dir = dir.getParentFile(); try { dir = dir.getParent(); } catch (Exception e) { System.err.println("notifySelectedDirectory:" + e); } } //System.out.println("notifySelectedDirectory currentDirectory:" // + currentDirectory + " dir:" + dir + " tree path:" + path); // Recursively expand the tree to get to the specified directory TreeItem[] items = tree.getItems(); TreeItem lastItem = null; String destConnectionId = null; TreeItem item = null; // filter by connection first for (int k = 0; k < items.length; ++k) { item = items[k]; destConnectionId = (String) item.getData(TREEITEMDATA_CONNECTIONID); if (connectionId.equals(connectionId)) { items = items[k].getItems(); } } for (int i = path.size() - 1; i >= 0; --i) { final FileObject pathElement = (FileObject) path.elementAt(i); // Search for a particular FileObject in the array of tree items // No guarantee that the items are sorted in any recognizable fashion, so we'll // just sequential scan. There shouldn't be more than a few thousand entries. item = null; for (int k = 0; k < items.length; ++k) { item = items[k]; if (item.isDisposed()) continue; final String fileURI = ((String) item.getData(TREEITEMDATA_URI)); destConnectionId = (String) item.getData(TREEITEMDATA_CONNECTIONID); // Resolving the children will attempt a server connection. This will hang the UI if the server is down // Thus perform a comparison by Host/Scheme/Path only // Cannot just compare the URI strings cuz FileObject hides the port number if (connectionId.equals(destConnectionId) && VFSUtil.compareURIs(fileURI, pathElement.toString())) break; } if (item == null) break; lastItem = item; if (i != 0 && !item.getExpanded()) { treeExpandItem(item); item.setExpanded(true); } items = item.getItems(); } if (connectionId.equals(destConnectionId)) { tree.setSelection((lastItem != null) ? new TreeItem[] { lastItem } : new TreeItem[0]); } /* Shell: * Sets the title to indicate the selected directory */ VFSUtil.setUiStateIdle(shell, VFSUtil.stripUserTokens(getCurrentDirectory().toString())); }
From source file:org.codehaus.cargo.util.VFSFileHandler.java
/** * Create a directory. {@inheritDoc}/* ww w. ja v a 2 s . co m*/ * @param parent Parent directory name. * @param path Directory name. * @return Created directory name. */ @Override public String createDirectory(String parent, String path) { String directoryname; if (path != null) { directoryname = path; } else { directoryname = ""; } if (parent != null) { if (!parent.endsWith("/") && !directoryname.startsWith("/")) { directoryname = "/" + directoryname; } directoryname = parent + directoryname; } try { FileObject fileObject = getFileSystemManager().resolveFile(directoryname); fileObject.createFolder(); return fileObject.toString(); } catch (FileSystemException e) { throw new CargoException("Failed to create folder [" + directoryname + "]", e); } }
From source file:org.openbi.kettle.plugins.refreshtableauextract.RefreshTableauExtract.java
public Result execute(Result previousResult, int nr) throws KettleException { Result result = previousResult; result.setResult(validate());/* w w w . j av a 2 s.c om*/ if (!result.getResult()) { return result; } String[] commands; String tableauCommand = getRealValue(getTableauClient()).trim(); if (tableauCommand.toLowerCase().endsWith(".exe")) { tableauCommand = tableauCommand.substring(0, tableauCommand.length() - 4); } tableauCommand = "\"" + tableauCommand + "\""; if (getRefreshType() == 0 || getRefreshType() == 1) { tableauCommand += " refreshextract"; } else if (getRefreshType() == 2) { tableauCommand += " addfiletoextract"; } else { logError(BaseMessages.getString(PKG, "RefreshTableauExtract.Error.InvalidRefreshType")); result.setResult(false); return result; } tableauCommand += " --server " + protocolList[getProtocol()] + "://" + getRealValue(getServer()); if (getRealValue(getServerPort()) != null && !getRealValue(getServerPort()).isEmpty()) { tableauCommand += ":" + getRealValue(getServerPort()); } tableauCommand += " --username " + getRealValue(getServerUser()); tableauCommand += " --password " + getRealValue(getServerPassword()); tableauCommand += " --datasource \"" + getRealValue(getDataSource()) + "\""; if (getRealValue(getSiteName()) != null && !getRealValue(getSiteName()).isEmpty()) { tableauCommand += " --site \"" + getRealValue(getSiteName()) + "\""; } if (getRealValue(getProject()) != null && !getRealValue(getProject()).isEmpty()) { tableauCommand += " --project \"" + getRealValue(getProject()) + "\""; } if (getRealValue(getProxyUser()) != null && !getRealValue(getProxyUser()).isEmpty()) { tableauCommand += " --proxy-username " + getRealValue(getProxyUser()); } if (getRealValue(getProxyPassword()) != null && !getRealValue(getProxyPassword()).isEmpty()) { tableauCommand += " --proxy-password " + getRealValue(getProxyPassword()); } if (getRefreshType() == 0) { commands = new String[1]; tableauCommand += " --original-file \"" + getRealValue(getExtractFile()) + "\""; commands[0] = new String(tableauCommand); } else if (getRefreshType() == 1) { commands = new String[1]; if (getFullRefresh()) { tableauCommand += " --force-full-refresh"; } if (getRealValue(getSourceUser()) != null && !getRealValue(getSourceUser()).isEmpty()) { tableauCommand += " --source-username " + getRealValue(getSourceUser()); } if (getRealValue(getSourcePassword()) != null & !getRealValue(getSourcePassword()).isEmpty()) { tableauCommand += " --source-password " + getRealValue(getSourcePassword()); } commands[0] = new String(tableauCommand); } else { String[] fileStrings = null; if (processResultFiles) { if (result != null && previousResult.getResultFiles().size() > 0) { int size = previousResult.getResultFiles().size(); if (log.isBasic()) { logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.FilesFound", "" + size)); } try { List<ResultFile> resultFiles = previousResult.getResultFilesList(); List<String> files = new ArrayList<String>(); Iterator<ResultFile> it = resultFiles.iterator(); while (it.hasNext()) { ResultFile f = it.next(); FileObject o = f.getFile(); if (o.getType().equals(FileType.FILE)) { if (o.exists()) { files.add(o.getName().toString().startsWith("file:///") ? o.getName().toString().substring(8) : o.getName().toString()); } else { logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.FileNotExist", "" + o.getName())); } } else { logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.ResultNotFile", "" + o.getName())); } } if (files.size() > 0) { Iterator<String> ite = files.iterator(); fileStrings = new String[files.size()]; int i = 0; while (ite.hasNext()) { fileStrings[i] = ite.next(); i++; } } else { logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.NoFilesOnResult")); result.setResult(true); return result; } } catch (Exception ex) { logError(ex.toString()); result.setResult(false); return result; } } else { logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.NoFilesOnResult")); result.setResult(true); return result; } } else { // Get source and destination files, also wildcard String[] vFilePaths = filePaths; String[] vWildcards = wildcards; boolean[] includeSubfolders = new boolean[vFilePaths.length]; String[] fileRequired = new String[vFilePaths.length]; for (int i = 0; i < includeSubfolders.length; i++) { includeSubfolders[i] = false; } FileInputList files = FileInputList.createFileList(this, vFilePaths, vWildcards, fileRequired, includeSubfolders); fileStrings = new String[files.getFileStrings().length]; fileStrings = files.getFileStrings(); } commands = new String[fileStrings.length]; for (int i = 0; i < fileStrings.length; i++) { commands[i] = new String(tableauCommand + " --file \"" + fileStrings[i] + "\""); } } FileObject fileObject = null; String realScript = ""; FileObject tempFile = null; for (int i = 0; i < commands.length; i++) { // realScript+="echo Running: "+commands[i]+"\n"; realScript += commands[i] + "\n"; if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "RefreshTableauExtract.Commands", commands[i])); } } try { // What's the exact command? String[] command; if (log.isBasic()) { logBasic(BaseMessages.getString(PKG, "RefreshTableuaExtract.RunningOn", Const.getOS())); } if (Const.getOS().equals("Windows 95")) { //base = new String[] { "command.com", "/C" }; tempFile = KettleVFS.createTempFile("kettle", "shell.bat", null, this); fileObject = createTemporaryShellFile(tempFile, realScript); command = new String[] { "command.com", "/C", "\"" + Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject)) + "\"" }; } else if (Const.getOS().startsWith("Windows")) { //base = new String[] { "cmd.exe", "/C" }; tempFile = KettleVFS.createTempFile("kettle", "shell.bat", null, this); fileObject = createTemporaryShellFile(tempFile, realScript); command = new String[] { "cmd.exe", "/C", "\"" + Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject)) + "\"" }; } else { tempFile = KettleVFS.createTempFile("kettle", "shell", null, this); fileObject = createTemporaryShellFile(tempFile, realScript); command = new String[] { Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject)) }; } ProcessBuilder pb = new ProcessBuilder(command); Map<String, String> env = pb.environment(); String[] variables = listVariables(); for (int i = 0; i < variables.length; i++) { env.put(variables[i], getVariable(variables[i])); } if (getWorkingDirectory() != null && !Const.isEmpty(Const.rtrim(getRealValue(getWorkingDirectory())))) { String vfsFilename = environmentSubstitute(getRealValue(getWorkingDirectory())); File file = new File(KettleVFS.getFilename(KettleVFS.getFileObject(vfsFilename, this))); pb.directory(file); } if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "RefreshTableauExtract.CommandStarted")); } Process proc = pb.start(); // any error message? StreamLogger errorLogger = new StreamLogger(log, proc.getErrorStream(), "(stderr)"); // any output? StreamLogger outputLogger = new StreamLogger(log, proc.getInputStream(), "(stdout)"); // kick them off new Thread(errorLogger).start(); new Thread(outputLogger).start(); proc.waitFor(); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "RefreshTableauExtract.CommandFinished")); } // What's the exit status? result.setExitStatus(proc.exitValue()); if (result.getExitStatus() != 0) { logError(BaseMessages.getString(PKG, "RefreshTableauExtract.ExitStatus", "" + result.getExitStatus())); result.setResult(false); } // close the streams // otherwise you get "Too many open files, java.io.IOException" after a lot of iterations proc.getErrorStream().close(); proc.getOutputStream().close(); } catch (Exception ex) { logError(ex.toString()); result.setResult(false); } finally { // If we created a temporary file, remove it... // if (tempFile != null) { try { tempFile.delete(); } catch (Exception e) { BaseMessages.getString(PKG, "RefreshTableauExtract.UnexpectedError", tempFile.toString(), e.toString()); } } } return result; }
From source file:org.pentaho.di.core.xml.XMLHandler.java
/** * Load a file into an XML document//from w w w.j a v a 2s . c o m * * @param filename * The filename to load into a document * @param systemId * Provide a base for resolving relative URIs. * @param ignoreEntities * Ignores external entities and returns an empty dummy. * @param namespaceAware * support XML namespaces. * @return the Document if all went well, null if an error occured! */ public static final Document loadXMLFile(FileObject fileObject, String systemID, boolean ignoreEntities, boolean namespaceAware) throws KettleXMLException { try { return loadXMLFile(KettleVFS.getInputStream(fileObject), systemID, ignoreEntities, namespaceAware); } catch (IOException e) { throw new KettleXMLException("Unable to read file [" + fileObject.toString() + "]", e); } }
From source file:org.pentaho.di.job.entries.addresultfilenames.JobEntryAddResultFilenames.java
private boolean processFile(String filename, String wildcard, Job parentJob, Result result) { boolean rcode = true; FileObject filefolder = null; String realFilefoldername = environmentSubstitute(filename); String realwildcard = environmentSubstitute(wildcard); try {//from w w w . j ava 2 s.c o m filefolder = KettleVFS.getFileObject(realFilefoldername, this); if (filefolder.exists()) { // the file or folder exists if (filefolder.getType() == FileType.FILE) { // Add filename to Resultfilenames ... if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobEntryAddResultFilenames.AddingFileToResult", filefolder.toString())); } ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, KettleVFS.getFileObject(filefolder.toString(), this), 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()) { logDetailed(BaseMessages.getString(PKG, "JobEntryAddResultFilenames.AddingFileToResult", list[i].toString())); } ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, KettleVFS.getFileObject(list[i].toString(), this), parentJob.getJobname(), toString()); result.getResultFiles().put(resultFile.getFile().toString(), resultFile); } } } else { // File can not be found if (log.isBasic()) { logBasic(BaseMessages.getString(PKG, "JobEntryAddResultFilenames.FileCanNotbeFound", realFilefoldername)); } rcode = false; } } catch (Exception e) { rcode = false; logError(BaseMessages.getString(PKG, "JobEntryAddResultFilenames.CouldNotProcess", realFilefoldername, e.getMessage()), e); } finally { if (filefolder != null) { try { filefolder.close(); filefolder = null; } catch (IOException ex) { // Ignore } } } return rcode; }
From source file:org.pentaho.di.job.entries.checkfilelocked.JobEntryCheckFilesLocked.java
private void ProcessFile(String filename, String wildcard) { FileObject filefolder = null; String realFilefoldername = environmentSubstitute(filename); String realwilcard = environmentSubstitute(wildcard); try {//www. j a v a2 s . co m filefolder = KettleVFS.getFileObject(realFilefoldername); FileObject[] files = new FileObject[] { filefolder }; if (filefolder.exists()) { // the file or folder exists if (filefolder.getType() == FileType.FOLDER) { // It's a folder if (isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobEntryCheckFilesLocked.ProcessingFolder", realFilefoldername)); } // Retrieve all files files = filefolder.findFiles(new TextFileSelector(filefolder.toString(), realwilcard)); if (isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobEntryCheckFilesLocked.TotalFilesToCheck", String.valueOf(files.length))); } } else { // It's a file if (isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobEntryCheckFilesLocked.ProcessingFile", realFilefoldername)); } } // Check files locked checkFilesLocked(files); } else { // We can not find thsi file logBasic(BaseMessages.getString(PKG, "JobEntryCheckFilesLocked.FileNotExist", realFilefoldername)); } } catch (Exception e) { logError(BaseMessages.getString(PKG, "JobEntryCheckFilesLocked.CouldNotProcess", realFilefoldername, e.getMessage())); } finally { if (filefolder != null) { try { filefolder.close(); } catch (IOException ex) { // Ignore } } } }
From source file:org.pentaho.di.job.entries.copyfiles.JobEntryCopyFiles.java
private boolean ProcessFileFolder(String sourcefilefoldername, String destinationfilefoldername, String wildcard, Job parentJob, Result result) { boolean entrystatus = false; FileObject sourcefilefolder = null; FileObject destinationfilefolder = null; // Clear list files to remove after copy process // This list is also added to result files name list_files_remove.clear();/*w ww.ja va2 s . co m*/ list_add_result.clear(); // Get real source, destination file and wildcard String realSourceFilefoldername = environmentSubstitute(sourcefilefoldername); String realDestinationFilefoldername = environmentSubstitute(destinationfilefoldername); String realWildcard = environmentSubstitute(wildcard); try { sourcefilefolder = KettleVFS.getFileObject(realSourceFilefoldername, this); destinationfilefolder = KettleVFS.getFileObject(realDestinationFilefoldername, this); 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 COPY FOLDER TO FILE !!! logError(BaseMessages.getString(PKG, "JobCopyFiles.Log.CanNotCopyFolderToFile", realSourceFilefoldername, realDestinationFilefoldername)); NbrFail++; } else { if (destinationfilefolder.getType().equals(FileType.FOLDER) && sourcefilefolder.getType().equals(FileType.FILE)) { // Source is a file, destination is a folder // Copy the file to the destination folder destinationfilefolder.copyFrom(sourcefilefolder.getParent(), new TextOneFileSelector(sourcefilefolder.getParent().toString(), sourcefilefolder.getName().getBaseName(), destinationfilefolder.toString())); if (isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobCopyFiles.Log.FileCopied", sourcefilefolder.getName().toString(), destinationfilefolder.getName().toString())); } } else if (sourcefilefolder.getType().equals(FileType.FILE) && destination_is_a_file) { // Source is a file, destination is a file destinationfilefolder.copyFrom(sourcefilefolder, new TextOneToOneFileSelector(destinationfilefolder)); } else { // Both source and destination are folders if (isDetailed()) { logDetailed(" "); logDetailed(BaseMessages.getString(PKG, "JobCopyFiles.Log.FetchFolder", sourcefilefolder.toString())); } TextFileSelector textFileSelector = new TextFileSelector(sourcefilefolder, destinationfilefolder, realWildcard, parentJob); try { destinationfilefolder.copyFrom(sourcefilefolder, textFileSelector); } finally { textFileSelector.shutdown(); } } // Remove Files if needed if (remove_source_files && !list_files_remove.isEmpty()) { String sourceFilefoldername = sourcefilefolder.toString(); int trimPathLength = sourceFilefoldername.length() + 1; FileObject removeFile; for (Iterator<String> iter = list_files_remove.iterator(); iter.hasNext() && !parentJob.isStopped();) { String fileremoventry = iter.next(); removeFile = null; // re=null each iteration // Try to get the file relative to the existing connection if (fileremoventry.startsWith(sourceFilefoldername)) { if (trimPathLength < fileremoventry.length()) { removeFile = sourcefilefolder .getChild(fileremoventry.substring(trimPathLength)); } } // Unable to retrieve file through existing connection; Get the file through a new VFS connection if (removeFile == null) { removeFile = KettleVFS.getFileObject(fileremoventry, this); } // Remove ONLY Files if (removeFile.getType() == FileType.FILE) { boolean deletefile = removeFile.delete(); logBasic(" ------ "); if (!deletefile) { logError(" " + BaseMessages.getString(PKG, "JobCopyFiles.Error.Exception.CanRemoveFileFolder", fileremoventry)); } else { if (isDetailed()) { logDetailed(" " + BaseMessages.getString(PKG, "JobCopyFiles.Log.FileFolderRemoved", fileremoventry)); } } } } } // Add files to result files name if (add_result_filesname && !list_add_result.isEmpty()) { String destinationFilefoldername = destinationfilefolder.toString(); int trimPathLength = destinationFilefoldername.length() + 1; FileObject addFile; for (Iterator<String> iter = list_add_result.iterator(); iter.hasNext();) { String fileaddentry = iter.next(); addFile = null; // re=null each iteration // Try to get the file relative to the existing connection if (fileaddentry.startsWith(destinationFilefoldername)) { if (trimPathLength < fileaddentry.length()) { addFile = destinationfilefolder .getChild(fileaddentry.substring(trimPathLength)); } } // Unable to retrieve file through existing connection; Get the file through a new VFS connection if (addFile == null) { addFile = KettleVFS.getFileObject(fileaddentry, this); } // Add ONLY Files if (addFile.getType() == FileType.FILE) { ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, addFile, parentJob.getJobname(), toString()); result.getResultFiles().put(resultFile.getFile().toString(), resultFile); if (isDetailed()) { logDetailed(" ------ "); logDetailed(" " + BaseMessages.getString(PKG, "JobCopyFiles.Log.FileAddedToResultFilesName", fileaddentry)); } } } } } entrystatus = true; } else { // Destination Folder or Parent folder is missing logError(BaseMessages.getString(PKG, "JobCopyFiles.Error.DestinationFolderNotFound", realDestinationFilefoldername)); } } else { logError(BaseMessages.getString(PKG, "JobCopyFiles.Error.SourceFileNotExists", realSourceFilefoldername)); } } catch (FileSystemException fse) { logError(BaseMessages.getString(PKG, "JobCopyFiles.Error.Exception.CopyProcessFileSystemException", fse.getMessage())); Throwable throwable = fse.getCause(); while (throwable != null) { logError(BaseMessages.getString(PKG, "JobCopyFiles.Log.CausedBy", throwable.getMessage())); throwable = throwable.getCause(); } } catch (Exception e) { logError(BaseMessages.getString(PKG, "JobCopyFiles.Error.Exception.CopyProcess", realSourceFilefoldername, realDestinationFilefoldername, e.getMessage()), e); } finally { if (sourcefilefolder != null) { try { sourcefilefolder.close(); sourcefilefolder = null; } catch (IOException ex) { /* Ignore */ } } if (destinationfilefolder != null) { try { destinationfilefolder.close(); destinationfilefolder = null; } catch (IOException ex) { /* Ignore */ } } } return entrystatus; }
From source file:org.pentaho.di.job.entries.copymoveresultfilenames.JobEntryCopyMoveResultFilenames.java
public Result execute(Result previousResult, int nr) { Result result = previousResult; result.setNrErrors(1);//from w ww . ja va2 s . co m result.setResult(false); boolean deleteFile = getAction().equals("delete"); String realdestinationFolder = null; if (!deleteFile) { realdestinationFolder = environmentSubstitute(getDestinationFolder()); if (!CreateDestinationFolder(realdestinationFolder)) { return result; } } if (!Const.isEmpty(wildcard)) { wildcardPattern = Pattern.compile(environmentSubstitute(wildcard)); } if (!Const.isEmpty(wildcardexclude)) { wildcardExcludePattern = Pattern.compile(environmentSubstitute(wildcardexclude)); } 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()) { logBasic(BaseMessages.getString(PKG, "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) { logError(BaseMessages.getString(PKG, "JobEntryCopyMoveResultFilenames.Error.SuccessConditionbroken", "" + NrErrors)); throw new Exception(BaseMessages.getString(PKG, "JobEntryCopyMoveResultFilenames.Error.SuccessConditionbroken", "" + NrErrors)); } ResultFile resultFile = it.next(); file = resultFile.getFile(); if (file != null && file.exists()) { if (!specifywildcard || (CheckFileWildcard(file.getName().getBaseName(), wildcardPattern, true) && !CheckFileWildcard(file.getName().getBaseName(), wildcardExcludePattern, false) && specifywildcard)) { // Copy or Move file if (!processFile(file, realdestinationFolder, result, parentJob, deleteFile)) { // Update Errors updateErrors(); } } } else { logError(BaseMessages.getString(PKG, "JobEntryCopyMoveResultFilenames.log.ErrorCanNotFindFile", file.toString())); // Update Errors updateErrors(); } } // end for } } catch (Exception e) { logError(BaseMessages.getString(PKG, "JobEntryCopyMoveResultFilenames.Error", e.toString())); } finally { if (file != null) { try { file.close(); file = null; } catch (Exception ex) { /* Ignore */ } } } } // Success Condition result.setNrErrors(NrErrors); result.setNrLinesWritten(NrSuccess); if (getSuccessStatus()) { result.setResult(true); } return result; }
From source file:org.pentaho.di.job.entries.copymoveresultfilenames.JobEntryCopyMoveResultFilenames.java
private boolean processFile(FileObject sourcefile, String destinationFolder, Result result, Job parentJob, boolean deleteFile) { boolean retval = false; try {//w w w.j a v a 2s .c om if (deleteFile) { // delete file if (sourcefile.delete()) { if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobEntryCopyMoveResultFilenames.log.DeletedFile", sourcefile.toString())); } // Remove source file from result files list result.getResultFiles().remove(sourcefile.toString()); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobEntryCopyMoveResultFilenames.RemovedFileFromResult", sourcefile.toString())); } } else { logError(BaseMessages.getString(PKG, "JobEntryCopyMoveResultFilenames.CanNotDeletedFile", sourcefile.toString())); } } else { // return destination short filename String shortfilename = getDestinationFilename(sourcefile.getName().getBaseName()); // build full destination filename String destinationFilename = destinationFolder + Const.FILE_SEPARATOR + shortfilename; FileObject destinationfile = KettleVFS.getFileObject(destinationFilename, this); boolean filexists = destinationfile.exists(); if (filexists) { if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobEntryCopyMoveResultFilenames.Log.FileExists", destinationFilename)); } } if ((!filexists) || (filexists && isOverwriteFile())) { if (getAction().equals("copy")) { // Copy file FileUtil.copyContent(sourcefile, destinationfile); if (log.isDetailed()) { logDetailed( BaseMessages.getString(PKG, "JobEntryCopyMoveResultFilenames.log.CopiedFile", sourcefile.toString(), destinationFolder)); } } else { // Move file sourcefile.moveTo(destinationfile); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobEntryCopyMoveResultFilenames.log.MovedFile", sourcefile.toString(), destinationFolder)); } } if (isRemovedSourceFilename()) { // Remove source file from result files list result.getResultFiles().remove(sourcefile.toString()); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobEntryCopyMoveResultFilenames.RemovedFileFromResult", sourcefile.toString())); } } if (isAddDestinationFilename()) { // Add destination filename to Resultfilenames ... ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, KettleVFS.getFileObject(destinationfile.toString(), this), parentJob.getJobname(), toString()); result.getResultFiles().put(resultFile.getFile().toString(), resultFile); if (log.isDetailed()) { logDetailed( BaseMessages.getString(PKG, "JobEntryCopyMoveResultFilenames.AddedFileToResult", destinationfile.toString())); } } } } retval = true; } catch (Exception e) { logError(BaseMessages.getString(PKG, "JobEntryCopyMoveResultFilenames.Log.ErrorProcessing", e.toString())); } return retval; }