List of usage examples for org.apache.commons.net.ftp FTPFile isDirectory
public boolean isDirectory()
From source file:com.bdaum.zoom.net.core.ftp.FtpAccount.java
@SuppressWarnings("fallthrough") private int transferFiles(FTPClient ftp, File[] files, IProgressMonitor monitor, IAdaptable adaptable, boolean deleteTransferred) throws IOException { if (monitor.isCanceled()) return -1; FTPFile[] oldfiles = ftp.listFiles(); if (monitor.isCanceled()) return -1; Map<String, FTPFile> names = new HashMap<String, FTPFile>(); for (FTPFile file : oldfiles) names.put(file.getName(), file); int n = 0;/* www.jav a 2 s . c om*/ for (File file : files) { final String filename = file.getName(); FTPFile ftpFile = names.get(filename); if (file.isDirectory()) { if (ftpFile != null) { if (!ftpFile.isDirectory()) throw new IOException( NLS.bind(Messages.FtpAccount_cannot_replace_file_with_subdir, filename)); boolean result = ftp.changeWorkingDirectory(Core.encodeUrlSegment(filename)); if (!result) throw new IOException(NLS.bind(Messages.FtpAccount_cannot_change_to_working_dir, filename)); // System.out.println(filename + " is new directory"); //$NON-NLS-1$ } else { ftp.makeDirectory(filename); boolean result = ftp.changeWorkingDirectory(Core.encodeUrlSegment(filename)); if (!result) throw new IOException(Messages.FtpAccount_creation_of_subdir_failed); // System.out.println(filename + " is new directory"); //$NON-NLS-1$ } if (monitor.isCanceled()) return -1; int c = transferFiles(ftp, file.listFiles(), monitor, adaptable, deleteTransferred); if (c < 0) return -1; n += c; ftp.changeToParentDirectory(); // System.out.println("Returned to parent directory"); //$NON-NLS-1$ } else { if (ftpFile != null) { if (ftpFile.isDirectory()) throw new IOException( NLS.bind(Messages.FtpAccount_cannot_replace_subdir_with_file, filename)); if (skipAll) { if (deleteTransferred) file.delete(); continue; } if (!replaceAll) { if (monitor.isCanceled()) return -1; int ret = 4; IDbErrorHandler errorHandler = Core.getCore().getErrorHandler(); if (errorHandler != null) { String[] buttons = (filecount > 1) ? new String[] { Messages.FtpAccount_overwrite, Messages.FtpAccount_overwrite_all, IDialogConstants.SKIP_LABEL, Messages.FtpAccount_skip_all, IDialogConstants.CANCEL_LABEL } : new String[] { Messages.FtpAccount_overwrite, IDialogConstants.SKIP_LABEL, IDialogConstants.CANCEL_LABEL }; ret = errorHandler.showMessageDialog(Messages.FtpAccount_file_already_exists, null, NLS.bind(Messages.FtpAccount_file_exists_overwrite, filename), MessageDialog.QUESTION, buttons, 0, adaptable); } if (filecount > 1) { switch (ret) { case 0: break; case 1: replaceAll = true; break; case 3: skipAll = true; /* FALL-THROUGH */ case 2: if (deleteTransferred) file.delete(); continue; default: return -1; } } else { switch (ret) { case 0: break; case 1: if (deleteTransferred) file.delete(); continue; default: return -1; } } } ftp.deleteFile(Core.encodeUrlSegment(filename)); // System.out.println(filename + " deleted"); //$NON-NLS-1$ } try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) { ftp.storeFile(Core.encodeUrlSegment(filename), in); // System.out.println(filename + " stored"); //$NON-NLS-1$ n++; } finally { if (deleteTransferred) file.delete(); monitor.worked(1); } } } return n; }
From source file:com.clickha.nifi.processors.util.FTPTransferV2.java
private List<FileInfo> getListing(final String path, final int depth, final int maxResults) throws IOException { final List<FileInfo> listing = new ArrayList<>(); if (maxResults < 1) { return listing; }/*from ww w .ja v a 2 s . c o m*/ if (depth >= 100) { logger.warn(this + " had to stop recursively searching directories at a recursive depth of " + depth + " to avoid memory issues"); return listing; } final boolean ignoreDottedFiles = ctx.getProperty(FileTransferV2.IGNORE_DOTTED_FILES).asBoolean(); final boolean recurse = ctx.getProperty(FileTransferV2.RECURSIVE_SEARCH).asBoolean(); final String fileFilterRegex = ctx.getProperty(FileTransferV2.FILE_FILTER_REGEX).getValue(); final Pattern pattern = (fileFilterRegex == null) ? null : Pattern.compile(fileFilterRegex); final String pathFilterRegex = ctx.getProperty(FileTransferV2.PATH_FILTER_REGEX).getValue(); final Pattern pathPattern = (!recurse || pathFilterRegex == null) ? null : Pattern.compile(pathFilterRegex); final String remotePath = ctx.getProperty(FileTransferV2.REMOTE_PATH).evaluateAttributeExpressions() .getValue(); // check if this directory path matches the PATH_FILTER_REGEX boolean pathFilterMatches = true; if (pathPattern != null) { Path reldir = path == null ? Paths.get(".") : Paths.get(path); if (remotePath != null) { reldir = Paths.get(remotePath).relativize(reldir); } if (reldir != null && !reldir.toString().isEmpty()) { if (!pathPattern.matcher(reldir.toString().replace("\\", "/")).matches()) { pathFilterMatches = false; } } } final FTPClient client = getClient(null); int count = 0; final FTPFile[] files; if (path == null || path.trim().isEmpty()) { files = client.listFiles("."); } else { files = client.listFiles(path); } if (files.length == 0 && path != null && !path.trim().isEmpty()) { // throw exception if directory doesn't exist final boolean cdSuccessful = setWorkingDirectory(path); if (!cdSuccessful) { throw new IOException("Cannot list files for non-existent directory " + path); } } for (final FTPFile file : files) { final String filename = file.getName(); if (filename.equals(".") || filename.equals("..")) { continue; } if (ignoreDottedFiles && filename.startsWith(".")) { continue; } final File newFullPath = new File(path, filename); final String newFullForwardPath = newFullPath.getPath().replace("\\", "/"); if (recurse && file.isDirectory()) { try { listing.addAll(getListing(newFullForwardPath, depth + 1, maxResults - count)); } catch (final IOException e) { logger.error( "Unable to get listing from " + newFullForwardPath + "; skipping this subdirectory"); } } // if is not a directory and is not a link and it matches // FILE_FILTER_REGEX - then let's add it if (!file.isDirectory() && !file.isSymbolicLink() && pathFilterMatches) { if (pattern == null || pattern.matcher(filename).matches()) { listing.add(newFileInfo(file, path)); count++; } } if (count >= maxResults) { break; } } return listing; }
From source file:com.sos.VirtualFileSystem.FTP.SOSVfsFtp.java
/** * return a listing of a directory in long format on * the remote machine/*from www. j a v a 2 s . co m*/ * * @param pathname on remote machine * @return a listing of the contents of a directory on the remote machine * @exception Exception * @see #nList() * @see #nList( String ) * @see #dir() */ @Override public SOSFileList dir(final String pathname, final int flag) { @SuppressWarnings("unused") final String conMethodName = conClassName + "::dir"; SOSFileList fileList = new SOSFileList(); FTPFile[] listFiles = null; try { listFiles = Client().listFiles(pathname); } catch (IOException e) { RaiseException(e, HostID(SOSVfs_E_0105.params(conMethodName))); } for (FTPFile listFile : listFiles) { if (flag > 0 && listFile.isDirectory()) { fileList.addAll(this.dir(pathname + "/" + listFile.toString(), flag >= 1024 ? flag : flag + 1024)); } else { if (flag >= 1024) { fileList.add(pathname + "/" + listFile.toString()); } else { fileList.add(listFile.toString()); } } } return fileList; }
From source file:madkitgroupextension.export.Export.java
public static void updateFTP(FTPClient ftpClient, String _directory_dst, File _directory_src, File _current_file_transfert) throws IOException, TransfertException { ftpClient.changeWorkingDirectory("./"); FTPListParseEngine ftplpe = ftpClient.initiateListParsing(_directory_dst); FTPFile files[] = ftplpe.getFiles(); File current_file_transfert = _current_file_transfert; try {/* w w w. ja v a2 s. c om*/ for (File f : _directory_src.listFiles()) { if (f.isDirectory()) { if (!f.getName().equals("./") && !f.getName().equals("../")) { if (_current_file_transfert != null) { if (!_current_file_transfert.getCanonicalPath().startsWith(f.getCanonicalPath())) continue; else _current_file_transfert = null; } boolean found = false; for (FTPFile ff : files) { if (f.getName().equals(ff.getName())) { if (ff.isFile()) { ftpClient.deleteFile(_directory_dst + ff.getName()); } else found = true; break; } } if (!found) { ftpClient.changeWorkingDirectory("./"); if (!ftpClient.makeDirectory(_directory_dst + f.getName() + "/")) System.err.println( "Impossible to create directory " + _directory_dst + f.getName() + "/"); } updateFTP(ftpClient, _directory_dst + f.getName() + "/", f, _current_file_transfert); } } else { if (_current_file_transfert != null) { if (!_current_file_transfert.equals(f.getCanonicalPath())) continue; else _current_file_transfert = null; } current_file_transfert = _current_file_transfert; FTPFile found = null; for (FTPFile ff : files) { if (f.getName().equals(ff.getName())) { if (ff.isDirectory()) { FileTools.removeDirectory(ftpClient, _directory_dst + ff.getName()); } else found = ff; break; } } if (found == null || (found.getTimestamp().getTimeInMillis() - f.lastModified()) < 0 || found.getSize() != f.length()) { FileInputStream fis = new FileInputStream(f); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (!ftpClient.storeFile(_directory_dst + f.getName(), fis)) System.err.println("Impossible to send file: " + _directory_dst + f.getName()); fis.close(); for (FTPFile ff : ftplpe.getFiles()) { if (f.getName().equals(ff.getName())) { f.setLastModified(ff.getTimestamp().getTimeInMillis()); break; } } } } } } catch (IOException e) { throw new TransfertException(current_file_transfert, null, e); } for (FTPFile ff : files) { if (!ff.getName().equals(".") && !ff.getName().equals("..")) { boolean found = false; for (File f : _directory_src.listFiles()) { if (f.getName().equals(ff.getName()) && f.isDirectory() == ff.isDirectory()) { found = true; break; } } if (!found) { if (ff.isDirectory()) { FileTools.removeDirectory(ftpClient, _directory_dst + ff.getName()); } else { ftpClient.deleteFile(_directory_dst + ff.getName()); } } } } }
From source file:lucee.runtime.tag.Ftp.java
/** * List data of a ftp connection/*from w w w . ja v a 2s .c o m*/ * @return FTPCLient * @throws PageException * @throws IOException */ private FTPClient actionListDir() throws PageException, IOException { required("name", name); required("directory", directory); FTPClient client = getClient(); FTPFile[] files = client.listFiles(directory); if (files == null) files = new FTPFile[0]; String[] cols = new String[] { "attributes", "isdirectory", "lastmodified", "length", "mode", "name", "path", "url", "type", "raw" }; String[] types = new String[] { "VARCHAR", "BOOLEAN", "DATE", "DOUBLE", "VARCHAR", "VARCHAR", "VARCHAR", "VARCHAR", "VARCHAR", "VARCHAR" }; lucee.runtime.type.Query query = new QueryImpl(cols, types, 0, "query"); // translate directory path for display if (directory.length() == 0) directory = "/"; else if (directory.startsWith("./")) directory = directory.substring(1); else if (directory.charAt(0) != '/') directory = '/' + directory; if (directory.charAt(directory.length() - 1) != '/') directory = directory + '/'; pageContext.setVariable(name, query); int row = 0; for (int i = 0; i < files.length; i++) { FTPFile file = files[i]; if (file.getName().equals(".") || file.getName().equals("..")) continue; query.addRow(); row++; query.setAt("attributes", row, ""); query.setAt("isdirectory", row, Caster.toBoolean(file.isDirectory())); query.setAt("lastmodified", row, new DateTimeImpl(file.getTimestamp())); query.setAt("length", row, Caster.toDouble(file.getSize())); query.setAt("mode", row, FTPConstant.getPermissionASInteger(file)); query.setAt("type", row, FTPConstant.getTypeAsString(file.getType())); //query.setAt("permission",row,FTPConstant.getPermissionASInteger(file)); query.setAt("raw", row, file.getRawListing()); query.setAt("name", row, file.getName()); query.setAt("path", row, directory + file.getName()); query.setAt("url", row, "ftp://" + client.getRemoteAddress().getHostName() + "" + directory + file.getName()); } writeCfftp(client); return client; }
From source file:ch.cyberduck.core.ftp.parser.UnixFTPEntryParserTest.java
/** * http://trac.cyberduck.ch/ticket/143/*from w w w .j a va 2 s .c o m*/ */ @Test public void testLeadingWhitespace() { FTPFileEntryParser parser = new FTPParserSelector().getParser("UNIX"); FTPFile parsed; parsed = parser.parseFTPEntry("-rw-r--r-- 1 20708 205 3553312 Feb 18 2005 D3I0_515.fmr"); assertNotNull(parsed); assertTrue(parsed.isFile()); assertEquals("D3I0_515.fmr", parsed.getName()); assertEquals("20708", parsed.getUser()); assertEquals("205", parsed.getGroup()); assertNotNull(parsed.getTimestamp()); assertEquals(Calendar.FEBRUARY, parsed.getTimestamp().get(Calendar.MONTH)); assertEquals(18, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH)); assertEquals(2005, parsed.getTimestamp().get(Calendar.YEAR)); parsed = parser.parseFTPEntry("drwxr-sr-x 14 17037 209 4096 Oct 6 2000 v3r7"); assertNotNull(parsed); assertTrue(parsed.isDirectory()); assertEquals("v3r7", parsed.getName()); assertEquals("17037", parsed.getUser()); assertEquals("209", parsed.getGroup()); assertNotNull(parsed.getTimestamp()); assertEquals(Calendar.OCTOBER, parsed.getTimestamp().get(Calendar.MONTH)); assertEquals(6, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH)); assertEquals(2000, parsed.getTimestamp().get(Calendar.YEAR)); // #2895 parsed = parser.parseFTPEntry("-rwx------ 1 user group 38635 Jul 13 2006 users.xml"); assertNotNull(parsed); assertEquals(FTPFile.FILE_TYPE, parsed.getType()); assertEquals("users.xml", parsed.getName()); assertEquals("user", parsed.getUser()); assertEquals("group", parsed.getGroup()); assertNotNull(parsed.getTimestamp()); assertEquals(Calendar.JULY, parsed.getTimestamp().get(Calendar.MONTH)); assertEquals(13, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH)); assertEquals(2006, parsed.getTimestamp().get(Calendar.YEAR)); }
From source file:adams.core.io.lister.FtpDirectoryLister.java
/** * Performs the recursive search. Search goes deeper if != 0 (use -1 to * start with for infinite search).//from w w w. j a va2s .c om * * @param client the client to use * @param current the current directory * @param files the files collected so far * @param depth the depth indicator (searched no deeper, if 0) * @throws Exception if listing fails */ protected void search(FTPClient client, String current, List<SortContainer> files, int depth) throws Exception { List<FTPFile> currFiles; int i; FTPFile entry; SortContainer cont; if (depth == 0) return; if (getDebug()) getLogger().info("search: current=" + current + ", depth=" + depth); client.changeWorkingDirectory(current); currFiles = new ArrayList<>(); currFiles.addAll(Arrays.asList(client.listFiles())); if (currFiles.size() == 0) { if (getDebug()) getLogger().info("No files listed!"); return; } for (i = 0; i < currFiles.size(); i++) { // do we have to stop? if (m_Stopped) break; entry = currFiles.get(i); // directory? if (entry.isDirectory()) { // ignore "." and ".." if (entry.getName().equals(".") || entry.getName().equals("..")) continue; // search recursively? if (m_Recursive) search(client, current + "/" + entry.getName(), files, depth - 1); if (m_ListDirs) { // does name match? if (!m_RegExp.isEmpty() && !m_RegExp.isMatch(entry.getName())) continue; files.add(new SortContainer(new FtpFileObject(current, entry, m_Client), m_Sorting)); } } else { if (m_ListFiles) { // does name match? if (!m_RegExp.isEmpty() && !m_RegExp.isMatch(entry.getName())) continue; files.add(new SortContainer(new FtpFileObject(current, entry, m_Client), m_Sorting)); } } } }
From source file:it.greenvulcano.util.remotefs.ftp.FTPManager.java
/** * @see it.greenvulcano.util.remotefs.RemoteManager#getDir(String, String, * String, java.util.Map)//ww w. ja v a 2s . co m */ @Override public boolean getDir(String remoteDirectory, String localParentDirectory, String localDirectory, Map<String, String> optProperties) throws RemoteManagerException { checkConnected(); boolean oldAutoConnect = isAutoconnect(); setAutoconnect(false); boolean result = false; try { changeWorkingDirectory(remoteDirectory); String currentlyDownloading = ftpClient.printWorkingDirectory(); if ((localDirectory == null) || localDirectory.equals("")) { localDirectory = new File(remoteDirectory).getName(); } File localDirectoryObj = new File(localParentDirectory, localDirectory); if (!localDirectoryObj.exists()) { if (!localDirectoryObj.mkdir()) { throw new RemoteManagerException( "Cannot create local directory " + localDirectoryObj.getAbsolutePath()); } logger.debug("Local directory " + localDirectoryObj.getAbsolutePath() + " created"); } FTPFile[] results = ftpClient.listFiles(); if (results != null) { for (FTPFile currFTPFile : results) { if (currFTPFile != null) { boolean partialResult = true; if (currFTPFile.isDirectory()) { partialResult = getDir(currFTPFile.getName(), localDirectoryObj.getAbsolutePath(), null, optProperties); } else { partialResult = get(null, currFTPFile.getName(), localDirectoryObj.getAbsolutePath(), null, optProperties); } if (!partialResult) { break; } } else { logger.debug("Remote file entry NULL"); } } } ftpClient.changeToParentDirectory(); int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { logger.debug("Remote directory " + currentlyDownloading + " downloaded"); result = true; } else { logger.warn("Could not download remote directory " + currentlyDownloading + " (FTP Server NEGATIVE response):"); logServerReply(Level.WARN); } return result; } catch (RemoteManagerException exc) { throw exc; } catch (IOException exc) { throw new RemoteManagerException("I/O error", exc); } catch (Exception exc) { throw new RemoteManagerException("Generic error", exc); } finally { setAutoconnect(oldAutoConnect); if (isAutoconnect()) { disconnect(); } } }
From source file:it.greenvulcano.util.remotefs.ftp.FTPManager.java
/** * @see it.greenvulcano.util.remotefs.RemoteManager#rm(String, String, java.util.Map) */// www . j av a 2 s . c o m @Override public boolean rm(String remoteDirectory, String entryNamePattern, Map<String, String> optProperties) throws RemoteManagerException { checkConnected(); boolean oldAutoConnect = isAutoconnect(); setAutoconnect(false); boolean result = false; try { if (remoteDirectory != null) { changeWorkingDirectory(remoteDirectory); } String[] filenames = ftpClient.listNames(); int detectedFiles = (filenames != null ? filenames.length : 0); FTPFile[] results = ftpClient.listFiles(); int parsedFiles = (results != null ? results.length : 0); if (detectedFiles != parsedFiles) { logger.warn("Some of all of the detected (" + detectedFiles + ") file entries couldn't be parsed (" + parsedFiles + "), recursive delete may fail"); } if (results != null) { RegExFileFilter fileFilter = new RegExFileFilter(entryNamePattern, RegExFileFilter.ALL, -1); for (FTPFile currFTPFile : results) { if (currFTPFile != null) { if (fileFilter.accept(currFTPFile)) { if (currFTPFile.isDirectory()) { result = rm(currFTPFile.getName(), ".*", optProperties); // remove all sub-directory content ftpClient.changeToParentDirectory(); if (result) { ftpClient.removeDirectory(currFTPFile.getName()); int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { logger.debug("Remote directory " + currFTPFile.getName() + " deleted."); result = true; } else { logger.warn("FTP Server NEGATIVE response: "); logServerReply(Level.WARN); } } } else { ftpClient.deleteFile(currFTPFile.getName()); int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { logger.debug("Remote file " + currFTPFile.getName() + " deleted."); result = true; } else { logger.warn("FTP Server NEGATIVE response: "); logServerReply(Level.WARN); } } if (!result) { break; } } } } } return result; } catch (IOException exc) { throw new RemoteManagerException("I/O error", exc); } catch (Exception exc) { throw new RemoteManagerException("Generic error", exc); } finally { setAutoconnect(oldAutoConnect); if (isAutoconnect()) { disconnect(); } } }
From source file:it.greenvulcano.util.remotefs.ftp.FTPManager.java
/** * @see it.greenvulcano.util.remotefs.RemoteManager#get(String, String, * String, java.util.Map)/*from w w w. j a va 2 s .c o m*/ */ @Override public boolean get(String remoteDirectory, String remoteFilePattern, String localDirectory, Map<String, String> optProperties) throws RemoteManagerException { checkConnected(); boolean oldAutoConnect = isAutoconnect(); setAutoconnect(false); boolean result = false; try { changeWorkingDirectory(remoteDirectory); String currentlyDownloading = ftpClient.printWorkingDirectory(); File localDirectoryObj = new File(localDirectory); if (!localDirectoryObj.exists()) { if (!localDirectoryObj.mkdir()) { throw new RemoteManagerException( "Cannot create local directory " + localDirectoryObj.getAbsolutePath()); } logger.debug("Local directory " + localDirectoryObj.getAbsolutePath() + " created"); } FTPFile[] results = ftpClient.listFiles(); if (results != null) { RegExFileFilter fileFilter = new RegExFileFilter(remoteFilePattern, RegExFileFilter.ALL, -1); for (FTPFile currFTPFile : results) { if (currFTPFile != null) { if (fileFilter.accept(currFTPFile)) { boolean partialResult = true; if (currFTPFile.isDirectory()) { partialResult = getDir(currFTPFile.getName(), localDirectoryObj.getAbsolutePath(), null, optProperties); } else { partialResult = get(null, currFTPFile.getName(), localDirectoryObj.getAbsolutePath(), null, optProperties); } if (!partialResult) { break; } } } else { logger.debug("Remote file entry NULL"); } } } int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { logger.debug("Remote directory " + currentlyDownloading + " downloaded"); result = true; } else { logger.warn("Could not download remote directory " + currentlyDownloading + " (FTP Server NEGATIVE response):"); logServerReply(Level.WARN); } return result; } catch (RemoteManagerException exc) { throw exc; } catch (IOException exc) { throw new RemoteManagerException("I/O error", exc); } catch (Exception exc) { throw new RemoteManagerException("Generic error", exc); } finally { setAutoconnect(oldAutoConnect); if (isAutoconnect()) { disconnect(); } } }