Java Code Examples for org.apache.commons.net.ftp.ftpclient#logout()

The following examples show how to use org.apache.commons.net.ftp.ftpclient#logout() . 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: 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 2
Source File: FtpUtil.java    From SSM with Apache License 2.0 6 votes vote down vote up
public static boolean uploadPicture(String FTP_HOSTNAME,int FTP_PORT,String FTP_USERNAME,String FTP_PASSWORD,String FTP_REMOTE_PATH,String picName,InputStream fileInputStream)throws IOException {
    //创建一个FtpClient
    FTPClient ftpClient = new FTPClient();
    //连接的ip和端口号
    ftpClient.connect(FTP_HOSTNAME,FTP_PORT);
    //登陆的用户名和密码
    ftpClient.login(FTP_USERNAME,FTP_PASSWORD);
    //将文件转换成输入流
    //修改文件的存放地址
    ftpClient.changeWorkingDirectory(FTP_REMOTE_PATH);
    //设置文件的上传格式
    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    //将我们的文件流以什么名字存放
    boolean result = ftpClient.storeFile(picName,fileInputStream);
    //退出
    ftpClient.logout();
    return result;
}
 
Example 3
Source File: Ftp.java    From Lottery with GNU General Public License v2.0 6 votes vote down vote up
private FTPClient getClient() throws SocketException, IOException {
	FTPClient ftp = new FTPClient();
	ftp.addProtocolCommandListener(new PrintCommandListener(
			new PrintWriter(System.out)));
	ftp.setDefaultPort(getPort());
	ftp.connect(getIp());
	int reply = ftp.getReplyCode();
	if (!FTPReply.isPositiveCompletion(reply)) {
		log.warn("FTP server refused connection: {}", getIp());
		ftp.disconnect();
		return null;
	}
	if (!ftp.login(getUsername(), getPassword())) {
		log.warn("FTP server refused login: {}, user: {}", getIp(),
				getUsername());
		ftp.logout();
		ftp.disconnect();
		return null;
	}
	ftp.setControlEncoding(getEncoding());
	ftp.setFileType(FTP.BINARY_FILE_TYPE);
	ftp.enterLocalPassiveMode();
	return ftp;
}
 
Example 4
Source File: FtpUtils.java    From kkFileView with Apache License 2.0 6 votes vote down vote up
public static void download(String ftpUrl, String localFilePath, String ftpUsername, String ftpPassword, String ftpControlEncoding) throws IOException {
    String username = StringUtils.isEmpty(ftpUsername) ? ConfigConstants.getFtpUsername() : ftpUsername;
    String password = StringUtils.isEmpty(ftpPassword) ? ConfigConstants.getFtpPassword() : ftpPassword;
    String controlEncoding = StringUtils.isEmpty(ftpControlEncoding) ? ConfigConstants.getFtpControlEncoding() : ftpControlEncoding;
    URL url = new URL(ftpUrl);
    String host = url.getHost();
    int port = (url.getPort() == -1) ? url.getDefaultPort() : url.getPort();
    String remoteFilePath = url.getPath();
    LOGGER.debug("FTP connection url:{}, username:{}, password:{}, controlEncoding:{}, localFilePath:{}", ftpUrl, username, password, controlEncoding, localFilePath);
    FTPClient ftpClient = connect(host, port, username, password, controlEncoding);
    OutputStream outputStream = new FileOutputStream(localFilePath);
    ftpClient.enterLocalPassiveMode();
    boolean downloadResult = ftpClient.retrieveFile(new String(remoteFilePath.getBytes(controlEncoding), StandardCharsets.ISO_8859_1), outputStream);
    LOGGER.debug("FTP download result {}", downloadResult);
    outputStream.flush();
    outputStream.close();
    ftpClient.logout();
    ftpClient.disconnect();
}
 
Example 5
Source File: FtpHelper.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Connect.
 *
 * @throws Exception the exception
 */
@Override
public void connect() throws Exception {
	try {
		ftpClient = new FTPClient();
		ftpClient.connect(host, port);
		if (usePassiveMode) {
			ftpClient.enterLocalPassiveMode();
		}
		if (!ftpClient.login(user, password)) {
			ftpClient.logout();
			throw new Exception("Authentication failed");
           }
	} catch (Exception e) {
		close();
		throw new Exception("Connection failed");
	}
}
 
