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

The following are top voted examples for showing how to use org.apache.commons.net.ftp.FTPClient. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: elegant-springboot   File: MyFtpClient.java   View source code 7 votes vote down vote up
/**
 * 下载文件
 *
 * @param remoteDir      远程操作目录
 * @param remoteFileName 远程下载文件名
 * @param downloadFile   下载文件
 * @return 下载结果<br> true - 下载成功<br>
 * false - 下载失败
 */
public boolean download(String remoteDir, String remoteFileName, File downloadFile) {
    FTPClient ftp = null;
    try {
        ftp = initFtpClient(remoteDir);
        if (ftp == null) {
            logger.debug("ftp初始化失败");
            return false;
        }
        try (OutputStream os = new FileOutputStream(downloadFile)) {
            boolean storeRet = ftp.retrieveFile(remoteFileName, os);
            if (!storeRet) {
                logger.debug("下载文件失败");
                return false;
            }
        }
        return true;
    } catch (IOException e) {
        logger.error("FTP操作异常", e);
        return false;
    } finally {
        close(ftp);
    }
}
 
Example 2
Project: Limitart   File: FTPUtil.java   View source code 7 votes vote down vote up
public static byte[] download(String url, int port, String username, String password, String remotePath,
		String fileName) throws IOException {
	FTPClient ftp = new FTPClient();
	ftp.setConnectTimeout(5000);
	ftp.setAutodetectUTF8(true);
	ftp.setCharset(CharsetUtil.UTF_8);
	ftp.setControlEncoding(CharsetUtil.UTF_8.name());
	try {
		ftp.connect(url, port);
		ftp.login(username, password);// 登录
		if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
			ftp.disconnect();
			throw new IOException("login fail!");
		}
		ftp.changeWorkingDirectory(remotePath);
		ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
		FTPFile[] fs = ftp.listFiles();
		for (FTPFile ff : fs) {
			if (ff.getName().equals(fileName)) {
				try (ByteArrayOutputStream is = new ByteArrayOutputStream();) {
					ftp.retrieveFile(ff.getName(), is);
					byte[] result = is.toByteArray();
					return result;
				}
			}
		}

		ftp.logout();
	} finally {
		if (ftp.isConnected()) {
			ftp.disconnect();
		}
	}
	return null;
}
 
Example 3
Project: hadoop   File: FTPFileSystem.java   View source code 7 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
Project: TITAN   File: FtpUtils.java   View source code 7 votes vote down vote up
/**
 * 上传文件至FTP服务器
 * 
 * @author gaoxianglong
 */
public boolean uploadFile(File file) {
	boolean result = false;
	FTPClient ftpClient = ftpConnManager.getFTPClient();
	if (null == ftpClient || !ftpClient.isConnected()) {
		return result;
	}
	try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file.getPath()))) {
		boolean storeFile = ftpClient.storeFile(file.getName(), in);
		if (storeFile) {
			result = true;
			log.info("file-->" + file.getPath() + "成功上传至FTP服务器");
		}
	} catch (Exception e) {
		log.error("error", e);
	} finally {
		disconnect(ftpClient);
	}
	return result;
}
 
Example 5
Project: TITAN   File: FtpUtils.java   View source code 7 votes vote down vote up
/**
 * 从FTP服务器下载指定的文件至本地
 * 
 * @author gaoxianglong
 */
public boolean downloadFile(File file) {
	boolean result = false;
	FTPClient ftpClient = ftpConnManager.getFTPClient();
	if (null == ftpClient || !ftpClient.isConnected()) {
		return result;
	}
	try (BufferedOutputStream out = new BufferedOutputStream(
			new FileOutputStream(System.getProperty("user.home") + "/" + file.getName()))) {
		result = ftpClient.retrieveFile(file.getName(), out);
		if (result) {
			result = true;
			log.info("file-->" + file.getPath() + "成功从FTP服务器下载");
		}
	} catch (Exception e) {
		log.error("error", e);
	} finally {
		disconnect(ftpClient);
	}
	return result;
}
 
