Java Code Examples for org.apache.commons.net.ftp.FTPFile

The following examples show how to use org.apache.commons.net.ftp.FTPFile. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: webcurator   Source File: FileUtils.java    License: Apache License 2.0 7 votes vote down vote up
public static void removeFTPDirectory(FTPClient ftpClient, String directoryName) {
	try {
    	ftpClient.changeWorkingDirectory(directoryName);
    	for (FTPFile file : ftpClient.listFiles()) {
    		if (file.isDirectory()) {
    			FileUtils.removeFTPDirectory(ftpClient, file.getName());
    		} else {
        	    log.debug("Deleting " + file.getName());
    			ftpClient.deleteFile(file.getName());
    		}
    	}
    	ftpClient.changeWorkingDirectory(directoryName);
    	ftpClient.changeToParentDirectory();
	    log.debug("Deleting " + directoryName);
    	ftpClient.removeDirectory(directoryName);
	} catch (Exception ex) {
		
	}
}
 
Example 2
Source Project: hadoop   Source File: FTPFileSystem.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convenience method, so that we don't open a new connection when using this
 * method from within another method. Otherwise every API invocation incurs
 * the overhead of opening/closing a TCP connection.
 */
private FileStatus[] listStatus(FTPClient client, Path file)
    throws IOException {
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  FileStatus fileStat = getFileStatus(client, absolute);
  if (fileStat.isFile()) {
    return new FileStatus[] { fileStat };
  }
  FTPFile[] ftpFiles = client.listFiles(absolute.toUri().getPath());
  FileStatus[] fileStats = new FileStatus[ftpFiles.length];
  for (int i = 0; i < ftpFiles.length; i++) {
    fileStats[i] = getFileStatus(ftpFiles[i], absolute);
  }
  return fileStats;
}
 
Example 3
public FTPInfo(FTPFile file, URI parent, URI self) throws UnsupportedEncodingException {
	this.file = file;
	this.parent = parent;
	String name = file.getName();
	Matcher m = FILENAME_PATTERN.matcher(name);
	if (m.matches()) {
		name = m.group(1); // some FTPs return full file paths as names, we want only the filename 
	}
	this.name = name;
	if (file.isDirectory() && !name.endsWith(URIUtils.PATH_SEPARATOR)) {
		name = name + URIUtils.PATH_SEPARATOR;
	}
	if (self != null) {
		this.uri = self;
	} else {
		this.uri = URIUtils.getChildURI(parent, name);
	}
}
 
Example 4
Source Project: FireFiles   Source File: NetworkFile.java    License: Apache License 2.0 6 votes vote down vote up
public NetworkFile(NetworkFile dir, FTPFile file) {
	String name = file.getName();
	String dirPath = dir.getPath();
	host = dir.host;
	this.file = file;
	if (name == null) {
		throw new NullPointerException("name == null");
	}
	if (dirPath == null || dirPath.isEmpty()) {
		this.path = fixSlashes(name);
	} else if (name.isEmpty()) {
		this.path = fixSlashes(dirPath);
	} else {
		this.path = fixSlashes(join(dirPath, name));
	}
}
 
Example 5
Source Project: desktop   Source File: FtpTransferManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public Map<String, RemoteFile> list() throws StorageException {
    connect();

    try {
        Map<String, RemoteFile> files = new HashMap<String, RemoteFile>();
        FTPFile[] ftpFiles = ftp.listFiles(getConnection().getPath());

        for (FTPFile f : ftpFiles) {
            files.put(f.getName(), new RemoteFile(f.getName(), f.getSize(), f));
            if (f.isDirectory()) {
                files.putAll(getDirectoryList(f.getName()));
            }
        }

        return files;
    } catch (IOException ex) {
        logger.error("Unable to list FTP directory.", ex);
        throw new StorageException(ex);
    }
}
 
