Java Code Examples for org.apache.commons.net.ftp.FTPClient#changeWorkingDirectory()

The following examples show how to use org.apache.commons.net.ftp.FTPClient#changeWorkingDirectory() . 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 File: FileUtils.java    From webcurator with 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 File: FtpConnection.java    From xian with Apache License 2.0 6 votes vote down vote up
FTPClient connect(String path, String addr, int port, String username, String password) throws Exception {
    FTPClient ftp = new FTPClient();
    int reply;
    ftp.connect(addr, port);
    ftp.login(username, password);
    ftp.configure(new FTPClientConfig(ftp.getSystemType()));
    ftp.setControlEncoding("UTF-8");
    ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
    reply = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        return null;
    }
    ftp.changeWorkingDirectory(path);
    return ftp;
}
 
Example 3
Source File: FTPFileSystem.java    From RDFS with 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.
 * 
 * @param client
 * @param src
 * @param dst
 * @return
 * @throws IOException
 */
private boolean rename(FTPClient client, Path src, Path dst)
    throws IOException {
  Path workDir = new Path(client.printWorkingDirectory());
  Path absoluteSrc = makeAbsolute(workDir, src);
  Path absoluteDst = makeAbsolute(workDir, dst);
  if (!exists(client, absoluteSrc)) {
    throw new IOException("Source path " + src + " does not exist");
  }
  if (exists(client, absoluteDst)) {
    throw new IOException("Destination path " + dst
        + " already exist, cannot rename!");
  }
  String parentSrc = absoluteSrc.getParent().toUri().toString();
  String parentDst = absoluteDst.getParent().toUri().toString();
  String from = src.getName();
  String to = dst.getName();
  if (!parentSrc.equals(parentDst)) {
    throw new IOException("Cannot rename parent(source): " + parentSrc
        + ", parent(destination):  " + parentDst);
  }
  client.changeWorkingDirectory(parentSrc);
  boolean renamed = client.rename(from, to);
  return renamed;
}
 
Example 4
Source File: FTPFileSystem.java    From big-c with 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 boolean mkdirs(FTPClient client, Path file, FsPermission permission)
    throws IOException {
  boolean created = true;
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  String pathName = absolute.getName();
  if (!exists(client, absolute)) {
    Path parent = absolute.getParent();
    created = (parent == null || mkdirs(client, parent, FsPermission
        .getDirDefault()));
    if (created) {
      String parentDir = parent.toUri().getPath();
      client.changeWorkingDirectory(parentDir);
      created = created && client.makeDirectory(pathName);
    }
  } else if (isFile(client, absolute)) {
    throw new ParentNotDirectoryException(String.format(
        "Can't make directory for path %s since it is a file.", absolute));
  }
  return created;
}
 
Example 5
Source File: FTPFileSystem.java    From RDFS with 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 boolean mkdirs(FTPClient client, Path file, FsPermission permission)
    throws IOException {
  boolean created = true;
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  String pathName = absolute.getName();
  if (!exists(client, absolute)) {
    Path parent = absolute.getParent();
    created = (parent == null || mkdirs(client, parent, FsPermission
        .getDefault()));
    if (created) {
      String parentDir = parent.toUri().getPath();
      client.changeWorkingDirectory(parentDir);
      created = created & client.makeDirectory(pathName);
    }
  } else if (isFile(client, absolute)) {
    throw new IOException(String.format(
        "Can't make directory for path %s since it is a file.", absolute));
  }
  return created;
}
 