Example 6
Project: elegant-springboot   File: MyFtpClient.java   View source code 6 votes vote down vote up
private FTPClient initFtpClient(String remoteDir) throws IOException {
    FTPClient ftp = new FTPClient();
    // 设置连接超时时间
    ftp.setConnectTimeout(CONNECT_TIMEOUT);
    // 设置传输文件名编码方式
    ftp.setControlEncoding(CONTROL_ENCODING);
    ftp.connect(host, ftpPort);
    int reply = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        logger.debug("无法连接FTP");
        return null;
    }
    boolean loginRet = ftp.login(ftpUsername, ftpPassword);
    if (!loginRet) {
        logger.debug("FTP登录失败");
        return null;
    }
    // 进入被动模式
    ftp.enterLocalPassiveMode();
    boolean changeDirResult = MKDAndCWD(ftp, remoteDir);
    if (!changeDirResult) {
        logger.debug("创建/切换文件夹失败");
        return null;
    }
    // 传输二进制文件
    ftp.setFileType(FTP.BINARY_FILE_TYPE);
    return ftp;
}
 
Example 7
Project: garlicts   File: FTPUpload.java   View source code 6 votes vote down vote up
/**
 * 删除文件
 * 
 * @author wangwei
 */
public Map<String,String> deleteFile(String filename, String remoteFolder)
		throws Exception {

	Map<String,String> rs = new HashMap<String, String>();
	// 连接FTP服务器
	FTPClient ftp = this.connectFTPServer();

	try {

		// 改变当前路径到指定路径
		this.changeDirectory(remoteFolder);
		boolean result = ftp.deleteFile(filename);
		if (!result) {
			throw new Exception("FTP删除文件失败!");
		}else{
			rs.put("ret", "success");
		}

	} catch (Exception e) {
		throw e;
	}
	
	return rs;

}
 
Example 8
Project: hadoop-oss   File: FTPFileSystem.java   View source code 6 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 9
Project: hadoop-oss   File: FTPFileSystem.java   View source code 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 getFileStatus(FTPClient client, Path file)
    throws IOException {
  FileStatus fileStat = null;
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  Path parentPath = absolute.getParent();
  if (parentPath == null) { // root dir
    long length = -1; // Length of root dir on server not known
    boolean isDir = true;
    int blockReplication = 1;
    long blockSize = DEFAULT_BLOCK_SIZE; // Block Size not known.
    long modTime = -1; // Modification time of root dir not known.
    Path root = new Path("/");
    return new FileStatus(length, isDir, blockReplication, blockSize,
        modTime, root.makeQualified(this));
  }
  String pathName = parentPath.toUri().getPath();
  FTPFile[] ftpFiles = client.listFiles(pathName);
  if (ftpFiles != null) {
    for (FTPFile ftpFile : ftpFiles) {
      if (ftpFile.getName().equals(file.getName())) { // file found in dir
        fileStat = getFileStatus(ftpFile, parentPath);
        break;
      }
    }
    if (fileStat == null) {
      throw new FileNotFoundException("File " + file + " does not exist.");
    }
  } else {
    throw new FileNotFoundException("File " + file + " does not exist.");
  }
  return fileStat;
}
 