Example 6
Source Project: netbeans   Source File: FtpClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public synchronized List<RemoteFile> listFiles() throws RemoteException {
    List<RemoteFile> result = null;
    String pwd = null;
    try {
        pwd = printWorkingDirectoryInternal();
        FTPFile[] files = ftpClient.listFiles(pwd);
        result = new ArrayList<>(files.length);
        for (FTPFile f : files) {
            // #142682
            if (f == null) {
                // hmm, really weird...
                LOGGER.log(Level.FINE, "NULL returned for listing of {0}", pwd);
                continue;
            }
            result.add(new RemoteFileImpl(f, pwd));
        }
    } catch (IOException ex) {
        WindowsJdk7WarningPanel.warn();
        LOGGER.log(Level.FINE, "Error while listing files for " + pwd, ex);
        throw new RemoteException(NbBundle.getMessage(FtpClient.class, "MSG_FtpCannotListFiles", pwd), ex, getReplyString());
    }
    scheduleKeepAlive();
    return result;
}
 
Example 7
Source Project: commons-vfs   Source File: FtpFileObject.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Lists the children of the file.
 */
@Override
protected String[] doListChildren() throws Exception {
    // List the children of this file
    doGetChildren();

    // VFS-210
    if (children == null) {
        return null;
    }

    // TODO - get rid of this children stuff
    final String[] childNames = new String[children.size()];
    int childNum = -1;
    final Iterator<FTPFile> iterChildren = children.values().iterator();
    while (iterChildren.hasNext()) {
        childNum++;
        final FTPFile child = iterChildren.next();
        childNames[childNum] = child.getName();
    }

    return UriParser.encode(childNames);
}
 
Example 8
Source Project: openbd-core   Source File: FtpExists.java    License: GNU General Public License v3.0 6 votes vote down vote up
public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException {
	cfFTPData	ftpdata	= getFTPData(_session, argStruct);

	boolean soe			= getNamedBooleanParam(argStruct, "stoponerror", true);
	boolean passive	= getNamedBooleanParam(argStruct, "passive", false);
	String	file		= getNamedStringParam(argStruct, "file", "/" );

	FTPFile[]	files;
	try{
		ftpdata.lock();
		
		ftpdata.setPassive(passive);
		files = ftpdata.listFiles(file);
		if ( soe && !ftpdata.isSucceeded() )
			throwException( _session, ftpdata.getErrorText() );
		
		if ( files == null || files.length == 0 )
			return cfBooleanData.FALSE;
		else
			return cfBooleanData.TRUE;
		
	}finally{
		ftpdata.unlock();
	}
}
 
Example 9
Source Project: mumu   Source File: FtpClient.java    License: Apache License 2.0 6 votes vote down vote up
/** 获得目录下最大文件名 */
public String getMaxFileName(String remotePath) {
	try {
		ftpClient.changeWorkingDirectory(remotePath);
		FTPFile[] files = ftpClient.listFiles();
		Arrays.sort(files, new Comparator<FTPFile>() {
			public int compare(FTPFile o1, FTPFile o2) {
				return o2.getName().compareTo(o1.getName());
			}
		});
		return files[0].getName();
	} catch (IOException e) {
		logger.error("", e);
		throw new FtpException("FTP访问目录[" + remotePath + "]出错!", e);
	}
}
 
Example 10
Source Project: commons-vfs   Source File: FtpFileObject.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Called by child file objects, to locate their ftp file info.
 *
 * @param name the file name in its native form ie. without URI stuff (%nn)
 * @param flush recreate children cache
 */
private FTPFile getChildFile(final String name, final boolean flush) throws IOException {
    /*
     * If we should flush cached children, clear our children map unless we're in the middle of a refresh in which
     * case we've just recently refreshed our children. No need to do it again when our children are refresh()ed,
     * calling getChildFile() for themselves from within getInfo(). See getChildren().
     */
    if (flush && !inRefresh.get()) {
        children = null;
    }

    // List the children of this file
    doGetChildren();

    // Look for the requested child
    // VFS-210 adds the null check.
    return children != null ? children.get(name) : null;
}
 
Example 11
Source Project: RDFS   Source File: FTPFileSystem.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert the file information in FTPFile to a {@link FileStatus} object. *
 * 
 * @param ftpFile
 * @param parentPath
 * @return FileStatus
 */
private FileStatus getFileStatus(FTPFile ftpFile, Path parentPath) {
  long length = ftpFile.getSize();
  boolean isDir = ftpFile.isDirectory();
  int blockReplication = 1;
  // Using default block size since there is no way in FTP client to know of
  // block sizes on server. The assumption could be less than ideal.
  long blockSize = DEFAULT_BLOCK_SIZE;
  long modTime = ftpFile.getTimestamp().getTimeInMillis();
  long accessTime = 0;
  FsPermission permission = getPermissions(ftpFile);
  String user = ftpFile.getUser();
  String group = ftpFile.getGroup();
  Path filePath = new Path(parentPath, ftpFile.getName());
  return new FileStatus(length, isDir, blockReplication, blockSize, modTime,
      accessTime, permission, user, group, filePath.makeQualified(this));
}
 