Example 6
Source File: Scar.java    From scar with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static public boolean ftpUpload (String server, String user, String password, String dir, Paths paths, boolean passive)
	throws IOException {
	FTPClient ftp = new FTPClient();
	InetAddress address = InetAddress.getByName(server);
	if (DEBUG) debug("scar", "Connecting to FTP server: " + address);
	ftp.connect(address);
	if (passive) ftp.enterLocalPassiveMode();
	if (!ftp.login(user, password)) {
		if (ERROR) error("scar", "FTP login failed for user: " + user);
		return false;
	}
	if (!ftp.changeWorkingDirectory(dir)) {
		if (ERROR) error("scar", "FTP directory change failed: " + dir);
		return false;
	}
	ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
	for (String path : paths) {
		if (INFO) info("scar", "FTP upload: " + path);
		BufferedInputStream input = new BufferedInputStream(new FileInputStream(path));
		try {
			ftp.storeFile(new File(path).getName(), input);
		} finally {
			try {
				input.close();
			} catch (Exception ignored) {
			}
		}
	}
	ftp.logout();
	ftp.disconnect();
	return true;
}
 
Example 7
Source File: FTPFileSystem.java    From RDFS with Apache License 2.0 5 votes vote down vote up
@Override
public FSDataInputStream open(Path file, int bufferSize) throws IOException {
  FTPClient client = connect();
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  FileStatus fileStat = getFileStatus(client, absolute);
  if (fileStat.isDir()) {
    disconnect(client);
    throw new IOException("Path " + file + " is a directory.");
  }
  client.allocate(bufferSize);
  Path parent = absolute.getParent();
  // Change to parent directory on the
  // server. Only then can we read the
  // file
  // on the server by opening up an InputStream. As a side effect the working
  // directory on the server is changed to the parent directory of the file.
  // The FTP client connection is closed when close() is called on the
  // FSDataInputStream.
  client.changeWorkingDirectory(parent.toUri().getPath());
  InputStream is = client.retrieveFileStream(file.getName());
  FSDataInputStream fis = new FSDataInputStream(new FTPInputStream(is,
      client, statistics));
  if (!FTPReply.isPositivePreliminary(client.getReplyCode())) {
    // The ftpClient is an inconsistent state. Must close the stream
    // which in turn will logout and disconnect from FTP server
    fis.close();
    throw new IOException("Unable to open file: " + file + ", Aborting");
  }
  return fis;
}
 
Example 8
Source File: Utils.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
/**
 * Uploads a file to an Azure web app.
 * @param profile the publishing profile for the web app.
 * @param fileName the name of the file on server
 * @param file the local file
 */