Example 10
Project: hadoop-oss   File: FTPFileSystem.java   View source code 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 11
Project: aos-FileCoreLibrary   File: Session.java   View source code 6 votes vote down vote up
public FTPClient getFTPClient(Uri uri) throws SocketException, IOException, AuthenticationException{
    NetworkCredentialsDatabase database = NetworkCredentialsDatabase.getInstance();
    Credential cred = database.getCredential(uri.toString());
    if(cred==null){
        cred = new Credential("anonymous","", buildKeyFromUri(uri).toString(), true);
    }
    FTPClient ftpclient = ftpClients.get(cred);
    if (ftpclient!=null && ftpclient.isConnected()){
        return ftpclient;
    }
    // Not previous session found, open a new one
    Log.d(TAG, "create new ftp session for "+uri);
    FTPClient ftp = getNewFTPClient(uri,FTP.BINARY_FILE_TYPE);
    if(ftp==null)
        return null;
    Uri key = buildKeyFromUri(uri);
    Log.d(TAG, "new ftp session created with key "+key);
    ftpClients.put(cred, ftp);
    return ftp;
}
 
Example 12
Project: aos-FileCoreLibrary   File: Session.java   View source code 6 votes vote down vote up
public FTPClient getFTPSClient(Uri uri) throws SocketException, IOException, AuthenticationException{
    NetworkCredentialsDatabase database = NetworkCredentialsDatabase.getInstance();
    Credential cred = database.getCredential(uri.toString());
    if(cred==null){
        cred = new Credential("anonymous","", buildKeyFromUri(uri).toString(), true);
    }
    FTPClient ftpclient = ftpsClients.get(cred);
    if (ftpclient!=null && ftpclient.isConnected()){
        return ftpclient;
    }
    // Not previous session found, open a new one
    Log.d(TAG, "create new ftp session for "+uri);
    FTPClient ftp = getNewFTPSClient(uri, FTP.BINARY_FILE_TYPE);
    if(ftp==null)
        return null;
    Uri key = buildKeyFromUri(uri);
    Log.d(TAG, "new ftp session created with key "+key);
    ftpsClients.put(cred, ftp);
    return ftp;
}
 
Example 13
Project: hadoop   File: FTPFileSystem.java   View source code 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 getFileStatus(FTPClient client, Path file)
    throws IOException {
  FileStatus fileStat = null;
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  Path parentPath = absolute.getParent();
  if (parentPath == null) { // root dir
    long length = -1; // Length of root dir on server not known
    boolean isDir = true;
    int blockReplication = 1;
    long blockSize = DEFAULT_BLOCK_SIZE; // Block Size not known.
    long modTime = -1; // Modification time of root dir not known.
    Path root = new Path("/");
    return new FileStatus(length, isDir, blockReplication, blockSize,
        modTime, root.makeQualified(this));
  }
  String pathName = parentPath.toUri().getPath();
  FTPFile[] ftpFiles = client.listFiles(pathName);
  if (ftpFiles != null) {
    for (FTPFile ftpFile : ftpFiles) {
      if (ftpFile.getName().equals(file.getName())) { // file found in dir
        fileStat = getFileStatus(ftpFile, parentPath);
        break;
      }
    }
    if (fileStat == null) {
      throw new FileNotFoundException("File " + file + " does not exist.");
    }
  } else {
    throw new FileNotFoundException("File " + file + " does not exist.");
  }
  return fileStat;
}
 
Example 14
Project: TITAN   File: FtpUtils.java   View source code 6 votes vote down vote up
public boolean uploadFile(File file, byte[] value) {
	boolean result = false;
	if (null == value) {
		return result;
	}
	FTPClient ftpClient = ftpConnManager.getFTPClient();
	if (null == ftpClient || !ftpClient.isConnected()) {
		return result;
	}
	try (BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(value))) {
		boolean storeFile = ftpClient.storeFile(file.getName(), in);
		if (storeFile) {
			result = true;
			log.info("file-->" + file.getPath() + "成功上传至FTP服务器");
		}
	} catch (Exception e) {
		log.error("error", e);
	} finally {
		disconnect(ftpClient);
	}
	return result;
}
 
