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

The following examples show how to use org.apache.commons.net.ftp.FTPClient#isConnected() . 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: ImgServiceImpl.java    From Tbed with GNU Affero General Public License v3.0 6 votes vote down vote up
public void delectFTP(Keys key, String fileName) {
    FTPClient ftp = new FTPClient();
    String[] host = key.getEndpoint().split("\\:");
    String h = host[0];
    Integer p = Integer.parseInt(host[1]);
    try {
        if(!ftp.isConnected()){
            ftp.connect(h,p);
        }
        ftp.login(key.getAccessKey(), key.getAccessSecret());
        ftp.deleteFile(fileName);
    } catch (IOException e) {
        e.printStackTrace();
        Print.warning("删除FTP存储的图片失败");
    }
}
 
Example 2
Source File: FTPUtil.java    From seed with Apache License 2.0 6 votes vote down vote up
/**
 * 登出FTP服务器
 * <p>
 *     由于本工具类会自动维护FTPClient连接,故调用该方法便可直接登出FTP
 * </p>
 */
public static void logout(){
    FTPClient ftpClient = ftpClientMap.get();
    ftpClientMap.remove();
    if(null != ftpClient){
        String ftpRemoteAddress = ftpClient.getRemoteAddress().toString();
        try{
            ftpClient.logout();
            LogUtil.getLogger().debug("FTP服务器[" + ftpRemoteAddress + "]登出成功...");
        }catch (IOException e){
            LogUtil.getLogger().warn("FTP服务器[" + ftpRemoteAddress + "]登出时发生异常,堆栈轨迹如下", e);
        }finally{
            if(ftpClient.isConnected()){
                try {
                    ftpClient.disconnect();
                    LogUtil.getLogger().debug("FTP服务器[" + ftpRemoteAddress + "]连接释放完毕...");
                } catch (IOException ioe) {
                    LogUtil.getLogger().warn("FTP服务器[" + ftpRemoteAddress + "]连接释放时发生异常,堆栈轨迹如下", ioe);
                }
            }
        }
    }
}
 
Example 3
Source File: FtpFileUtil.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
/**
 * Disconnect and logout given FTP client.
 * @param hostName the FTP server host name
 */
public static void disconnectAndLogoutFromFTPServer(FTPClient ftpClient, String hostName) {
    try {
        // logout and disconnect
        if (ftpClient != null && ftpClient.isConnected()) {
            ftpClient.logout();
            ftpClient.disconnect();
        }
    } catch (IOException e) {
        // what the hell?!
        throw new RuntimeException("Unable to logout and disconnect from : " + hostName, e);
    }
}
 
Example 4
Source File: FTPOperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void disconnect(FTPClient ftp) {
	if ((ftp != null) && ftp.isConnected()) {
		try {
			ftp.logout();
			ftp.disconnect();
		} catch(IOException ex) {
			ex.printStackTrace();
		}
	}
}
 
Example 5
Source File: FtpServiceImp.java    From imageServer with Apache License 2.0 5 votes vote down vote up
/**
 * 删除FTP服务器上的指定文件
 *
 * @param filePath 被删除文件在FTP服务器上的全路径
 * @return true : 删除成功
 * @throws IOException 删除失败
 */
@Override
synchronized public boolean deleteFile(String filePath) throws IOException {
    FTPClient ftpClient = FTPUtil.getFTPClient(ftpConnectAttr);
    boolean result = ftpClient != null && ftpClient.deleteFile(filePath);
    if(result && ftpClient.isConnected())
        ftpClient.disconnect();
    return result;
}
 
Example 6
Source File: FtpServiceImp.java    From imageServer with Apache License 2.0 5 votes vote down vote up
/**
 * 删除FTP服务器上的指定文件
 *
 * @param directory 文件目录
 * @param fileName  文件名
 * @return true : 删除成功
 * @throws IOException 删除失败
 */
synchronized public boolean deleteFile(String directory, String fileName) throws IOException {
    log.info("删除FTP文件");
    log.info("被删除的文件目录:" + directory);
    log.info("被删除的文件:" + fileName);
    FTPClient ftpClient = FTPUtil.getFTPClient(ftpConnectAttr);
    boolean result = ftpClient != null && ftpClient.deleteFile(directory + "/" + fileName);
    if(result && ftpClient.isConnected())
        ftpClient.disconnect();
    return result;
}
 
Example 7
Source File: FTPFileSystem.java    From big-c with Apache License 2.0 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 8
Source File: BugReportSenderFtp.java    From YalpStore with GNU General Public License v2.0 5 votes vote down vote up
static private void closeSilently(FTPClient ftpClient) {
    try {
        ftpClient.logout();
        if (ftpClient.isConnected()) {
            ftpClient.disconnect();
        }
    } catch (IOException e) {
        // Ignore
    }
}
 