public static void uploadFileToWebApp(PublishingProfile profile, String fileName, InputStream file) {
    FTPClient ftpClient = new FTPClient();
    String[] ftpUrlSegments = profile.ftpUrl().split("/", 2);
    String server = ftpUrlSegments[0];
    String path = "./site/wwwroot/webapps";
    if (fileName.contains("/")) {
        int lastslash = fileName.lastIndexOf('/');
        path = path + "/" + fileName.substring(0, lastslash);
        fileName = fileName.substring(lastslash + 1);
    }
    try {
        ftpClient.connect(server);
        ftpClient.login(profile.ftpUsername(), profile.ftpPassword());
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        for (String segment : path.split("/")) {
            if (!ftpClient.changeWorkingDirectory(segment)) {
                ftpClient.makeDirectory(segment);
                ftpClient.changeWorkingDirectory(segment);
            }
        }
        ftpClient.storeFile(fileName, file);
        ftpClient.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 9
Source File: FtpUtil.java    From learning-taotaoMall with MIT License 5 votes vote down vote up
/** 
 * Description: 从FTP服务器下载文件 
 * @param host FTP服务器hostname 
 * @param port FTP服务器端口 
 * @param username FTP登录账号 
 * @param password FTP登录密码 
 * @param remotePath FTP服务器上的相对路径 
 * @param fileName 要下载的文件名 
 * @param localPath 下载后保存到本地的路径 
 * @return 
 */
public static boolean downloadFile(String host, int port, String username, String password, String remotePath, String fileName, String localPath) {
	boolean result = false;
	FTPClient ftp = new FTPClient();
	try {
		int reply;
		ftp.connect(host, port);
		// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
		ftp.login(username, password);// 登录
		reply = ftp.getReplyCode();
		if (!FTPReply.isPositiveCompletion(reply)) {
			ftp.disconnect();
			return result;
		}
		ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
		FTPFile[] fs = ftp.listFiles();
		for (FTPFile ff : fs) {
			if (ff.getName().equals(fileName)) {
				File localFile = new File(localPath + "/" + ff.getName());

				OutputStream is = new FileOutputStream(localFile);
				ftp.retrieveFile(ff.getName(), is);
				is.close();
			}
		}

		ftp.logout();
		result = true;
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		if (ftp.isConnected()) {
			try {
				ftp.disconnect();
			} catch (IOException ioe) {
			}
		}
	}
	return result;
}
 
Example 10
Source File: AppServiceTest.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
/**
 * Uploads a file to an Azure web app.
 * @param profile the publishing profile for the web app.
 * @param fileName the name of the file on server
 * @param file the local file
 */
public static void uploadFileToWebApp(PublishingProfile profile, String fileName, InputStream file) {
    FTPClient ftpClient = new FTPClient();
    String[] ftpUrlSegments = profile.ftpUrl().split("/", 2);
    String server = ftpUrlSegments[0];
    String path = "./site/wwwroot/webapps";
    if (fileName.contains("/")) {
        int lastslash = fileName.lastIndexOf('/');
        path = path + "/" + fileName.substring(0, lastslash);
        fileName = fileName.substring(lastslash + 1);
    }
    try {
        ftpClient.connect(server);
        ftpClient.login(profile.ftpUsername(), profile.ftpPassword());
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        for (String segment : path.split("/")) {
            if (!ftpClient.changeWorkingDirectory(segment)) {
                ftpClient.makeDirectory(segment);
                ftpClient.changeWorkingDirectory(segment);
            }
        }
        ftpClient.storeFile(fileName, file);
        ftpClient.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 11
Source File: MyFtp.java    From axelor-open-suite with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void getDataFiles(
    String server,
    String username,
    String password,
    String folder,
    String destinationFolder,
    Calendar start,
    Calendar end) {

  try {

    // Connect and logon to FTP Server
    FTPClient ftp = new FTPClient();
    ftp.connect(server);
    ftp.login(username, password);

    // List the files in the directory
    ftp.changeWorkingDirectory(folder);
    FTPFile[] files = ftp.listFiles();
    getDataFile(files, destinationFolder, start, end, ftp);
    // Logout from the FTP Server and disconnect
    ftp.logout();
    ftp.disconnect();

  } catch (Exception e) {

    LOG.error(e.getMessage());
  }
}
 
Example 12
Source File: FTPFileSystem.java    From hadoop-gpu with Apache License 2.0 5 votes vote down vote up
@Override
public FSDataInputStream open(Path file, int bufferSize) throws IOException {
  FTPClient client = connect();
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  FileStatus fileStat = getFileStatus(client, absolute);
  if (fileStat.isDir()) {
    disconnect(client);
    throw new IOException("Path " + file + " is a directory.");
  }
  client.allocate(bufferSize);
  Path parent = absolute.getParent();
  // Change to parent directory on the
  // server. Only then can we read the
  // file
  // on the server by opening up an InputStream. As a side effect the working
  // directory on the server is changed to the parent directory of the file.
  // The FTP client connection is closed when close() is called on the
  // FSDataInputStream.
  client.changeWorkingDirectory(parent.toUri().getPath());
  InputStream is = client.retrieveFileStream(file.getName());
  FSDataInputStream fis = new FSDataInputStream(new FTPInputStream(is,
      client, statistics));
  if (!FTPReply.isPositivePreliminary(client.getReplyCode())) {
    // The ftpClient is an inconsistent state. Must close the stream
    // which in turn will logout and disconnect from FTP server
    fis.close();
    throw new IOException("Unable to open file: " + file + ", Aborting");
  }
  return fis;
}
 
Example 13
Source File: FTPUploader.java    From azure-gradle-plugins with MIT License 5 votes vote down vote up
/**
 * Recursively upload a directory to FTP server with the provided FTP client object.
 *
 * @param sourceDirectoryPath
 * @param targetDirectoryPath
 * @param logPrefix
 * @throws IOException
 */
protected void uploadDirectory(final FTPClient ftpClient, final String sourceDirectoryPath,
                               final String targetDirectoryPath, final String logPrefix) throws IOException {
    logger.quiet(String.format(UPLOAD_DIR, logPrefix, sourceDirectoryPath, targetDirectoryPath));
    final File sourceDirectory = new File(sourceDirectoryPath);
    final File[] files = sourceDirectory.listFiles();
    if (files == null || files.length == 0) {
        logger.quiet(String.format("%sEmpty directory at %s", logPrefix, sourceDirectoryPath));
        return;
    }

    // Make sure target directory exists
    final boolean isTargetDirectoryExist = ftpClient.changeWorkingDirectory(targetDirectoryPath);
    if (!isTargetDirectoryExist) {
        ftpClient.makeDirectory(targetDirectoryPath);
    }

    final String nextLevelPrefix = logPrefix + "..";
    for (File file : files) {
        if (file.isFile()) {
            uploadFile(ftpClient, file.getAbsolutePath(), targetDirectoryPath, nextLevelPrefix);
        } else {
            uploadDirectory(ftpClient, Paths.get(sourceDirectoryPath, file.getName()).toString(),
                    targetDirectoryPath + "/" + file.getName(), nextLevelPrefix);
        }
    }
}
 
Example 14
Source File: FTPFileSystem.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Override
public FSDataInputStream open(Path file, int bufferSize) throws IOException {
  FTPClient client = connect();
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  FileStatus fileStat = getFileStatus(client, absolute);
  if (fileStat.isDirectory()) {
    disconnect(client);
    throw new FileNotFoundException("Path " + file + " is a directory.");
  }
  client.allocate(bufferSize);
  Path parent = absolute.getParent();
  // Change to parent directory on the
  // server. Only then can we read the
  // file
  // on the server by opening up an InputStream. As a side effect the working
  // directory on the server is changed to the parent directory of the file.
  // The FTP client connection is closed when close() is called on the
  // FSDataInputStream.
  client.changeWorkingDirectory(parent.toUri().getPath());
  InputStream is = client.retrieveFileStream(file.getName());
  FSDataInputStream fis = new FSDataInputStream(new FTPInputStream(is,
      client, statistics));
  if (!FTPReply.isPositivePreliminary(client.getReplyCode())) {
    // The ftpClient is an inconsistent state. Must close the stream
    // which in turn will logout and disconnect from FTP server
    fis.close();
    throw new IOException("Unable to open file: " + file + ", Aborting");
  }
  return fis;
}
 
Example 15
Source File: FtpUtil.java    From util with Apache License 2.0 5 votes vote down vote up
/** 
 * 从FTP服务器列出指定文件夹下文件名列表。 
 * @param remotePath FTP服务器上的相对路径 
 * @return List<String> 文件名列表,如果出现异常返回null。
 * @throws IOException 
 */  
public List<String> getFileNameList(String remotePath) throws IOException {  
	//目录列表记录
       List<String> fileNames=new ArrayList<String>();
    FTPClient ftp = new FTPClient();  
    try {  
        int reply;  
        ftp.connect(url, port);  
        //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器  
        ftp.login(userName, password);//登录  
        reply = ftp.getReplyCode();  
        if (!FTPReply.isPositiveCompletion(reply)) {  
            ftp.disconnect();  
            return null;  
        }  
        ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录  
        FTPFile[] fs = ftp.listFiles();
        for(FTPFile file : fs){
        	fileNames.add(file.getName());
        }  
        ftp.logout();  
    } catch (IOException e) { 
        e.printStackTrace();  
        throw e ;
    } finally {  
        if (ftp.isConnected()) {  
            try {  
                ftp.disconnect();  
            } catch (IOException ioe) {  
            }  
        }  
    }
    return fileNames;
}
 
Example 16
Source File: FTPServerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Create a user other than "admin" who has access to a set of files. 
 * 
 * Create a folder containing test.docx as user one
 * Update that file as user two.
 * Check user one can see user two's changes.
 * 
 * @throws Exception
 */
public void testTwoUserUpdate() throws Exception
{
    logger.debug("Start testFTPConnect");
    
    final String TEST_DIR="/Alfresco/User Homes/" + USER_ONE;
 
    FTPClient ftpOne = connectClient();
    FTPClient ftpTwo = connectClient();
    try
    {
        int reply = ftpOne.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply))
        {
            fail("FTP server refused connection.");
        }
        
        reply = ftpTwo.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply))
        {
            fail("FTP server refused connection.");
        }
    
        boolean login = ftpOne.login(USER_ONE, PASSWORD_ONE);
        assertTrue("user one login not successful", login);
        
        login = ftpTwo.login(USER_TWO, PASSWORD_TWO);
        assertTrue("user two login not successful", login);
        
        boolean success = ftpOne.changeWorkingDirectory("Alfresco");
        assertTrue("user one unable to cd to Alfreco", success);
        success = ftpOne.changeWorkingDirectory("User*Homes");
        assertTrue("user one unable to cd to User*Homes", success);
        success = ftpOne.changeWorkingDirectory(USER_ONE);
        assertTrue("user one unable to cd to " + USER_ONE, success);
        
        success = ftpTwo.changeWorkingDirectory("Alfresco");
        assertTrue("user two unable to cd to Alfreco", success);
        success = ftpTwo.changeWorkingDirectory("User*Homes");
        assertTrue("user two unable to cd to User*Homes", success);
        success = ftpTwo.changeWorkingDirectory(USER_ONE);
        assertTrue("user two unable to cd " + USER_ONE, success);

        // Create a file as user one
        String FILE1_CONTENT_1="test file 1 content";
        String FILE1_NAME = "test.docx";
        success = ftpOne.appendFile(FILE1_NAME , new ByteArrayInputStream(FILE1_CONTENT_1.getBytes("UTF-8")));
        assertTrue("user one unable to append file", success);
        
        // Update the file as user two
        String FILE1_CONTENT_2="test file content updated";
        success = ftpTwo.storeFile(FILE1_NAME , new ByteArrayInputStream(FILE1_CONTENT_2.getBytes("UTF-8")));
        assertTrue("user two unable to append file", success);
        
        // User one should read user2's content
        InputStream is1 = ftpOne.retrieveFileStream(FILE1_NAME);
        assertNotNull("is1 is null", is1);
        String content1 = inputStreamToString(is1);
        assertEquals("Content is not as expected", FILE1_CONTENT_2, content1);
        ftpOne.completePendingCommand();
        
        // User two should read user2's content
        InputStream is2 = ftpTwo.retrieveFileStream(FILE1_NAME);
        assertNotNull("is2 is null", is2);
        String content2 = inputStreamToString(is2);
        assertEquals("Content is not as expected", FILE1_CONTENT_2, content2);
        ftpTwo.completePendingCommand();
        logger.debug("Test finished");
  
    } 
    finally
    {
        ftpOne.dele(TEST_DIR);
        if(ftpOne != null)
        {
            ftpOne.disconnect();
        }
        if(ftpTwo != null)
        {
            ftpTwo.disconnect();
        }
    }       

}
 