Example 15
Project: elegant-springboot   File: MyFtpClient.java   View source code 6 votes vote down vote up
private boolean MKDAndCWD(FTPClient ftp, String remoteDir) throws IOException {
    // 切分出所有子文件夹,按顺序
    String[] dirs = remoteDir.split("/");
    // 遍历文件夹
    for (String subDir : dirs) {
        // 文件夹字符串非空
        if (!subDir.isEmpty()) {
            // 切换工作目录
            if (!ftp.changeWorkingDirectory(subDir)) {
                // 若目录不存在则先创建
                if (!ftp.makeDirectory(subDir)) {
                    return false;
                }
                // 切换工作目录
                if (!ftp.changeWorkingDirectory(subDir)) {
                    return false;
                }
            }
        }
    }
    return true;
}
 
Example 16
Project: TITAN   File: FtpUtils.java   View source code 6 votes vote down vote up
/**
 * 删除服务器上指定的文件
 * 
 * @author gaoxianglong
 */
public boolean deleteFile(File file) {
	boolean result = false;
	FTPClient ftpClient = ftpConnManager.getFTPClient();
	if (null == ftpClient || !ftpClient.isConnected()) {
		return result;
	}
	try {
		result = ftpClient.deleteFile(file.getName());
		if (result) {
			result = true;
			log.info("file-->" + file.getPath() + "成功从FTP服务器删除");
		}
	} catch (Exception e) {
		log.error("error", e);
	} finally {
		disconnect(ftpClient);
	}
	return result;
}
 
Example 17
Project: alfresco-repository   File: FTPServerTest.java   View source code 6 votes vote down vote up
/**
 * Simple test that connects to the inbuilt ftp server and logs on
 * 
 * @throws Exception
 */
public void testFTPConnect() throws Exception
{
    logger.debug("Start testFTPConnect");
    
    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 not successful", login);
    } 
    finally
    {
        ftp.disconnect();
    }       
}
 
Example 18
Project: alfresco-repository   File: FTPServerTest.java   View source code 6 votes vote down vote up
private FTPClient connectClient() throws IOException
{
    FTPClient ftp = new FTPClient();

    if(logger.isDebugEnabled())
    {
        ftp.addProtocolCommandListener(new PrintCommandListener(
                                   new PrintWriter(System.out)));
    }
    ftp.connect(HOSTNAME, ftpConfigSection.getFTPPort());
    return ftp;
}
 
Example 19
Project: spring-boot-seed   File: FTPClientImpl.java   View source code 6 votes vote down vote up
/**
 * 是否需要更新
 *
 * @param ftpClient         ftp client实例
 * @param localVerisonPath  本地版本文件路径(文件中第一行存储的版本号:yyyyMMddHHmmss)
 * @param remoteVersionPath 远程文件路径(使用最后更新时间作为版本号)
 * @return
 * @throws IOException
 */
public boolean needUpdate(FTPClient ftpClient, String localVerisonPath, String remoteVersionPath) throws IOException {
    File localVersionFile = new File(localVerisonPath);
    if (!localVersionFile.exists()) {
        localVersionFile.createNewFile();
        return true;
    }
    String localVersionStr = FileOperateUtils.readFirstLineFromFile(localVersionFile);
    if (StringUtils.isEmpty(localVersionStr)) {
        return true;
    }
    String remoteVersionStr = ftpClient.getModificationTime(remoteVersionPath);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    try {
        Date remoteVersion = dateFormat.parse(remoteVersionStr);
        if (remoteVersion.after(dateFormat.parse(localVersionStr))) {
            return true;
        }
    } catch (ParseException e) {
        logger.error(e.getMessage(), e);
    }

    return false;
}
 
Example 20
Project: azure-maven-plugins   File: FTPUploader.java   View source code 6 votes vote down vote up
/**
 * Upload directory to specified FTP server without retries.
 *
 * @param ftpServer
 * @param username
 * @param password
 * @param sourceDirectoryPath
 * @param targetDirectoryPath
 * @return Boolean to indicate whether uploading is successful.
 */