Example 12
@Bean
public IntegrationFlow ftpInboundFlow(FtpSinkProperties properties, SessionFactory<FTPFile> ftpSessionFactory) {
	FtpMessageHandlerSpec handlerSpec =
		Ftp.outboundAdapter(new FtpRemoteFileTemplate(ftpSessionFactory), properties.getMode())
			.remoteDirectory(properties.getRemoteDir())
			.remoteFileSeparator(properties.getRemoteFileSeparator())
			.autoCreateDirectory(properties.isAutoCreateDir())
			.temporaryFileSuffix(properties.getTmpFileSuffix());
	if (properties.getFilenameExpression() != null) {
		handlerSpec.fileNameExpression(properties.getFilenameExpression().getExpressionString());
	}
	return IntegrationFlows.from(Sink.INPUT)
		.handle(handlerSpec,
			new Consumer<GenericEndpointSpec<FileTransferringMessageHandler<FTPFile>>>() {
				@Override
				public void accept(GenericEndpointSpec<FileTransferringMessageHandler<FTPFile>> e) {
					e.autoStartup(false);
				}
			})
		.get();
}
 
Example 13
@Test
public void testUnknownSystIdentifier() {
    this.parser = new FTPParserSelector().getParser("Digital Domain FTP");

    FTPFile parsed;
    parsed = parser.parseFTPEntry(
        "drwxrwxrwx               folder        0 Jan 19 20:36 Mastered 1644"
    );
    assertNotNull(parsed);
    assertEquals("Mastered 1644", parsed.getName());
    assertEquals(FTPFile.DIRECTORY_TYPE, parsed.getType());

    parsed = parser.parseFTPEntry(
        "-rwxrwxrwx        0   208143684 208143684 Jan 14 02:13 Dhannya dhannya.rar"
    );
    assertNotNull(parsed);
    assertEquals("Dhannya dhannya.rar", parsed.getName());
    assertEquals(FTPFile.FILE_TYPE, parsed.getType());

    parsed = parser.parseFTPEntry(
        "drwxr-xr-x               folder        0 Jan 14 16:04 Probeordner");
    assertNotNull(parsed);
    assertEquals("Probeordner", parsed.getName());
    assertEquals(FTPFile.DIRECTORY_TYPE, parsed.getType());
}
 
Example 14
@Test
public void testUpperCaseMonths() {
    FTPFileEntryParser parser = new FTPParserSelector().getParser("UNIX");

    FTPFile parsed;

    parsed = parser.parseFTPEntry(
        "drwxrwxrwx    41 spinkb  spinkb      1394 Feb 21 20:57 Desktop");
    assertNotNull(parsed);
    assertEquals("Desktop", parsed.getName());
    assertEquals(FTPFile.DIRECTORY_TYPE, parsed.getType());
    assertEquals("spinkb", parsed.getUser());
    assertEquals("spinkb", parsed.getGroup());
    assertEquals(Calendar.FEBRUARY, parsed.getTimestamp().get(Calendar.MONTH));
    assertEquals(21, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH));
}
 
Example 15
@Test
public void testSolarisAcl() {
    FTPFileEntryParser parser = new FTPParserSelector().getParser("UNIX");

    FTPFile parsed;

    //#215
    parsed = parser.parseFTPEntry(
        "drwxrwsr-x+ 34 cristol  molvis      3072 Jul 12 20:16 molvis");
    assertNotNull(parsed);
    assertEquals(parsed.getName(), "molvis");
    assertEquals(FTPFile.DIRECTORY_TYPE, parsed.getType());
    assertEquals("cristol", parsed.getUser());
    assertEquals("molvis", parsed.getGroup());
    assertNotNull(parsed.getTimestamp());
    assertEquals(Calendar.JULY, parsed.getTimestamp().get(Calendar.MONTH));
    assertEquals(12, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH));
}
 