Example 9
Source File: FTPInputStream.java    From hadoop with Apache License 2.0 5 votes vote down vote up
public FTPInputStream(InputStream stream, FTPClient client,
    FileSystem.Statistics stats) {
  if (stream == null) {
    throw new IllegalArgumentException("Null InputStream");
  }
  if (client == null || !client.isConnected()) {
    throw new IllegalArgumentException("FTP client null or not connected");
  }
  this.wrappedStream = stream;
  this.client = client;
  this.stats = stats;
  this.pos = 0;
  this.closed = false;
}
 
Example 10
Source File: FTPDropbox2Publisher.java    From datasync with MIT License 5 votes vote down vote up
/**
 * Closes the given FTPS connection (if one is open)
 *
 * @param ftp authenticated ftps object
 */
private static void closeFTPConnection(FTPClient ftp) {
    if(ftp.isConnected()) {
        try {
            ftp.logout();
            ftp.disconnect();
        } catch(IOException ioe) {
            // do nothing
        }
    }
}
 
Example 11
Source File: FtpUtils.java    From carina with Apache License 2.0 5 votes vote down vote up
public static void ftpDisconnect(FTPClient ftp) {
    try {
        if (ftp.isConnected()) {
            try {
                ftp.logout();
                ftp.disconnect();
            } catch (Exception ioe) {
                LOGGER.error("Exception while disconnecting ftp", ioe);
            }
        }
    } catch (Throwable thr) {
        LOGGER.error("Throwable while disconnecting ftp", thr);
    }
    LOGGER.debug("FTP has been successfully disconnected.");
}
 
Example 12
Source File: FTPFileSystem.java    From RDFS with Apache License 2.0 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 13
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 14
Source File: FtpConnectionFactory.java    From BigDataScript with Apache License 2.0 5 votes vote down vote up
/**
 * Disconnect and FTP client
 */
private void disconnect(FTPClient ftp, String key) {
	if (ftp == null) return;
	synchronized (ftp) {
		if (!ftp.isConnected()) return;
		try {
			ftp.disconnect();
		} catch (IOException e) {
			Gpr.debug("ERROR while disconnecting from '" + key + "'");
		}
	}
}
 
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: 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 17
Source File: FTPFileSystem.java    From hadoop 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);
  FileStatus status;
  try {
    status = getFileStatus(client, file);
  } catch (FileNotFoundException fnfe) {
    status = null;
  }
  if (status != null) {
    if (overwrite && !status.isDirectory()) {
      delete(client, file, false);
    } else {
      disconnect(client);
      throw new FileAlreadyExistsException("File already exists: " + file);
    }
  }
  
  Path parent = absolute.getParent();
  if (parent == null || !mkdirs(client, parent, FsPermission.getDirDefault())) {
    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 18
Source File: FtpUtil.java    From learning-taotaoMall with MIT License 4 votes vote down vote up
/** 
 * Description: 向FTP服务器上传文件 
 * @param host FTP服务器hostname 
 * @param port FTP服务器端口 
 * @param username FTP登录账号 
 * @param password FTP登录密码 
 * @param basePath FTP服务器基础目录
 * @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
 * @param filename 上传到FTP服务器上的文件名 
 * @param input 输入流 
 * @return 成功返回true,否则返回false 
 */
public static boolean uploadFile(String host, int port, String username, String password, String basePath, String filePath, String filename,
		InputStream input) {
	boolean result = false;
	FTPClient ftp = new FTPClient();
	try {
		int reply;
		ftp.connect(host, port);// 连接FTP服务器
		// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
		ftp.login(username, password);// 登录
		reply = ftp.getReplyCode();
		if (!FTPReply.isPositiveCompletion(reply)) {
			ftp.disconnect();
			return result;
		}
		//切换到上传目录
		if (!ftp.changeWorkingDirectory(basePath + filePath)) {
			//如果目录不存在创建目录
			String[] dirs = filePath.split("/");
			String tempPath = basePath;
			for (String dir : dirs) {
				if (null == dir || "".equals(dir))
					continue;
				tempPath += "/" + dir;
				if (!ftp.changeWorkingDirectory(tempPath)) {
					if (!ftp.makeDirectory(tempPath)) {
						return result;
					} else {
						ftp.changeWorkingDirectory(tempPath);
					}
				}
			}
		}
		//设置上传文件的类型为二进制类型
		ftp.setFileType(FTP.BINARY_FILE_TYPE);
		//上传文件
		if (!ftp.storeFile(filename, input)) {
			return result;
		}
		input.close();
		ftp.logout();
		result = true;
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		if (ftp.isConnected()) {
			try {
				ftp.disconnect();
			} catch (IOException ioe) {
			}
		}
	}
	return result;
}
 
Example 19
Source File: FTPFileSystem.java    From big-c 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);
  FileStatus status;
  try {
    status = getFileStatus(client, file);
  } catch (FileNotFoundException fnfe) {
    status = null;
  }
  if (status != null) {
    if (overwrite && !status.isDirectory()) {
      delete(client, file, false);
    } else {
      disconnect(client);
      throw new FileAlreadyExistsException("File already exists: " + file);
    }
  }
  
  Path parent = absolute.getParent();
  if (parent == null || !mkdirs(client, parent, FsPermission.getDirDefault())) {
    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: 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;
}