protected boolean uploadDirectory(final String ftpServer, final String username, final String password,
                                  final String sourceDirectoryPath, final String targetDirectoryPath) {
    log.debug("FTP username: " + username);
    try {
        final FTPClient ftpClient = getFTPClient(ftpServer, username, password);

        log.info(String.format(UPLOAD_DIR_START, sourceDirectoryPath, targetDirectoryPath));
        uploadDirectory(ftpClient, sourceDirectoryPath, targetDirectoryPath, "");
        log.info(String.format(UPLOAD_DIR_FINISH, sourceDirectoryPath, targetDirectoryPath));

        ftpClient.disconnect();
        return true;
    } catch (Exception e) {
        log.debug(e);
        log.error(String.format(UPLOAD_DIR_FAILURE, sourceDirectoryPath, targetDirectoryPath));
    }

    return false;
}
 
Example 21
Project: azure-maven-plugins   File: FTPUploader.java   View source code 6 votes vote down vote up
/**
 * Upload a single file to FTP server with the provided FTP client object.
 *
 * @param sourceFilePath
 * @param targetFilePath
 * @param logPrefix
 * @throws IOException
 */
protected void uploadFile(final FTPClient ftpClient, final String sourceFilePath, final String targetFilePath,
                          final String logPrefix) throws IOException {
    log.info(String.format(UPLOAD_FILE, logPrefix, sourceFilePath, targetFilePath));
    final File sourceFile = new File(sourceFilePath);
    try (final InputStream is = new FileInputStream(sourceFile)) {
        ftpClient.changeWorkingDirectory(targetFilePath);
        ftpClient.storeFile(sourceFile.getName(), is);

        final int replyCode = ftpClient.getReplyCode();
        final String replyMessage = ftpClient.getReplyString();
        if (isCommandFailed(replyCode)) {
            log.error(String.format(UPLOAD_FILE_REPLY, logPrefix, replyMessage));
            throw new IOException("Failed to upload file: " + sourceFilePath);
        } else {
            log.info(String.format(UPLOAD_FILE_REPLY, logPrefix, replyMessage));
        }
    }
}
 
Example 22
Project: aliyun-maxcompute-data-collectors   File: MainframeFTPClientUtils.java   View source code 6 votes vote down vote up
public static List<String> listSequentialDatasets(
    String pdsName, Configuration conf) throws IOException {
  List<String> datasets = new ArrayList<String>();
  FTPClient ftp = null;
  try {
    ftp = getFTPConnection(conf);
    if (ftp != null) {
      ftp.changeWorkingDirectory("'" + pdsName + "'");
      FTPFile[] ftpFiles = ftp.listFiles();
      for (FTPFile f : ftpFiles) {
        if (f.getType() == FTPFile.FILE_TYPE) {
          datasets.add(f.getName());
        }
      }
    }
  } catch(IOException ioe) {
    throw new IOException ("Could not list datasets from " + pdsName + ":"
        + ioe.toString());
  } finally {
    if (ftp != null) {
      closeFTPConnection(ftp);
    }
  }
  return datasets;
}
 
Example 23
Project: spring-boot-seed   File: FTPClientImpl.java   View source code 6 votes vote down vote up
/**
 * 从远程服务器目录下载文件到本地服务器目录中
 *
 * @param ftp          ftp对象
 * @param localdir     本地文件夹路径
 * @param remotedir    远程文件夹路径
 * @param localTmpFile 本地下载文件名记录
 * @return
 * @throws IOException
 */