Example 16
@Test
public void testStickyBit() {
    FTPFileEntryParser parser = new FTPParserSelector().getParser("UNIX");

    FTPFile parsed;

    parsed = parser.parseFTPEntry(
        "drwxr--r-t   1 user     group          0 Feb 29 18:14 Filename"
    );
    assertNotNull(parsed);
    assertTrue(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION));

    parsed = parser.parseFTPEntry(
        "drwxr--r-T   1 user     group          0 Feb 29 18:14 Filename"
    );
    assertNotNull(parsed);
    assertFalse(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION));
}
 
Example 17
Source Project: openbd-core   Source File: cfFTPData.java    License: GNU General Public License v3.0 6 votes vote down vote up
public FTPFile[]	listFiles(String directory) {
	if ( !ftpclient.isConnected() ){
		errorText = "not connected";
		succeeded	= false;
		return null;
	}
	
	FTPFile[]	files = null;
	
	try{
		files			= ftpclient.listFiles(directory);
		errorCode = ftpclient.getReplyCode();
		succeeded	= FTPReply.isPositiveCompletion(errorCode);
	}catch(Exception e){
		errorCode = ftpclient.getReplyCode();
		errorText	= e.getMessage();
	}finally{
		setStatusData();
	}
	
	return files;
}
 
Example 18
@Test
public void testParse() {
    FTPFile parsed;

    // #3689
    parsed = parser.parseFTPEntry(
        "drwxr-xr-x+  5 niels    staff          7 Sep  6 13:46 data"
    );
    assertNotNull(parsed);
    assertEquals(parsed.getName(), "data");
    assertEquals(FTPFile.DIRECTORY_TYPE, parsed.getType());
    assertEquals(7, parsed.getSize());
    assertEquals(Calendar.SEPTEMBER, parsed.getTimestamp().get(Calendar.MONTH));
    assertEquals(6, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH));
    assertTrue(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION));
    assertTrue(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION));
    assertTrue(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION));
    assertTrue(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION));
    assertTrue(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION));
    assertTrue(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION));
    assertTrue(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION));
}
 
Example 19
/**
 * http://trac.cyberduck.ch/ticket/1198
 */
@Test
public void testFile() {
    FTPFile parsed;

    parsed = parser.parseFTPEntry(
        "-r--r--r--          0     165100     165100 Aug  1 10:24 grau2.tif"
    );
    assertNotNull(parsed);
    assertEquals("grau2.tif", parsed.getName());
    assertEquals(FTPFile.FILE_TYPE, parsed.getType());
    assertEquals(Calendar.AUGUST, parsed.getTimestamp().get(Calendar.MONTH));
    assertEquals(1, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH));
    assertEquals(10, parsed.getTimestamp().get(Calendar.HOUR_OF_DAY));
    assertEquals(24, parsed.getTimestamp().get(Calendar.MINUTE));
    assertTrue(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION));
    assertTrue(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION));
    assertTrue(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION));
    assertFalse(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION));
    assertFalse(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.WRITE_PERMISSION));
    assertFalse(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.WRITE_PERMISSION));
    assertFalse(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION));
    assertFalse(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION));
    assertFalse(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION));
}
 
Example 20
@Test
    public void testReadonlyFile() {
        FTPFile parsed = parser.parseFTPEntry("+m825718503,r,s280,\tdjb.html\r\n");

        assertEquals("djb.html", parsed.getName());
        assertFalse(parsed.isDirectory());

        assertEquals(280, parsed.getSize(), 0);

        long millis = 825718503;
        millis = millis * 1000;
        assertEquals(millis, parsed.getTimestamp().getTimeInMillis());
        assertEquals(FTPFile.FILE_TYPE, parsed.getType());
        assertFalse(parsed.isDirectory());
        assertTrue(parsed.isFile());
        assertFalse(parsed.isSymbolicLink());
//        assertEquals("owner", "Unknown", parsed.getUser());
//        assertEquals("group", "Unknown", parsed.getGroup());

//        assertEquals("permissions", "r--r--r-- (444)", parsed.attributes.getPermission().toString());
    }
 
