Java Code Examples for org.apache.commons.net.ftp.FTPReply#isPositiveCompletion()
The following examples show how to use
org.apache.commons.net.ftp.FTPReply#isPositiveCompletion() .
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: FtpFileUtil.java From hsac-fitnesse-fixtures with Apache License 2.0 | 6 votes |
/** * Connect and login on given FTP server with provided credentials. * @param hostName the FTP server host name to connect * @param port the port to connect * @param userName the user name * @param password the password */ public static void connectAndLoginOnFTPServer(FTPClient ftpClient, String hostName, Integer port, String userName, String password) { try { if (port != null && port.intValue() > 0) { ftpClient.connect(hostName, port); } else { ftpClient.connect(hostName); } if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { throw new IOException(String.format("FTP server '%s' refused connection.", hostName)); } // try to login if (!ftpClient.login(userName, password)) { throw new IOException(String.format("Unable to login to FTP server '%s'.", hostName)); } } catch (IOException ex) { throw new RuntimeException( String.format("Unable to connect and login to FTP server '%s'. Cause: ", hostName), ex); } }
Example 2
Source File: FTPNetworkClient.java From FireFiles with Apache License 2.0 | 6 votes |
@Override public boolean connectClient() throws IOException { boolean isLoggedIn = true; client.setAutodetectUTF8(true); client.setControlEncoding("UTF-8"); client.connect(host, port); client.setFileType(FTP.BINARY_FILE_TYPE); client.enterLocalPassiveMode(); client.login(username, password); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { client.disconnect(); LogUtils.LOGD(TAG, "Negative reply form FTP server, aborting, id was {}:"+ reply); //throw new IOException("failed to connect to FTP server"); isLoggedIn = false; } return isLoggedIn; }
Example 3
Source File: FTPNetworkClient.java From FireFiles with Apache License 2.0 | 6 votes |
@Override public boolean connectClient() throws IOException { boolean isLoggedIn = true; client.setAutodetectUTF8(true); client.setControlEncoding("UTF-8"); client.connect(host, port); client.setFileType(FTP.BINARY_FILE_TYPE); client.enterLocalPassiveMode(); client.login(username, password); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { client.disconnect(); LogUtils.LOGD(TAG, "Negative reply form FTP server, aborting, id was {}:"+ reply); //throw new IOException("failed to connect to FTP server"); isLoggedIn = false; } return isLoggedIn; }
Example 4
Source File: cfFTPData.java From openbd-core with GNU General Public License v3.0 | 6 votes |
public boolean siteCmd(String cmd) { if ( !ftpclient.isConnected() ){ errorText = "not connected"; succeeded = false; return false; } boolean bResult = false; try{ bResult = ftpclient.sendSiteCommand(cmd); errorCode = ftpclient.getReplyCode(); succeeded = FTPReply.isPositiveCompletion(errorCode); }catch(Exception e){ errorCode = ftpclient.getReplyCode(); errorText = e.getMessage(); }finally{ setStatusData(); } return bResult; }
Example 5
Source File: cfFTPData.java From openbd-core with GNU General Public License v3.0 | 6 votes |
public boolean makeDirectory(String file) { if ( !ftpclient.isConnected() ){ errorText = "not connected"; succeeded = false; return false; } boolean bResult = false; try{ bResult = ftpclient.makeDirectory(file); errorCode = ftpclient.getReplyCode(); succeeded = FTPReply.isPositiveCompletion(errorCode); }catch(Exception e){ errorCode = ftpclient.getReplyCode(); errorText = e.getMessage(); }finally{ setStatusData(); } return bResult; }
Example 6
Source File: FTPUtils.java From TranskribusCore with GNU General Public License v3.0 | 5 votes |
public static void connectToFTP(FTPSClient ftp, String ftpServer, int ftpPort) throws SocketException, IOException { ftp.connect(ftpServer, ftpPort); // After connection attempt, you should check the reply code to verify // success. int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new IOException("FTP server refused connection, reply code: " + reply); } logger.debug("Connected to " + ftpServer + "."+ftp.getReplyString()); }
Example 7
Source File: FtpUtil.java From AndroidRobot with Apache License 2.0 | 5 votes |
/** * @return 判断是否登入成功 * */ public boolean ftpLogin() { boolean isLogin = false; FTPClientConfig ftpClientConfig = new FTPClientConfig(); ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID()); this.ftpClient.setControlEncoding("GBK"); this.ftpClient.configure(ftpClientConfig); try { if (this.intPort > 0) { this.ftpClient.connect(this.strIp, this.intPort); } else { this.ftpClient.connect(this.strIp); } // FTP服务器连接回答 int reply = this.ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { this.ftpClient.disconnect(); System.out.println("登录FTP服务失败!"); return isLogin; } this.ftpClient.login(this.user, this.password); // 设置传输协议 this.ftpClient.enterLocalPassiveMode(); this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); System.out.println("恭喜" + this.user + "成功登陆FTP服务器"); //logger.info("恭喜" + this.user + "成功登陆FTP服务器"); isLogin = true; } catch (Exception e) { e.printStackTrace(); System.out.println(this.user + "登录FTP服务失败!" + e.getMessage()); //logger.error(this.user + "登录FTP服务失败!" + e.getMessage()); } this.ftpClient.setBufferSize(1024 * 2); this.ftpClient.setDataTimeout(30 * 1000); return isLogin; }
Example 8
Source File: FtpUtil.java From util with Apache License 2.0 | 5 votes |
/** * 从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 9
Source File: FTPClientWrapper.java From commons-vfs with Apache License 2.0 | 5 votes |
private FTPFile[] listFilesInDirectory(final String relPath) throws IOException { FTPFile[] files; // VFS-307: no check if we can simply list the files, this might fail if there are spaces in the path files = getFtpClient().listFiles(relPath); if (FTPReply.isPositiveCompletion(getFtpClient().getReplyCode())) { return files; } // VFS-307: now try the hard way by cd'ing into the directory, list and cd back // if VFS is required to fallback here the user might experience a real bad FTP performance // as then every list requires 4 ftp commands. String workingDirectory = null; if (relPath != null) { workingDirectory = getFtpClient().printWorkingDirectory(); if (!getFtpClient().changeWorkingDirectory(relPath)) { return null; } } files = getFtpClient().listFiles(); if (relPath != null && !getFtpClient().changeWorkingDirectory(workingDirectory)) { throw new FileSystemException("vfs.provider.ftp.wrapper/change-work-directory-back.error", workingDirectory); } return files; }
Example 10
Source File: FTPWriteFeature.java From cyberduck with GNU General Public License v3.0 | 5 votes |
@Override public void close() throws IOException { if(close.get()) { log.warn(String.format("Skip double close of stream %s", this)); return; } try { super.close(); if(session.isConnected()) { // Read 226 status after closing stream reply = session.getClient().getReply(); if(!FTPReply.isPositiveCompletion(reply)) { final String text = session.getClient().getReplyString(); if(status.isSegment()) { // Ignore 451 and 426 response because stream was prematurely closed log.warn(String.format("Ignore unexpected reply %s when completing file segment %s", text, status)); } else if(!status.isComplete()) { log.warn(String.format("Ignore unexpected reply %s with incomplete transfer status %s", text, status)); } else { log.warn(String.format("Unexpected reply %s when completing file download with status %s", text, status)); throw new FTPException(session.getClient().getReplyCode(), text); } } } } finally { close.set(true); } }
Example 11
Source File: PooledFTPConnection.java From CloverETL-Engine with GNU Lesser General Public License v2.1 | 5 votes |
public void connect() throws IOException { if (ftp.isConnected()) { return; } // FTPClientConfig config = new FTPClientConfig(); // config.setServerTimeZoneId("GMT+0"); // ftp.configure(config); ftp.setListHiddenFiles(true); UserInfo userInfo = UserInfo.fromAuthority(authority); try { int port = authority.getPort(); if (port < 0) { port = 21; } ftp.connect(authority.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$ } ftp.printWorkingDirectory(); // CLO-4241 } catch (IOException ioe) { IOException outer = new IOException(FileOperationMessages.getString("FTPOperationHandler.connection_failed"), ioe); try { disconnect(); } catch (IOException disconnectException) { outer.addSuppressed(disconnectException); // CLO-4404 } throw outer; //$NON-NLS-1$ } }
Example 12
Source File: Client.java From nutch-htmlunit with Apache License 2.0 | 5 votes |
/*** * Login to the FTP server using the provided username and password. * <p> * @param username The username to login under. * @param password The password to use. * @return True if successfully completed, false if not. * @exception FTPConnectionClosedException * If the FTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send FTP reply code 421. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public boolean login(String username, String password) throws IOException { user(username); if (FTPReply.isPositiveCompletion(getReplyCode())) return true; // If we get here, we either have an error code, or an intermmediate // reply requesting password. if (!FTPReply.isPositiveIntermediate(getReplyCode())) return false; return FTPReply.isPositiveCompletion(pass(password)); }
Example 13
Source File: Client.java From anthelion with Apache License 2.0 | 5 votes |
private boolean _notBadReply(int reply) { if (FTPReply.isPositiveCompletion(reply)) { // do nothing } else if (reply == 426) { // FTPReply.TRANSFER_ABORTED // some ftp servers reply 426, e.g., // foggy FTP server (Version wu-2.6.2(2) // there is second reply witing? no! //getReply(); } else if (reply == 450) { // FTPReply.FILE_ACTION_NOT_TAKEN // some ftp servers reply 450, e.g., // ProFTPD [ftp.kernel.org] // there is second reply witing? no! //getReply(); } else if (reply == 451) { // FTPReply.ACTION_ABORTED // some ftp servers reply 451, e.g., // ProFTPD [ftp.kernel.org] // there is second reply witing? no! //getReply(); } else if (reply == 451) { // FTPReply.ACTION_ABORTED } else { // what other kind of ftp server out there? return false; } return true; }
Example 14
Source File: FTPsClient.java From iaf with Apache License 2.0 | 4 votes |
private Object _readReply(InputStream in, boolean concatenateLines) throws IOException { // obtain the result BufferedReader reader = new BufferedReader(StreamUtil.getCharsetDetectingInputStreamReader(in, FTP_CLIENT_CHARSET)); int replyCode = 0; StringBuffer reply = new StringBuffer(); List replyList = new ArrayList(); String line = reader.readLine(); if (line == null) throw new FTPConnectionClosedException("Connection closed without indication."); reply.append(line).append("\n"); replyList.add(line); // In case we run into an anomaly we don't want fatal index exceptions // to be thrown. int length = line.length(); if (length < 3) throw new MalformedServerReplyException("Truncated server reply: " + line); try { String code = line.substring(0, 3); replyCode = Integer.parseInt(code); } catch (NumberFormatException e) { MalformedServerReplyException mfre = new MalformedServerReplyException("Could not parse response code.\nServer Reply [" + line+"]"); mfre.initCause(e); throw mfre; } // Get extra lines if message continues. if (length > 3 && line.charAt(3) == '-') { do { line = reader.readLine(); if (line == null) throw new FTPConnectionClosedException("Connection closed without indication after having read ["+reply.toString()+"]"); reply.append(line).append("\n"); replyList.add(line); } while (!(line.length() >= 4 && line.charAt(3) != '-' && Character.isDigit(line.charAt(0)))); } if (replyCode == FTPReply.SERVICE_NOT_AVAILABLE) throw new FTPConnectionClosedException("FTP response 421 received. Server closed connection."); if (!FTPReply.isPositiveCompletion(replyCode)) throw new IOException("Exception while sending command \n" + reply.toString()); log.debug("_readReply ["+reply.toString()+"]"); if (concatenateLines) { return reply.toString(); } return (String[])replyList.toArray(new String[0]); }
Example 15
Source File: FTPServerTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 4 votes |
/** * 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 16
Source File: Client.java From nutch-htmlunit with Apache License 2.0 | 4 votes |
/*** * Fetches the system type name from the server and returns the string. * This value is cached for the duration of the connection after the * first call to this method. In other words, only the first time * that you invoke this method will it issue a SYST command to the * FTP server. FTPClient will remember the value and return the * cached value until a call to disconnect. * <p> * @return The system type name obtained from the server. null if the * information could not be obtained. * @exception FTPConnectionClosedException * If the FTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send FTP reply code 421. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public String getSystemName() throws IOException, FtpExceptionBadSystResponse { //if (syst() == FTPReply.NAME_SYSTEM_TYPE) // Technically, we should expect a NAME_SYSTEM_TYPE response, but // in practice FTP servers deviate, so we soften the condition to // a positive completion. if (__systemName == null && FTPReply.isPositiveCompletion(syst())) { __systemName = (getReplyStrings()[0]).substring(4); } else { throw new FtpExceptionBadSystResponse( "Bad response of SYST: " + getReplyString()); } return __systemName; }
Example 17
Source File: FtpService.java From cerberus-source with GNU General Public License v3.0 | 4 votes |
@Override public AnswerItem<AppService> getFTP(HashMap<String, String> informations, FTPClient ftp, AppService myResponse) throws IOException { MessageEvent message = null; AnswerItem<AppService> result = new AnswerItem<>(); LOG.info("Start retrieving ftp file"); FTPFile[] ftpFile = ftp.listFiles(informations.get("path")); if (ftpFile.length != 0) { InputStream done = ftp.retrieveFileStream(informations.get("path")); boolean success = ftp.completePendingCommand(); myResponse.setResponseHTTPCode(ftp.getReplyCode()); if (success && FTPReply.isPositiveCompletion(myResponse.getResponseHTTPCode())) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int n = 0; while ((n = done.read(buf)) >= 0) { baos.write(buf, 0, n); } byte[] content = baos.toByteArray(); myResponse.setFile(content); LOG.info("ftp file successfully retrieve"); message = new MessageEvent(MessageEventEnum.ACTION_SUCCESS_CALLSERVICE); message.setDescription(message.getDescription().replace("%SERVICEMETHOD%", "GET")); message.setDescription(message.getDescription().replace("%SERVICEPATH%", informations.get("path"))); result.setResultMessage(message); String expectedContent = IOUtils.toString(new ByteArrayInputStream(content), "UTF-8"); String extension = testCaseExecutionFileService.checkExtension(informations.get("path"), ""); if ("JSON".equals(extension) || "XML".equals(extension) || "TXT".equals(extension)) { myResponse.setResponseHTTPBody(expectedContent); } myResponse.setResponseHTTPBodyContentType(extension); result.setItem(myResponse); baos.close(); } else { LOG.error("Error when downloading the file. Something went wrong"); message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE); message.setDescription(message.getDescription().replace("%SERVICE%", informations.get("path"))); message.setDescription(message.getDescription().replace("%DESCRIPTION%", "Error when downloading the file. Something went wrong")); result.setResultMessage(message); } done.close(); } else { LOG.error("The file is not present on FTP server. Please check the FTP path"); message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE); message.setDescription(message.getDescription().replace("%SERVICE%", informations.get("path"))); message.setDescription(message.getDescription().replace("%DESCRIPTION%", "Impossible to retrieve the file. Please check the FTP path")); result.setResultMessage(message); } return result; }
Example 18
Source File: Client.java From anthelion with Apache License 2.0 | 3 votes |
/*** * Sets the file type to be transferred. This should be one of * <code> FTP.ASCII_FILE_TYPE </code>, <code> FTP.IMAGE_FILE_TYPE </code>, * etc. The file type only needs to be set when you want to change the * type. After changing it, the new type stays in effect until you change * it again. The default file type is <code> FTP.ASCII_FILE_TYPE </code> * if this method is never called. * <p> * @param fileType The <code> _FILE_TYPE </code> constant indcating the * type of file. * @return True if successfully completed, false if not. * @exception FTPConnectionClosedException * If the FTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send FTP reply code 421. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public boolean setFileType(int fileType) throws IOException { if (FTPReply.isPositiveCompletion(type(fileType))) { __fileType = fileType; __fileFormat = FTP.NON_PRINT_TEXT_FORMAT; return true; } return false; }
Example 19
Source File: Client.java From anthelion with Apache License 2.0 | 2 votes |
/*** * Sends a NOOP command to the FTP server. This is useful for preventing * server timeouts. * <p> * @return True if successfully completed, false if not. * @exception FTPConnectionClosedException * If the FTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send FTP reply code 421. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public boolean sendNoOp() throws IOException { return FTPReply.isPositiveCompletion(noop()); }
Example 20
Source File: Client.java From anthelion with Apache License 2.0 | 2 votes |
/*** * Logout of the FTP server by sending the QUIT command. * <p> * @return True if successfully completed, false if not. * @exception FTPConnectionClosedException * If the FTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send FTP reply code 421. This exception may be caught either * as an IOException or independently as itself. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public boolean logout() throws IOException { return FTPReply.isPositiveCompletion(quit()); }