private Collection<String> downloadFolderFiles(FTPClient ftp, final String localdir, final String remotedir, final String localTmpFile) throws IOException {
    //切换到下载目录的中
    ftp.changeWorkingDirectory(remotedir);
    //获取目录中所有的文件信息
    FTPFile[] ftpfiles = ftp.listFiles();
    Collection<String> fileNamesCol = new ArrayList<>();
    //判断文件目录是否为空
    if (!ArrayUtils.isEmpty(ftpfiles)) {
        for (FTPFile ftpfile : ftpfiles) {
            String remoteFilePath = ftpfile.getName();
            String localFilePath = localdir + separator + ftpfile.getName();
            //System.out.println("remoteFilePath ="+remoteFilePath +" localFilePath="+localFilePath)
            //单个文件下载状态
            DownloadStatus downStatus = FtpHelper.getInstance().download(ftp, remoteFilePath, localFilePath);
            if (downStatus == DownloadStatus.Download_New_Success) {
                //临时目录中添加记录信息
                fileNamesCol.add(remoteFilePath);
            }
        }
    }
    if (!fileNamesCol.isEmpty() && !StringUtils.isEmpty(localTmpFile)) {
        FileOperateUtils.writeLinesToFile(fileNamesCol, localTmpFile, false);
    }
    return fileNamesCol;
}
 
Example 24
Project: aliyun-maxcompute-data-collectors   File: TestMainframeFTPClientUtils.java   View source code 6 votes vote down vote up
@Test
public void testAnonymous_VERBOSE_IllegelPort() {
  try {
    when(mockFTPClient.login("anonymous", "")).thenReturn(true);
    when(mockFTPClient.logout()).thenReturn(true);
    when(mockFTPClient.isConnected()).thenReturn(false);
    when(mockFTPClient.getReplyCode()).thenReturn(200);
  } catch (IOException e) {
    fail("No IOException should be thrown!");
  }

  conf.set(DBConfiguration.URL_PROPERTY, "localhost:testPort");
  conf.setBoolean(JobBase.PROPERTY_VERBOSE, true);

  FTPClient ftp = null;
  boolean success = false;
  try {
    ftp = MainframeFTPClientUtils.getFTPConnection(conf);
  } catch (IOException ioe) {
    fail("No IOException should be thrown!");
  } finally {
    success = MainframeFTPClientUtils.closeFTPConnection(ftp);
  }
  Assert.assertTrue(success);
}
 
Example 25
Project: hadoop   File: FTPFileSystem.java   View source code 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 delete(FTPClient client, Path file, boolean recursive)
    throws IOException {
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  String pathName = absolute.toUri().getPath();
  try {
    FileStatus fileStat = getFileStatus(client, absolute);
    if (fileStat.isFile()) {
      return client.deleteFile(pathName);
    }
  } catch (FileNotFoundException e) {
    //the file is not there
    return false;
  }
  FileStatus[] dirEntries = listStatus(client, absolute);
  if (dirEntries != null && dirEntries.length > 0 && !(recursive)) {
    throw new IOException("Directory: " + file + " is not empty.");
  }
  for (FileStatus dirEntry : dirEntries) {
    delete(client, new Path(absolute, dirEntry.getPath()), recursive);
  }
  return client.removeDirectory(pathName);
}
 
Example 26
Project: elegant-springboot   File: MyFtpClient.java   View source code 6 votes vote down vote up
/**
 * 移动ftp上的文件
 *
 * @param srcPath 原文件路径
 * @param desPath 模板文件路径
 * @return 操作结果
 */
public boolean move(String srcPath, String desPath) {
    FTPClient ftp = null;
    try {
        ftp = initFtpClient("/");

        // 创建目标文件夹
        String remoteDir = desPath.substring(0, desPath.lastIndexOf("/"));
        MKDAndCWD(ftp, remoteDir);

        if (ftp == null) {
            logger.debug("ftp初始化失败");
            return false;
        }
        if (!ftp.rename(srcPath, desPath)) {
            logger.warn("移动文件失败");
            return false;
        }
        return true;
    } catch (IOException e) {
        logger.error("FTP操作异常", e);
        return false;
    } finally {
        close(ftp);
    }
}
 