Example 21
Source Project: FireFiles   Source File: NetworkStorageProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Cursor queryChildDocuments(String parentDocumentId, String[] projection,
                                  String sortOrder) throws FileNotFoundException {
    final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection));
    final NetworkFile parent = getFileForDocId(parentDocumentId);
    final NetworkConnection connection = getNetworkConnection(parentDocumentId);
    try {
        connection.getConnectedClient().changeWorkingDirectory(parent.getPath());
        for (FTPFile file : connection.getConnectedClient().listFiles()) {
            includeFile(result, null, new NetworkFile(parent, file));
        }
    } catch (IOException e) {
        Crashlytics.logException(e);
    }
    return result;
}
 
Example 22
Source Project: hadoop-gpu   Source File: FTPFileSystem.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convenience method, so that we don't open a new connection when using this
 * method from within another method. Otherwise every API invocation incurs
 * the overhead of opening/closing a TCP connection.
 */
private FileStatus[] listStatus(FTPClient client, Path file)
    throws IOException {
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  FileStatus fileStat = getFileStatus(client, absolute);
  if (!fileStat.isDir()) {
    return new FileStatus[] { fileStat };
  }
  FTPFile[] ftpFiles = client.listFiles(absolute.toUri().getPath());
  FileStatus[] fileStats = new FileStatus[ftpFiles.length];
  for (int i = 0; i < ftpFiles.length; i++) {
    fileStats[i] = getFileStatus(ftpFiles[i], absolute);
  }
  return fileStats;
}
 
Example 23
public FTPInfo(FTPFile file, URI parent, URI self) throws UnsupportedEncodingException {
	this.file = file;
	this.parent = parent;
	String name = file.getName();
	Matcher m = FILENAME_PATTERN.matcher(name);
	if (m.matches()) {
		name = m.group(1); // some FTPs return full file paths as names, we want only the filename 
	}
	if (name.equals("/")) {
		name = ""; // root directory has no name
	} else if (name.endsWith(URIUtils.PATH_SEPARATOR)) {
		name = name.substring(0, name.length()-1);
	}
	this.name = name;
	// name is modified just for the URI
	if (file.isDirectory() && !name.endsWith(URIUtils.PATH_SEPARATOR)) {
		name = name + URIUtils.PATH_SEPARATOR;
	}
	if (self != null) {
		this.uri = self;
	} else {
		this.uri = URIUtils.getChildURI(parent, name);
	}
}
 
Example 24
Source Project: cyberduck   Source File: HPTru64ParserTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * http://trac.cyberduck.ch/ticket/2246
 */
@Test
public void testParse() {
    FTPFile parsed;

    parsed = parser.parseFTPEntry(
        "drwxr-xr-x   7 ToysPKG  advertise   8192 Jun 24 11:58 Private Label Mock"
    );
    assertNotNull(parsed);
    assertEquals(parsed.getName(), "Private Label Mock");
    assertEquals(FTPFile.DIRECTORY_TYPE, parsed.getType());
    assertEquals("ToysPKG", parsed.getUser());
    assertEquals("advertise", parsed.getGroup());
    assertEquals(8192, parsed.getSize());
    assertEquals(Calendar.JUNE, parsed.getTimestamp().get(Calendar.MONTH));
    assertEquals(24, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH));

    parsed = parser.parseFTPEntry(
        "-rw-r--r--   1 ToysPKG  advertise24809879 Jun 25 10:54 TRU-Warning Guide Master CD.sitx"
    );
    assertNull(parsed);
}
 
Example 25
@Test
public void testParse() {
    FTPFile parsed;

    //#1213
    parsed = parser.parseFTPEntry(
        "-rw-r--r--  FTP  User       10439 Apr 20 05:29 ASCheckbox_2_0.zip"
    );
    assertNotNull(parsed);
    assertEquals("ASCheckbox_2_0.zip", parsed.getName());
    assertEquals(FTPFile.FILE_TYPE, parsed.getType());
    assertEquals(10439, parsed.getSize());
    assertEquals(Calendar.APRIL, parsed.getTimestamp().get(Calendar.MONTH));
    assertEquals(20, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH));
    assertTrue(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION));
    assertTrue(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION));
    assertTrue(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION));
    assertTrue(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION));
    assertFalse(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.WRITE_PERMISSION));
    assertFalse(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.WRITE_PERMISSION));
    assertFalse(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION));
    assertFalse(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION));
    assertFalse(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION));
}
 