Example 17
Source File: FTPServerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Test of obscure path names in the FTP server
 * 
 * RFC959 states that paths are constructed thus...
 * <string> ::= <char> | <char><string>
 * <pathname> ::= <string>
 * <char> ::= any of the 128 ASCII characters except <CR> and <LF>
 *       
 *  So we need to check how high characters and problematic are encoded     
 */
public void testPathNames() throws Exception
{
    
    logger.debug("Start testPathNames");
    
    FTPClient ftp = connectClient();

    String PATH1="testPathNames";
    
    try
    {
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply))
        {
            fail("FTP server refused connection.");
        }
    
        boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN);
        assertTrue("admin login successful", login);
                      
        reply = ftp.cwd("/Alfresco/User*Homes");
        assertTrue(FTPReply.isPositiveCompletion(reply));
                    
        // Delete the root directory in case it was left over from a previous test run
        try
        {
            ftp.removeDirectory(PATH1);
        }
        catch (IOException e)
        {
            // ignore this error
        }
        
        // make root directory for this test
        boolean success = ftp.makeDirectory(PATH1);
        assertTrue("unable to make directory:" + PATH1, success);
        
        success = ftp.changeWorkingDirectory(PATH1);
        assertTrue("unable to change to working directory:" + PATH1, success);
        
        assertTrue("with a space", ftp.makeDirectory("test space"));
        assertTrue("with exclamation", ftp.makeDirectory("space!"));
        assertTrue("with dollar", ftp.makeDirectory("space$"));
        assertTrue("with brackets", ftp.makeDirectory("space()"));
        assertTrue("with hash curley  brackets", ftp.makeDirectory("space{}"));


        //Pound sign U+00A3
        //Yen Sign U+00A5
        //Capital Omega U+03A9

        assertTrue("with pound sign", ftp.makeDirectory("pound \u00A3.world"));
        assertTrue("with yen sign", ftp.makeDirectory("yen \u00A5.world"));
        
        // Test steps that do not work
        // assertTrue("with omega", ftp.makeDirectory("omega \u03A9.world"));
        // assertTrue("with obscure ASCII chars", ftp.makeDirectory("?/.,<>"));    
    } 
    finally
    {
        // clean up tree if left over from previous run

        ftp.disconnect();
    }    


}
 
