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

The following examples show how to use org.apache.commons.net.ftp.FTPClient#makeDirectory() . 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: 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 2
Source File: FTPFileSystem.java    From hadoop-gpu 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 3
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 4
Source File: BugReportSenderFtp.java    From YalpStore with GNU General Public License v2.0 6 votes vote down vote up
private boolean uploadAll() {
    FTPClient ftpClient = new FTPClient();
    try {
        ftpClient.connect(FTP_HOST, FTP_PORT);
        if (!ftpClient.login(FTP_USER, FTP_PASSWORD)) {
            return false;
        }
        String dirName = getDirName();
        ftpClient.makeDirectory(dirName);
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE, FTP.BINARY_FILE_TYPE);
        ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
        boolean result = true;
        for (File file: files) {
            result &= upload(ftpClient, file, dirName + "/" + file.getName());
        }
        return result;
    } catch (IOException e) {
        Log.e(BugReportSenderFtp.class.getSimpleName(), "FTP network error: " + e.getMessage());
    } finally {
        closeSilently(ftpClient);
    }
    return false;
}
 
Example 5
Source File: FTPFileSystem.java    From hadoop 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 6
Source File: FTPTransfer.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void ensureDirectoryExists(final FlowFile flowFile, final File directoryName) throws IOException {
    if (directoryName.getParent() != null && !directoryName.getParentFile().equals(new File(File.separator))) {
        ensureDirectoryExists(flowFile, directoryName.getParentFile());
    }

    final String remoteDirectory = directoryName.getAbsolutePath().replace("\\", "/").replaceAll("^.\\:", "");
    final FTPClient client = getClient(flowFile);
    final boolean cdSuccessful = setWorkingDirectory(remoteDirectory);

    if (!cdSuccessful) {
        logger.debug("Remote Directory {} does not exist; creating it", new Object[] {remoteDirectory});
        if (client.makeDirectory(remoteDirectory)) {
            logger.debug("Created {}", new Object[] {remoteDirectory});
        } else {
            throw new IOException("Failed to create remote directory " + remoteDirectory);
        }
    }
}
 
Example 7
Source File: FTPUtil.java    From seed with Apache License 2.0 6 votes vote down vote up
/**
 * 创建远程目录
 * @param remotePath 不含文件名的远程路径(格式为/a/b/c)
 */
private static void createRemoteFolder(FTPClient ftpClient, String remotePath) throws IOException{
    String[] folders = remotePath.split("/");
    String remoteTempPath = "";
    for(String folder : folders){
        if(StringUtils.isNotBlank(folder)){
            remoteTempPath += "/" + folder;
            boolean flag = ftpClient.changeWorkingDirectory(remoteTempPath);
            LogUtil.getLogger().info("change working directory : " + remoteTempPath + "-->" + (flag?"SUCCESS":"FAIL"));
            if(!flag){
                flag = ftpClient.makeDirectory(remoteTempPath);
                LogUtil.getLogger().info("make directory : " + remoteTempPath + "-->" + (flag?"SUCCESS":"FAIL"));
            }
        }
    }
}
 
Example 8
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 9
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
 */