Example 27
Project: spring-boot-seed   File: FtpHelper.java   View source code 6 votes vote down vote up
protected void makeRemoteDir(FTPClient ftp, String dir)
        throws IOException {
    String workingDirectory = ftp.printWorkingDirectory();
    if (dir.indexOf("/") == 0) {
        ftp.changeWorkingDirectory("/");
    }
    String subdir;
    StringTokenizer st = new StringTokenizer(dir, "/");
    while (st.hasMoreTokens()) {
        subdir = st.nextToken();
        if (!(ftp.changeWorkingDirectory(subdir))) {
            if (!(ftp.makeDirectory(subdir))) {
                int rc = ftp.getReplyCode();
                if (rc != 550 && rc != 553 && rc != 521) {
                    throw new IOException("could not create directory: " + ftp.getReplyString());
                }
            } else {
                ftp.changeWorkingDirectory(subdir);
            }
        }
    }
    if (workingDirectory != null) {
        ftp.changeWorkingDirectory(workingDirectory);
    }
}
 
Example 28
Project: hadoop   File: FTPFileSystem.java   View source code 6 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 29
Project: elegant-springboot   File: MyFtpClient.java   View source code 6 votes vote down vote up
/**
 * 检查文件/文件夹下是否存在
 *
 * @param remoteDir      远程地址
 * @param remoteFileName 远程文件名称
 * @return true文件存在,false文件不存在
 */
public boolean isFileExist(String remoteDir, String remoteFileName) {
    FTPClient ftp = null;
    try {
        ftp = initFtpClient(remoteDir);
        if (ftp == null) {
            logger.debug("ftp初始化失败");
            return false;
        }

        FTPFile[] files = null;
        files = ftp.listFiles(remoteDir + remoteFileName);
        if (null != files && files.length > 0) {
            return true;
        }

        return false;
    } catch (IOException e) {
        logger.error("FTP操作异常", e);
        return false;
    } finally {
        close(ftp);
    }
}
 
Example 30
Project: X-mall   File: FTPUtil.java   View source code 5 votes vote down vote up
private boolean connectServer(String ip, int port, String user, String pwd) {

        boolean isSuccess = false;
        ftpClient = new FTPClient();
        try {
            ftpClient.connect(ip);
            isSuccess = ftpClient.login(user, pwd);
        } catch (IOException e) {
            logger.error("连接FTP服务器异常", e);
        }
        return isSuccess;
    }
 
Example 31
Project: garlicts   File: FTPUpload.java   View source code 5 votes vote down vote up
/**
 * 连接FTP服务器
 * 
 * @author wangwei
 */
public FTPClient connectFTPServer() throws Exception {

	ftpClient = new FTPClient();
	try {
		ftpClient.configure(getFTPClientConfig());
		ftpClient.connect(ftpConstant.getHost(), ftpConstant.getPort());
		ftpClient.login(ftpConstant.getUsername(), ftpConstant.getPassword());

		// 设置以二进制方式传输
		ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
		// 设置被动模式
		ftpClient.enterLocalPassiveMode();
		ftpClient.setControlEncoding("GBK");

		// 响应信息
		int replyCode = ftpClient.getReplyCode();
		if ((!FTPReply.isPositiveCompletion(replyCode))) {
			// 关闭Ftp连接
			closeFTPClient();
			// 释放空间
			ftpClient = null;
			throw new Exception("登录FTP服务器失败,请检查!");
		} else {
			return ftpClient;
		}
	} catch (Exception e) {
		ftpClient.disconnect();
		ftpClient = null;
		throw e;
	}
}
 
Example 32
Project: garlicts   File: FTPUpload.java   View source code 5 votes vote down vote up
/**
 * FTP下载
 * 
 * @author wangwei
 */