Example 18
Source File: FTPFileSystem.java    From hadoop-gpu with Apache License 2.0 4 votes vote down vote up
/**
 * A stream obtained via this call must be closed before using other APIs of
 * this class or else the invocation will block.
 */
@Override
public FSDataOutputStream create(Path file, FsPermission permission,
    boolean overwrite, int bufferSize, short replication, long blockSize,
    Progressable progress) throws IOException {
  final FTPClient client = connect();
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  if (exists(client, file)) {
    if (overwrite) {
      delete(client, file);
    } else {
      disconnect(client);
      throw new IOException("File already exists: " + file);
    }
  }
  Path parent = absolute.getParent();
  if (parent == null || !mkdirs(client, parent, FsPermission.getDefault())) {
    parent = (parent == null) ? new Path("/") : parent;
    disconnect(client);
    throw new IOException("create(): Mkdirs failed to create: " + parent);
  }
  client.allocate(bufferSize);
  // Change to parent directory on the server. Only then can we write to the
  // file on the server by opening up an OutputStream. As a side effect the
  // working directory on the server is changed to the parent directory of the
  // file. The FTP client connection is closed when close() is called on the
  // FSDataOutputStream.
  client.changeWorkingDirectory(parent.toUri().getPath());
  FSDataOutputStream fos = new FSDataOutputStream(client.storeFileStream(file
      .getName()), statistics) {
    @Override
    public void close() throws IOException {
      super.close();
      if (!client.isConnected()) {
        throw new FTPException("Client not connected");
      }
      boolean cmdCompleted = client.completePendingCommand();
      disconnect(client);
      if (!cmdCompleted) {
        throw new FTPException("Could not complete transfer, Reply Code - "
            + client.getReplyCode());
      }
    }
  };
  if (!FTPReply.isPositivePreliminary(client.getReplyCode())) {
    // The ftpClient is an inconsistent state. Must close the stream
    // which in turn will logout and disconnect from FTP server
    fos.close();
    throw new IOException("Unable to create file: " + file + ", Aborting");
  }
  return fos;
}
 