private 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 10
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 11
Source File: Utils.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
/**
 * Uploads a file to an Azure function 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 uploadFileToFunctionApp(PublishingProfile profile, String fileName, InputStream file) {
    FTPClient ftpClient = new FTPClient();
    String[] ftpUrlSegments = profile.ftpUrl().split("/", 2);
    String server = ftpUrlSegments[0];
    String path = "site/wwwroot";
    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.ASCII_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 12
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 uploadFileToWebAppWwwRoot(PublishingProfile profile, String fileName, InputStream file) {
    FTPClient ftpClient = new FTPClient();
    String[] ftpUrlSegments = profile.ftpUrl().split("/", 2);
    String server = ftpUrlSegments[0];
    String path = "./site/wwwroot";
    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 13
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 14
Source File: FTPClientTemplate.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
/**  
     * 递归创建远程服务器目录  
     * @param pathname 远程服务器文件绝对路径
     * @return 目录创建是否成功  
     * @throws IOException
     */  
    public boolean mkdirMore(String pathname) throws Exception {
//        UploadStatus status = UploadStatus.Create_Directory_Success;   
        String directory = pathname;
        if(!directory.startsWith("/")){   
        	directory ="/"+directory;   
        } 
        if(pathname.lastIndexOf("/")==pathname.length()-1){
        	directory = pathname.substring(0,pathname.lastIndexOf("/")); 
        }
        FTPClient ftpClient=getFTPClient();
        if(!directory.equalsIgnoreCase("/")&&!ftpClient.changeWorkingDirectory(new String(directory.getBytes("GBK"),"iso-8859-1"))){
            //如果远程目录不存在,则递归创建远程服务器目录   
        	 if(!directory.endsWith("/")){  
             	directory=directory+"/";
             } 
        	int start=0;
            int end =directory.indexOf("/",start+1);   
            while(true){   
                String subDirectory = new String(pathname.substring(start,end).getBytes("GBK"),"iso-8859-1");
                if(!ftpClient.changeWorkingDirectory(subDirectory)){   
                    if(ftpClient.makeDirectory(subDirectory)){   
                        ftpClient.changeWorkingDirectory(subDirectory);   
                    }else {   
//                        System.out.println("创建目录失败");  
                        return true;
                    }   
                }   
                   
                start = end + 1;   
                end = directory.indexOf("/",start);   
                //检查所有目录是否创建完毕   
                if(end <= start){   
                    break;   
                }   
            }   
        }   
        return true;   
    }
 
Example 15
Source File: FtpUploadTemplate.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
/**
 * 选择上传的目录,没有创建目录
 *
 * @param ftpPath 需要上传、创建的目录
 * @return
 */
public static boolean mkDir(FTPClient ftpClient, String ftpPath) {
    if (!ftpClient.isConnected()) {
        return false;
    }
    try {
        // 将路径中的斜杠统一
        char[] chars = ftpPath.toCharArray();
        StringBuffer sbStr = new StringBuffer(256);
        for (int i = 0; i < chars.length; i++) {
            if ('\\' == chars[i]) {
                sbStr.append('/');
            } else {
                sbStr.append(chars[i]);
            }
        }
        ftpPath = sbStr.toString();
        // System.out.println("ftpPath:" + ftpPath);
        if (ftpPath.indexOf('/') == -1) {
            // 只有一层目录
            ftpClient.makeDirectory(new String(ftpPath.getBytes(), "iso-8859-1"));
            ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(), "iso-8859-1"));
        } else {
            // 多层目录循环创建
            String[] paths = ftpPath.split("/");
            for (int i = 0; i < paths.length; i++) {
                ftpClient.makeDirectory(new String(paths[i].getBytes(), "iso-8859-1"));
                ftpClient.changeWorkingDirectory(new String(paths[i].getBytes(), "iso-8859-1"));
            }
        }
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 16
Source File: PooledFTPOperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
private boolean create(FTPClient ftp, URI uri, CreateParameters params) throws IOException {
	if (Thread.currentThread().isInterrupted()) {
		throw new IOException(FileOperationMessages.getString("IOperationHandler.interrupted")); //$NON-NLS-1$
	}
	boolean success = true;
	boolean createDirectory = Boolean.TRUE.equals(params.isDirectory());
	boolean createParents = Boolean.TRUE.equals(params.isMakeParents());
	Info fileInfo = info(uri, ftp);
	if (fileInfo == null) { // does not exist
		URI parentUri = URIUtils.getParentURI(uri);
		if (createParents) {
			create(ftp, parentUri, params.clone().setDirectory(true));
		} else {
			Info parentInfo = info(parentUri, ftp);
			if (parentInfo == null) {
				throw new FileNotFoundException(MessageFormat.format(FileOperationMessages.getString("IOperationHandler.file_not_found"), uri.toString())); //$NON-NLS-1$
			}
		}
		String path = getPath(uri);
		if (createDirectory) {
			success = ftp.makeDirectory(path);
		} else {
			success = createFile(ftp, path);
		}
	} else {
		Boolean directory = params.isDirectory();
		if ((directory != null) && !directory.equals(fileInfo.isDirectory())) {
			throw new IOException(MessageFormat.format(createDirectory ? FileOperationMessages.getString("IOperationHandler.exists_not_directory") : FileOperationMessages.getString("IOperationHandler.exists_not_file"), fileInfo.getURI())); //$NON-NLS-1$ //$NON-NLS-2$
		}
	}
	return success;
}
 
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: FTPServerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Test of rename case ALF-20584
 * 
  
 */