Example 6
Source File: FTPFileSystem.java    From hadoop 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 7
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 8
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 9
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 10
Source File: FTPOperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected FTPClient connect(URI uri) throws IOException {
		FTPClient ftp = new FTPClient();
//		FTPClientConfig config = new FTPClientConfig();
//		config.setServerTimeZoneId("GMT+0");
//		ftp.configure(config);
		ftp.setListHiddenFiles(true);
		UserInfo userInfo = UserInfo.fromURI(uri);
		try {
			int port = uri.getPort();
			if (port < 0) {
				port = 21;
			}
			ftp.connect(uri.getHost(), port);
			if (!ftp.login(userInfo.getUser(), userInfo.getPassword())) {
	            ftp.logout();
	            throw new IOException(FileOperationMessages.getString("FTPOperationHandler.authentication_failed")); //$NON-NLS-1$
	        }
			ftp.enterLocalPassiveMode();
			
			int reply = ftp.getReplyCode();
	        if (!FTPReply.isPositiveCompletion(reply)) {
	        	throw new IOException(FileOperationMessages.getString("FTPOperationHandler.connection_failed")); //$NON-NLS-1$
	        }
	        return ftp;
		} catch (IOException ioe) {
			disconnect(ftp);
			throw new IOException(FileOperationMessages.getString("FTPOperationHandler.connection_failed"), ioe); //$NON-NLS-1$
		}
	}
 
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 hadoop-gpu 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: 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 14
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 15
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 16
Source File: TestCase.java    From springboot-ureport with Apache License 2.0 5 votes vote down vote up
/**
 * Description: 向FTP服务器上传文件
 * @Version1.0 Jul 27, 2008 4:31:09 PM by 崔红保([email protected])创建
 * @param url FTP服务器hostname
 * @param port FTP服务器端口
 * @param username FTP登录账号
 * @param password FTP登录密码
 * @param path FTP服务器保存目录
 * @param filename 上传到FTP服务器上的文件名
 * @param input 输入流
 * @return 成功返回true,否则返回false
 */
public static boolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {
	boolean success = false;
	FTPClient ftp = new FTPClient();
	try {
		int reply;
		ftp.connect(url, port);//连接FTP服务器
		//如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
		ftp.login(username, password);//登录
		reply = ftp.getReplyCode();
		if (!FTPReply.isPositiveCompletion(reply)) {
			ftp.disconnect();
			return success;
		}
		ftp.changeWorkingDirectory(path);
		ftp.storeFile(filename, input);			
		
		input.close();
		ftp.logout();
		success = true;
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		if (ftp.isConnected()) {
			try {
				ftp.disconnect();
			} catch (IOException ioe) {
			}
		}
	}
	return success;
}
 
Example 17
Source File: FTPClientFactory.java    From springboot-ureport with Apache License 2.0 5 votes vote down vote up
/**
 * 销毁一个FTPClient对象
 */
@Override
public void destroyObject(FTPClient ftpClient) throws Exception {
	try {
		if(ftpClient != null && ftpClient.isConnected()){
			ftpClient.logout();
		}
	} catch (Exception e) {
		e.printStackTrace();
	}finally{
		ftpClient.disconnect();
	}
}
 
Example 18
Source File: FtpVerifierExtension.java    From syndesis with Apache License 2.0 4 votes vote down vote up
private static void verifyCredentials(ResultBuilder builder, Map<String, Object> parameters) {

        final String host = ConnectorOptions.extractOption(parameters, "host");
        final Integer port = ConnectorOptions.extractOptionAndMap(parameters, "port", Integer::parseInt, 21);
        final String userName = ConnectorOptions.extractOption(parameters, "username", "anonymous");

        String password = "";
        if (! "anonymous".equals(userName)) {
            password = ConnectorOptions.extractOption(parameters, "password", password);
        }

        int reply;
        FTPClient ftp = new FTPClient();

        String illegalParametersMessage = "Unable to connect to the FTP server";
        boolean hasValidParameters = false;

        try {
            ftp.connect(host, port);
            reply = ftp.getReplyCode();
            hasValidParameters = FTPReply.isPositiveCompletion(reply);
        } catch (IOException e) {
            illegalParametersMessage = e.getMessage();
        }

        if (!hasValidParameters) {
            builder.error(
                    ResultErrorBuilder.withCodeAndDescription(VerificationError.StandardCode.ILLEGAL_PARAMETER_VALUE,
                            illegalParametersMessage).parameterKey("host").parameterKey("port").build());

        } else {

            boolean isAuthenticated = false;
            String authentionErrorMessage = "Authentication failed";

            try {
                isAuthenticated = ftp.login(userName, password);
            } catch (IOException ioe) {
                authentionErrorMessage = ioe.getMessage();
            }
            if (!isAuthenticated) {

                builder.error(ResultErrorBuilder
                        .withCodeAndDescription(VerificationError.StandardCode.AUTHENTICATION, authentionErrorMessage)
                        .parameterKey("username").parameterKey("password").build());

            } else {
                try {
                    ftp.logout();
                    ftp.disconnect();
                } catch (IOException ignored) {
                    // ignore
                }

            }
        }

    }
 
Example 19
Source File: CfdaServiceImpl.java    From kfs with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * @return
 * @throws IOException
 */