Example 19
Source File: FTPFileSystem.java    From RDFS with Apache License 2.0 4 votes vote down vote up
/**
 * A stream obtained via this call must be closed before using other APIs of
 * this class or else the invocation will block.
 */
@Override
public FSDataOutputStream create(Path file, FsPermission permission,
    boolean overwrite, int bufferSize, short replication, long blockSize,
    Progressable progress) throws IOException {
  final FTPClient client = connect();
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  if (exists(client, file)) {
    if (overwrite) {
      delete(client, file);
    } else {
      disconnect(client);
      throw new IOException("File already exists: " + file);
    }
  }
  Path parent = absolute.getParent();
  if (parent == null || !mkdirs(client, parent, FsPermission.getDefault())) {
    parent = (parent == null) ? new Path("/") : parent;
    disconnect(client);
    throw new IOException("create(): Mkdirs failed to create: " + parent);
  }
  client.allocate(bufferSize);
  // Change to parent directory on the server. Only then can we write to the
  // file on the server by opening up an OutputStream. As a side effect the
  // working directory on the server is changed to the parent directory of the
  // file. The FTP client connection is closed when close() is called on the
  // FSDataOutputStream.
  client.changeWorkingDirectory(parent.toUri().getPath());
  FSDataOutputStream fos = new FSDataOutputStream(client.storeFileStream(file
      .getName()), statistics) {
    @Override
    public void close() throws IOException {
      super.close();
      if (!client.isConnected()) {
        throw new FTPException("Client not connected");
      }
      boolean cmdCompleted = client.completePendingCommand();
      disconnect(client);
      if (!cmdCompleted) {
        throw new FTPException("Could not complete transfer, Reply Code - "
            + client.getReplyCode());
      }
    }
  };
  if (!FTPReply.isPositivePreliminary(client.getReplyCode())) {
    // The ftpClient is an inconsistent state. Must close the stream
    // which in turn will logout and disconnect from FTP server
    fos.close();
    throw new IOException("Unable to create file: " + file + ", Aborting");
  }
  return fos;
}
 