public void testRenameCase() throws Exception
{
    
    logger.debug("Start testRenameCase");
    
    FTPClient ftp = connectClient();

    String PATH1="testRenameCase";
    
    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);
        
        ftp.cwd(PATH1);
        
        String FILE1_CONTENT_2="That's how it is says Pooh!";
        ftp.storeFile("FileA.txt" , new ByteArrayInputStream(FILE1_CONTENT_2.getBytes("UTF-8")));
        
        assertTrue("unable to rename", ftp.rename("FileA.txt", "FILEA.TXT"));
    
    } 
    finally
    {
        // clean up tree if left over from previous run

        ftp.disconnect();
    }    


}
 
Example 19
Source File: FTPServerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Test CRUD for FTP server
 *
 * @throws Exception
 */
public void testCRUD() throws Exception
{
    final String PATH1 = "FTPServerTest";
    final String PATH2 = "Second part";
    
    logger.debug("Start testFTPCRUD");
    
    FTPClient ftp = connectClient();

    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
        ftp.makeDirectory(PATH1);
        ftp.cwd(PATH1);
        
        // make sub-directory in new directory
        ftp.makeDirectory(PATH2);
        ftp.cwd(PATH2);
        
        // List the files in the new directory
        FTPFile[] files = ftp.listFiles();
        assertTrue("files not empty", files.length == 0);
        
        // Create a file
        String FILE1_CONTENT_1="test file 1 content";
        String FILE1_NAME = "testFile1.txt";
        ftp.appendFile(FILE1_NAME , new ByteArrayInputStream(FILE1_CONTENT_1.getBytes("UTF-8")));
        
        // Get the new file
        FTPFile[] files2 = ftp.listFiles();
        assertTrue("files not one", files2.length == 1);
        
        InputStream is = ftp.retrieveFileStream(FILE1_NAME);
        
        String content = inputStreamToString(is);
        assertEquals("Content is not as expected", content, FILE1_CONTENT_1);
        ftp.completePendingCommand();
        
        // Update the file contents
        String FILE1_CONTENT_2="That's how it is says Pooh!";
        ftp.storeFile(FILE1_NAME , new ByteArrayInputStream(FILE1_CONTENT_2.getBytes("UTF-8")));
        
        InputStream is2 = ftp.retrieveFileStream(FILE1_NAME);
        
        String content2 = inputStreamToString(is2);
        assertEquals("Content is not as expected", FILE1_CONTENT_2, content2);
        ftp.completePendingCommand();
        
        // now delete the file we have been using.
        assertTrue (ftp.deleteFile(FILE1_NAME));
        
        // negative test - file should have gone now.
        assertFalse (ftp.deleteFile(FILE1_NAME));
        
    } 
    finally
    {
        // clean up tree if left over from previous run

        ftp.disconnect();
    }    
}
 
Example 20
Source File: FtpContinueClient.java    From spring-boot-study with MIT License 4 votes vote down vote up
/**
 * 递归创建远程服务器目录
 *
 * @param remote 远程服务器文件绝对路径
 * @param ftpClient FTPClient对象
 * @return 目录创建是否成功
 * @throws IOException
 */
public UploadStatus CreateDirecroty(String remote, FTPClient ftpClient)
        throws IOException {
    UploadStatus status = UploadStatus.Create_Directory_Success;
    String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
    if (!directory.equalsIgnoreCase("/")
            && !ftpClient.changeWorkingDirectory(new String(directory.getBytes("GBK"), "iso-8859-1")))
    {
        // 如果远程目录不存在,则递归创建远程服务器目录
        int start = 0;
        int end = 0;
        if (directory.startsWith("/"))
        {
            start = 1;
        }
        else
        {
            start = 0;
        }
        end = directory.indexOf("/", start);
        while (true)
        {
            String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
            if (!ftpClient.changeWorkingDirectory(subDirectory))
            {
                if (ftpClient.makeDirectory(subDirectory))
                {
                    ftpClient.changeWorkingDirectory(subDirectory);
                }
                else
                {
                    System.out.println("创建目录失败");
                    return UploadStatus.Create_Directory_Fail;
                }
            }

            start = end + 1;
            end = directory.indexOf("/", start);

            // 检查所有目录是否创建完毕
            if (end <= start)
            {
                break;
            }
        }
    }
    return status;
}