Example 26
@Test
public void testParse() {
    FTPFile parsed;

    // #5437
    parsed = parser.parseFTPEntry(
        "-rw-r--r--    1 3642     3643          106 Nov 15 22:20 index.html"
    );
    assertNotNull(parsed);
    assertEquals("index.html", parsed.getName());
    assertEquals(FTPFile.FILE_TYPE, parsed.getType());
    assertEquals(106, parsed.getSize());
    assertEquals(Calendar.NOVEMBER, parsed.getTimestamp().get(Calendar.MONTH));
    assertEquals(15, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH));
    assertTrue(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION));
    assertTrue(parsed.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION));
    assertTrue(parsed.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION));
    assertTrue(parsed.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION));
}
 
Example 27
Source Project: hadoop   Source File: FTPFileSystem.java    License: Apache License 2.0 5 votes vote down vote up
private FsAction getFsAction(int accessGroup, FTPFile ftpFile) {
  FsAction action = FsAction.NONE;
  if (ftpFile.hasPermission(accessGroup, FTPFile.READ_PERMISSION)) {
    action.or(FsAction.READ);
  }
  if (ftpFile.hasPermission(accessGroup, FTPFile.WRITE_PERMISSION)) {
    action.or(FsAction.WRITE);
  }
  if (ftpFile.hasPermission(accessGroup, FTPFile.EXECUTE_PERMISSION)) {
    action.or(FsAction.EXECUTE);
  }
  return action;
}
 
Example 28
Source Project: tutorials   Source File: FtpClient.java    License: MIT License 5 votes vote down vote up
Collection<String> listFiles(String path) throws IOException {
    FTPFile[] files = ftp.listFiles(path);

    return Arrays.stream(files)
            .map(FTPFile::getName)
            .collect(Collectors.toList());
}
 
Example 29
Source Project: bamboobsc   Source File: FtpClientUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 把目錄下的檔案抓下來,如果有權限
 * 
 * @param cwdDirectory		cd 目錄
 * @param storeDir			本地端目錄
 * @param head				檔案開頭 代null或 空白 忽略
 * @param deleteFtpFile		是否刪除 FTP 上檔案(取完後刪除)
 * 
 * @throws SocketException
 * @throws IOException
 * @throws Exception
 */
public void get(String cwdDirectory, File storeDir, String head, 
		boolean deleteFtpFile) throws SocketException, IOException, Exception {
	
	if (!this.ftpClient.isConnected() ) {
		this.logger.error("FTP not connection...");
		throw new Exception("FTP not connection...");
	}				
	this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // 非 binary mode 在類 vsFtpd 可能會有問題 
	if (cwdDirectory!=null && !"".equals(cwdDirectory)) {
		this.ftpClient.cwd(cwdDirectory);
	}
	FTPFile ftpFiles[] = this.ftpClient.listFiles();		
	for (int ix=0; ftpFiles!=null && ix<ftpFiles.length; ix++) {
		if (head!=null && !"".equals(head)) {
			if (ftpFiles[ix].getName().indexOf(head)!=0) {
				logger.info("not get : " + ftpFiles[ix].getName());
				continue;
			}				
		}
		logger.info( ftpFiles[ix] );
		if (ftpFiles[ix].isFile()) {
			File downloadFile = new File(storeDir.getPath() + "/" + ftpFiles[ix].getName() );
			FileOutputStream fos = new FileOutputStream(downloadFile);
			if (this.ftpClient.retrieveFile(ftpFiles[ix].getName(), fos) ) {
				logger.info("ftp GET (save to) : " + storeDir.getPath() + "/" + ftpFiles[ix].getName());
				if (deleteFtpFile) {
					this.delete(ftpFiles[ix].getName());
				}					
			}
			downloadFile = null;
			fos.close();
			fos = null;
		}
	}		
}
 
Example 30
Source Project: anyline   Source File: FTPUtil.java    License: Apache License 2.0 5 votes vote down vote up
public List<String> files(String dir) throws IOException {   
    List<String> fileList = new ArrayList<String>();   
   
    FTPFile[] ftpFiles = client.listFiles(dir);   
    for (int i = 0; ftpFiles!=null && i<ftpFiles.length; i++) {   
        FTPFile ftpFile = ftpFiles[i];   
        if (ftpFile.isFile()) {   
            fileList.add(ftpFile.getName());   
        }   
    }   
       
    return fileList;   
}