Example 20
Source File: FtpCheck.java    From commons-vfs with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args) throws Exception {
    if (args.length < 3) {
        throw new IllegalArgumentException("Usage: FtpCheck user pass host dir");
    }
    final String user = args[0];
    final String pass = args[1];
    final String host = args[2];
    String dir = null;
    if (args.length == 4) {
        dir = args[3];
    }

    final FTPClient client = new FTPClient();
    client.connect(host);
    final int reply = client.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        throw new IllegalArgumentException("cant connect: " + reply);
    }
    if (!client.login(user, pass)) {
        throw new IllegalArgumentException("login failed");
    }
    client.enterLocalPassiveMode();

    final OutputStream os = client.storeFileStream(dir + "/test.txt");
    if (os == null) {
        throw new IllegalStateException(client.getReplyString());
    }
    os.write("test".getBytes(Charset.defaultCharset()));
    os.close();
    client.completePendingCommand();

    if (dir != null && !client.changeWorkingDirectory(dir)) {
        throw new IllegalArgumentException("change dir to '" + dir + "' failed");
    }

    System.err.println("System: " + client.getSystemType());

    final FTPFile[] files = client.listFiles();
    for (int i = 0; i < files.length; i++) {
        final FTPFile file = files[i];
        if (file == null) {
            System.err.println("#" + i + ": " + null);
        } else {
            System.err.println("#" + i + ": " + file.getRawListing());
            System.err.println("#" + i + ": " + file.toString());
            System.err.println("\t name:" + file.getName() + " type:" + file.getType());
        }
    }
    client.disconnect();
}