List of usage examples for org.apache.commons.net.ftp FTPReply isPositiveCompletion
public static boolean isPositiveCompletion(int reply)
From source file:org.apache.ftpserver.ssl.MinaClientAuthTest.java
public void testCommandChannel() throws Exception { assertTrue(client.login(ADMIN_USERNAME, ADMIN_PASSWORD)); assertTrue(FTPReply.isPositiveCompletion(client.noop())); }
From source file:org.apache.hadoop.fs.ftp.FTPFileSystem.java
/** * Connect to the FTP server using configuration parameters * * /* w w w . j a v a 2s.com*/ * @return An FTPClient instance * @throws IOException */ private FTPClient connect() throws IOException { FTPClient client = null; Configuration conf = getConf(); String host = conf.get("fs.ftp.host"); int port = conf.getInt("fs.ftp.host.port", FTP.DEFAULT_PORT); String user = conf.get("fs.ftp.user." + host); String password = conf.get("fs.ftp.password." + host); client = new FTPClient(); client.connect(host, port); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("Server - " + host + " refused connection on port - " + port); } else if (client.login(user, password)) { client.setFileTransferMode(FTP.BLOCK_TRANSFER_MODE); client.setFileType(FTP.BINARY_FILE_TYPE); client.setBufferSize(DEFAULT_BUFFER_SIZE); } else { throw new IOException("Login failed on server - " + host + ", port - " + port); } return client; }
From source file:org.apache.jmeter.protocol.ftp.sampler.FTPSampler.java
@Override public SampleResult sample(Entry e) { SampleResult res = new SampleResult(); res.setSuccessful(false); // Assume failure String remote = getRemoteFilename(); String local = getLocalFilename(); boolean binaryTransfer = isBinaryMode(); res.setSampleLabel(getName());/*from ww w. jav a 2 s . c om*/ final String label = getLabel(); res.setSamplerData(label); try { res.setURL(new URL(label)); } catch (MalformedURLException e1) { log.warn("Cannot set URL: " + e1.getLocalizedMessage()); } InputStream input = null; OutputStream output = null; res.sampleStart(); FTPClient ftp = new FTPClient(); try { savedClient = ftp; final int port = getPortAsInt(); if (port > 0) { ftp.connect(getServer(), port); } else { ftp.connect(getServer()); } res.latencyEnd(); int reply = ftp.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { if (ftp.login(getUsername(), getPassword())) { if (binaryTransfer) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } ftp.enterLocalPassiveMode();// should probably come from the setup dialog boolean ftpOK = false; if (isUpload()) { String contents = getLocalFileContents(); if (contents.length() > 0) { byte[] bytes = contents.getBytes(); // TODO - charset? input = new ByteArrayInputStream(bytes); res.setBytes(bytes.length); } else { File infile = new File(local); res.setBytes((int) infile.length()); input = new BufferedInputStream(new FileInputStream(infile)); } ftpOK = ftp.storeFile(remote, input); } else { final boolean saveResponse = isSaveResponse(); ByteArrayOutputStream baos = null; // No need to close this OutputStream target = null; // No need to close this if (saveResponse) { baos = new ByteArrayOutputStream(); target = baos; } if (local.length() > 0) { output = new FileOutputStream(local); if (target == null) { target = output; } else { target = new TeeOutputStream(output, baos); } } if (target == null) { target = new NullOutputStream(); } input = ftp.retrieveFileStream(remote); if (input == null) {// Could not access file or other error res.setResponseCode(Integer.toString(ftp.getReplyCode())); res.setResponseMessage(ftp.getReplyString()); } else { long bytes = IOUtils.copy(input, target); ftpOK = bytes > 0; if (saveResponse && baos != null) { res.setResponseData(baos.toByteArray()); if (!binaryTransfer) { res.setDataType(SampleResult.TEXT); } } else { res.setBytes((int) bytes); } } } if (ftpOK) { res.setResponseCodeOK(); res.setResponseMessageOK(); res.setSuccessful(true); } else { res.setResponseCode(Integer.toString(ftp.getReplyCode())); res.setResponseMessage(ftp.getReplyString()); } } else { res.setResponseCode(Integer.toString(ftp.getReplyCode())); res.setResponseMessage(ftp.getReplyString()); } } else { res.setResponseCode("501"); // TODO res.setResponseMessage("Could not connect"); //res.setResponseCode(Integer.toString(ftp.getReplyCode())); res.setResponseMessage(ftp.getReplyString()); } } catch (IOException ex) { res.setResponseCode("000"); // TODO res.setResponseMessage(ex.toString()); } finally { savedClient = null; if (ftp.isConnected()) { try { ftp.logout(); } catch (IOException ignored) { } try { ftp.disconnect(); } catch (IOException ignored) { } } IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } res.sampleEnd(); return res; }
From source file:org.apache.maven.wagon.providers.ftp.FtpWagon.java
protected void openConnectionInternal() throws ConnectionException, AuthenticationException { AuthenticationInfo authInfo = getAuthenticationInfo(); if (authInfo == null) { throw new IllegalArgumentException("Authentication Credentials cannot be null for FTP protocol"); }//from w w w. j a va2s. co m if (authInfo.getUserName() == null) { authInfo.setUserName(System.getProperty("user.name")); } String username = authInfo.getUserName(); String password = authInfo.getPassword(); if (username == null) { throw new AuthenticationException("Username not specified for repository " + getRepository().getId()); } if (password == null) { throw new AuthenticationException("Password not specified for repository " + getRepository().getId()); } String host = getRepository().getHost(); ftp = new FTPClient(); ftp.setDefaultTimeout(getTimeout()); ftp.setDataTimeout(getTimeout()); ftp.setControlEncoding(getControlEncoding()); ftp.addProtocolCommandListener(new PrintCommandListener(this)); try { if (getRepository().getPort() != WagonConstants.UNKNOWN_PORT) { ftp.connect(host, getRepository().getPort()); } else { ftp.connect(host); } // After connection attempt, you should check the reply code to // verify // success. int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new AuthenticationException("FTP server refused connection."); } } catch (IOException e) { if (ftp.isConnected()) { try { fireSessionError(e); ftp.disconnect(); } catch (IOException f) { // do nothing } } throw new AuthenticationException("Could not connect to server.", e); } try { if (!ftp.login(username, password)) { throw new AuthenticationException("Cannot login to remote system"); } fireSessionDebug("Remote system is " + ftp.getSystemName()); // Set to binary mode. ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.setListHiddenFiles(true); // Use passive mode as default because most of us are // behind firewalls these days. if (isPassiveMode()) { ftp.enterLocalPassiveMode(); } } catch (IOException e) { throw new ConnectionException("Cannot login to remote system", e); } }
From source file:org.apache.maven.wagon.providers.ftp.FtpWagonInclRmdir.java
protected void openConnectionInternal() throws ConnectionException, AuthenticationException { logger.info("Open ftp connection ..."); this.remoteRemovedDirectories = new LinkedList<String>(); AuthenticationInfo authInfo = getAuthenticationInfo(); if (authInfo == null) { throw new IllegalArgumentException("Authentication Credentials cannot be null for FTP protocol"); }/*from w w w. j av a 2 s . co m*/ if (authInfo.getUserName() == null) { authInfo.setUserName(System.getProperty("user.name")); } String username = authInfo.getUserName(); String password = authInfo.getPassword(); if (username == null) { throw new AuthenticationException("Username not specified for repository " + getRepository().getId()); } if (password == null) { throw new AuthenticationException("Password not specified for repository " + getRepository().getId()); } String host = getRepository().getHost(); ftp = new FTPClient(); ftp.setDefaultTimeout(getTimeout()); ftp.setDataTimeout(getTimeout()); ftp.setControlEncoding(getControlEncoding()); ftp.addProtocolCommandListener(new PrintCommandListener(this)); try { if (getRepository().getPort() != WagonConstants.UNKNOWN_PORT) { ftp.connect(host, getRepository().getPort()); } else { ftp.connect(host); } // After connection attempt, you should check the reply code to // verify // success. int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new AuthenticationException("FTP server refused connection."); } } catch (IOException e) { if (ftp.isConnected()) { try { fireSessionError(e); ftp.disconnect(); } catch (IOException f) { // do nothing } } throw new AuthenticationException("Could not connect to server.", e); } try { if (!ftp.login(username, password)) { throw new AuthenticationException("Cannot login to remote system"); } fireSessionDebug("Remote system is " + ftp.getSystemName()); // Set to binary mode. ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.setListHiddenFiles(true); // Use passive mode as default because most of us are // behind firewalls these days. if (isPassiveMode()) { ftp.enterLocalPassiveMode(); } } catch (IOException e) { throw new ConnectionException("Cannot login to remote system", e); } }
From source file:org.apache.nutch.protocol.ftp.Client.java
/*** * Login to the FTP server using the provided username and password. * <p>/* w w w . ja v a 2s . c o m*/ * * @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)); }
From source file:org.apache.nutch.protocol.ftp.Client.java
/** * reply check after closing data connection * // w ww .java2 s .c o m * @param reply * @return */ 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; }
From source file:org.apache.nutch.protocol.ftp.Client.java
/*** * 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./* ww w. jav a 2 s .co m*/ * <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; }
From source file:org.apache.nutch.protocol.ftp.Client.java
/*** * 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>/* w ww . j ava2 s.c o m*/ * * @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; }
From source file:org.apache.nutch.protocol.ftp.FtpResponse.java
public FtpResponse(URL url, CrawlDatum datum, Ftp ftp, Configuration conf) throws FtpException, IOException { this.orig = url.toString(); this.base = url.toString(); this.ftp = ftp; this.conf = conf; if (!"ftp".equals(url.getProtocol())) throw new FtpException("Not a ftp url:" + url); if (url.getPath() != url.getFile()) { if (Ftp.LOG.isWarnEnabled()) { Ftp.LOG.warn("url.getPath() != url.getFile(): " + url); }/* www.j a va2 s .c o m*/ } String path = "".equals(url.getPath()) ? "/" : url.getPath(); try { if (ftp.followTalk) { if (Ftp.LOG.isInfoEnabled()) { Ftp.LOG.info("fetching " + url); } } else { if (Ftp.LOG.isTraceEnabled()) { Ftp.LOG.trace("fetching " + url); } } InetAddress addr = InetAddress.getByName(url.getHost()); if (addr != null && conf.getBoolean("store.ip.address", false) == true) { headers.add("_ip_", addr.getHostAddress()); } // idled too long, remote server or ourselves may have timed out, // should start anew. if (ftp.client != null && ftp.keepConnection && ftp.renewalTime < System.currentTimeMillis()) { if (Ftp.LOG.isInfoEnabled()) { Ftp.LOG.info("delete client because idled too long"); } ftp.client = null; } // start anew if needed if (ftp.client == null) { if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) { Ftp.LOG.info("start client"); } // the real client ftp.client = new Client(); // when to renew, take the lesser // ftp.renewalTime = System.currentTimeMillis() // + ((ftp.timeout<ftp.serverTimeout) ? ftp.timeout : // ftp.serverTimeout); // timeout for control connection ftp.client.setDefaultTimeout(ftp.timeout); // timeout for data connection ftp.client.setDataTimeout(ftp.timeout); // follow ftp talk? if (ftp.followTalk) ftp.client.addProtocolCommandListener(new PrintCommandListener(Ftp.LOG)); } // quit from previous site if at a different site now if (ftp.client.isConnected()) { InetAddress remoteAddress = ftp.client.getRemoteAddress(); if (!addr.equals(remoteAddress)) { if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) { Ftp.LOG.info("disconnect from " + remoteAddress + " before connect to " + addr); } // quit from current site ftp.client.logout(); ftp.client.disconnect(); } } // connect to current site if needed if (!ftp.client.isConnected()) { if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) { Ftp.LOG.info("connect to " + addr); } ftp.client.connect(addr); if (!FTPReply.isPositiveCompletion(ftp.client.getReplyCode())) { ftp.client.disconnect(); if (Ftp.LOG.isWarnEnabled()) { Ftp.LOG.warn("ftp.client.connect() failed: " + addr + " " + ftp.client.getReplyString()); } this.code = 500; // http Internal Server Error return; } if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) { Ftp.LOG.info("log into " + addr); } if (!ftp.client.login(ftp.userName, ftp.passWord)) { // login failed. // please note that some server may return 421 immediately // after USER anonymous, thus ftp.client.login() won't return false, // but throw exception, which then will be handled by caller // (not dealt with here at all) . ftp.client.disconnect(); if (Ftp.LOG.isWarnEnabled()) { Ftp.LOG.warn("ftp.client.login() failed: " + addr); } this.code = 401; // http Unauthorized return; } // insist on binary file type if (!ftp.client.setFileType(FTP.BINARY_FILE_TYPE)) { ftp.client.logout(); ftp.client.disconnect(); if (Ftp.LOG.isWarnEnabled()) { Ftp.LOG.warn("ftp.client.setFileType() failed: " + addr); } this.code = 500; // http Internal Server Error return; } if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) { Ftp.LOG.info("set parser for " + addr); } // SYST is valid only after login try { ftp.parser = null; String parserKey = ftp.client.getSystemName(); // some server reports as UNKNOWN Type: L8, but in fact UNIX Type: L8 if (parserKey.startsWith("UNKNOWN Type: L8")) parserKey = "UNIX Type: L8"; ftp.parser = (new DefaultFTPFileEntryParserFactory()).createFileEntryParser(parserKey); } catch (FtpExceptionBadSystResponse e) { if (Ftp.LOG.isWarnEnabled()) { Ftp.LOG.warn("ftp.client.getSystemName() failed: " + addr + " " + e); } ftp.parser = null; } catch (ParserInitializationException e) { // ParserInitializationException is RuntimeException defined in // org.apache.commons.net.ftp.parser.ParserInitializationException if (Ftp.LOG.isWarnEnabled()) { Ftp.LOG.warn("createFileEntryParser() failed. " + addr + " " + e); } ftp.parser = null; } finally { if (ftp.parser == null) { // do not log as severe, otherwise // FetcherThread/RequestScheduler will abort if (Ftp.LOG.isWarnEnabled()) { Ftp.LOG.warn("ftp.parser is null: " + addr); } ftp.client.logout(); ftp.client.disconnect(); this.code = 500; // http Internal Server Error return; } } } else { if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) { Ftp.LOG.info("use existing connection"); } } this.content = null; path = java.net.URLDecoder.decode(path, "UTF-8"); if (path.endsWith("/")) { getDirAsHttpResponse(path, datum.getModifiedTime()); } else { getFileAsHttpResponse(path, datum.getModifiedTime()); } // reset next renewalTime, take the lesser if (ftp.client != null && ftp.keepConnection) { ftp.renewalTime = System.currentTimeMillis() + ((ftp.timeout < ftp.serverTimeout) ? ftp.timeout : ftp.serverTimeout); if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) { Ftp.LOG.info("reset renewalTime to " + HttpDateFormat.toString(ftp.renewalTime)); } } // getDirAsHttpResponse() or getFileAsHttpResponse() above // may have deleted ftp.client if (ftp.client != null && !ftp.keepConnection) { if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) { Ftp.LOG.info("disconnect from " + addr); } ftp.client.logout(); ftp.client.disconnect(); } } catch (Exception e) { if (Ftp.LOG.isWarnEnabled()) { Ftp.LOG.warn("Error: ", e); } // for any un-foreseen exception (run time exception or not), // do ultimate clean and leave ftp.client for garbage collection if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) { Ftp.LOG.info("delete client due to exception"); } ftp.client = null; // or do explicit garbage collection? // System.gc(); // can we be less dramatic, using the following instead? // probably unnecessary for our practical purpose here // try { // ftp.client.logout(); // ftp.client.disconnect(); // } throw new FtpException(e); // throw e; } }