public void downloadFile(String downloadFilename, String remoteFolder,
		OutputStream outputStream, HttpServletResponse response)
		throws Exception {

	// 连接FTP服务器
	FTPClient ftp = this.connectFTPServer();

	try {

		this.changeDirectory(remoteFolder);
		FTPFile[] fs = ftp.listFiles();
		for (int i = 0; i < fs.length; i++) {
			FTPFile ff = fs[i];
			if (ff.getName().equals(downloadFilename)) {
				response.setHeader(
						"Content-disposition",
						"attachment;filename="
								+ URLEncoder.encode(downloadFilename,
										"utf-8"));
				boolean result = ftp.retrieveFile(new String(ff.getName()
						.getBytes("GBK"), "ISO-8859-1"), outputStream);
				if (!result) {
					throw new Exception("FTP文件下载失败!");
				}
				outputStream.flush();
			}
		}

	} catch (Exception e) {
		throw e;
	} finally {
		if (outputStream != null) {
			outputStream.close();
		}
	}

}
 
Example 33
Project: garlicts   File: FTPUpload.java   View source code 5 votes vote down vote up
/**
 * 关闭FTP连接
 * 
 * @author wangwei
 */
public void closeFTPClient(FTPClient ftp) throws Exception {

	try {
		if (ftp.isConnected())
			ftp.disconnect();
	} catch (Exception e) {
		throw new Exception("关闭FTP服务出错!");
	}
}
 
Example 34
Project: acr-java-manage-azure-container-registry   File: Utils.java   View source code 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 35
Project: acr-java-manage-azure-container-registry   File: Utils.java   View source code 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 36
Project: hadoop   File: FTPFileSystem.java   View source code 5 votes vote down vote up
@Override
public boolean rename(Path src, Path dst) throws IOException {
  FTPClient client = connect();
  try {
    boolean success = rename(client, src, dst);
    return success;
  } finally {
    disconnect(client);
  }
}
 
Example 37
Project: wherehowsX   File: FtpUtils.java   View source code 5 votes vote down vote up
public static boolean downloadFile(String url, int port, String username, String password,
                                   String remotePath, String fileName, String localPath) {
    boolean success = false;
    FTPClient ftp = new FTPClient();
    try {
        int reply;
        ftp.connect(url, port);
        ftp.login(username, password);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return success;
        }
        ftp.changeWorkingDirectory(remotePath);
        FTPFile[] fs = ftp.listFiles();
        System.out.println(fs.length);
        for (FTPFile ff : fs) {
            System.out.println(ff.getName());
            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();
        success = true;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }
    return success;
}
 
Example 38
Project: spring-boot-seed   File: FTPClientImpl.java   View source code 5 votes vote down vote up
@Override
public UploadStatus uploadCover(File localFile, String remoteFilePath) throws IOException {
    return execute((FTPClient ftpClient) -> {
                boolean deleteRemote = ftpClient.deleteFile(remoteFilePath);
                if (deleteRemote) {
                    return FtpHelper.getInstance().upload(ftpClient, localFile, remoteFilePath);
                } else {
                    return UploadStatus.Upload_New_File_Failed;
                }
            }
    );
}
 
Example 39
Project: hadoop-oss   File: FTPFileSystem.java   View source code 5 votes vote down vote up
/**
 * Logout and disconnect the given FTPClient. *
 * 
 * @param client
 * @throws IOException
 */
private void disconnect(FTPClient client) throws IOException {
  if (client != null) {
    if (!client.isConnected()) {
      throw new FTPException("Client not connected");
    }
    boolean logoutSuccess = client.logout();
    client.disconnect();
    if (!logoutSuccess) {
      LOG.warn("Logout failed while disconnecting, error code - "
          + client.getReplyCode());
    }
  }
}
 
Example 40
Project: hadoop-oss   File: FTPFileSystem.java   View source code 5 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.
 * @throws IOException on IO problems other than FileNotFoundException
 */
private boolean exists(FTPClient client, Path file) throws IOException {
  try {
    getFileStatus(client, file);
    return true;
  } catch (FileNotFoundException fnfe) {
    return false;
  }
}