public SortedMap<String, CFDA> getGovCodes() throws IOException {
    Calendar calendar = dateTimeService.getCurrentCalendar();
    SortedMap<String, CFDA> govMap = new TreeMap<String, CFDA>();

    // ftp://ftp.cfda.gov/programs09187.csv
    String govURL = parameterService.getParameterValueAsString(CfdaBatchStep.class, KFSConstants.SOURCE_URL_PARAMETER);
    String fileName = StringUtils.substringAfterLast(govURL, "/");
    govURL = StringUtils.substringBeforeLast(govURL, "/");
    if (StringUtils.contains(govURL, "ftp://")) {
        govURL = StringUtils.remove(govURL, "ftp://");
    }

    // need to pull off the '20' in 2009
    String year = "" + calendar.get(Calendar.YEAR);
    year = year.substring(2, 4);
    fileName = fileName + year;

    // the last 3 numbers in the file name are the day of the year, but the files are from "yesterday"
    fileName = fileName + String.format("%03d", calendar.get(Calendar.DAY_OF_YEAR) - 1);
    fileName = fileName + ".csv";

    LOG.info("Getting government file: " + fileName + " for update");

    InputStream inputStream = null;
    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(govURL);
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            LOG.error("FTP connection to server not established.");
            throw new IOException("FTP connection to server not established.");
        }

        boolean isLoggedIn = ftp.login("anonymous", "");
        if (!isLoggedIn) {
            LOG.error("Could not login as anonymous.");
            throw new IOException("Could not login as anonymous.");
        }

        LOG.info("Successfully connected and logged in");
        ftp.enterLocalPassiveMode();
        inputStream = ftp.retrieveFileStream(fileName);
        if (inputStream != null) {
            LOG.info("reading input stream");
            InputStreamReader screenReader = new InputStreamReader(inputStream);
            BufferedReader screen = new BufferedReader(screenReader);

            CSVReader csvReader = new CSVReader(screenReader, ',', '"', 1);
            List<String[]> lines = csvReader.readAll();
            for (String[] line : lines) {
                String title = line[0];
                String number = line[1];

                CFDA cfda = new CFDA();
                cfda.setCfdaNumber(number);
                cfda.setCfdaProgramTitleName(title);

                govMap.put(number, cfda);
            }
        }

        ftp.logout();
        ftp.disconnect();
    }
    finally {
        if (ftp.isConnected()) {
            ftp.disconnect();
        }
    }

    return govMap;
}
 
Example 20
Source File: RinexNavigation.java    From GNSS_Compare with Apache License 2.0 4 votes vote down vote up
private RinexNavigationParserGps getFromFTP(String url) throws IOException{
	RinexNavigationParserGps rnp = null;

	String origurl = url;
	if(negativeChache.containsKey(url)){
		if(System.currentTimeMillis()-negativeChache.get(url).getTime() < 60*60*1000){
			throw new FileNotFoundException("cached answer");
		}else{
			negativeChache.remove(url);
		}
	}

	String filename = url.replaceAll("[ ,/:]", "_");
	if(filename.endsWith(".Z")) filename = filename.substring(0, filename.length()-2);
	File rnf = new File(RNP_CACHE,filename);

	if(rnf.exists()){
     System.out.println(url+" from cache file "+rnf);
     rnp = new RinexNavigationParserGps(rnf);
     try{
       rnp.init();
       return rnp;
     }
     catch( Exception e ){
       rnf.delete();
     }
	}
	
	// if the file doesn't exist of is invalid
	System.out.println(url+" from the net.");
	FTPClient ftp = new FTPClient();

	try {
		int reply;
		System.out.println("URL: "+url);
		url = url.substring("ftp://".length());
		String server = url.substring(0, url.indexOf('/'));
		String remoteFile = url.substring(url.indexOf('/'));
		String remotePath = remoteFile.substring(0,remoteFile.lastIndexOf('/'));
		remoteFile = remoteFile.substring(remoteFile.lastIndexOf('/')+1);

		ftp.connect(server);
		ftp.login("anonymous", "[email protected]");

		System.out.print(ftp.getReplyString());

		// After connection attempt, you should check the reply code to
		// verify
		// success.
		reply = ftp.getReplyCode();

		if (!FTPReply.isPositiveCompletion(reply)) {
			ftp.disconnect();
			System.err.println("FTP server refused connection.");
			return null;
		}

		ftp.enterLocalPassiveMode();
		ftp.setRemoteVerificationEnabled(false);

		System.out.println("cwd to "+remotePath+" "+ftp.changeWorkingDirectory(remotePath));
		System.out.println(ftp.getReplyString());
		ftp.setFileType(FTP.BINARY_FILE_TYPE);
		System.out.println(ftp.getReplyString());

		System.out.println("open "+remoteFile);
		InputStream is = ftp.retrieveFileStream(remoteFile);
		System.out.println(ftp.getReplyString());
		if(ftp.getReplyString().startsWith("550")){
			negativeChache.put(origurl, new Date());
			throw new FileNotFoundException();
		}
     InputStream uis = is;

		if(remoteFile.endsWith(".Z")){
			uis = new UncompressInputStream(is);
		}

		rnp = new RinexNavigationParserGps(uis,rnf);
		rnp.init();
		is.close();


		ftp.completePendingCommand();

		ftp.logout();
	} 
	finally {
		if (ftp.isConnected()) {
			try {
				ftp.disconnect();
			} catch (IOException ioe) {
				// do nothing
			}
		}
	}
	return rnp;
}