/***************************************** * * A convenience method for connecting and logging in. */ public void connectAndLogin( String host, String username, String password ) throws IOException, UnknownHostException, FTPConnectionClosedException { this.host = host; this.userName = username; log.debug("attempting to connect to " + host ); connect( host ); if ( FTPReply.isPositiveCompletion( getReplyCode() ) ) { log.debug("connect successful, logging in as " + userName ); login( userName, password ); } else { log.warn("failed to connect to " + host + ", disconnecting..."); disconnect(); return; } log.info("connected to " + host + " as user " + userName ); }
/************************************************ * */ public FTPFile statFile( String server_file ) throws IOException, FTPConnectionClosedException { FTPFile[] filelist = this.listFiles( server_file ); FTPFile filestat; if ( filelist == null || filelist.length < 1 ) { if (log.isDebugEnabled()) log.debug( "File '" + server_file + "' not found on server"); return null; } else if ( filelist.length > 1 ) { throw new RuntimeException( "Multiple files returned for stat('" + server_file + "') -- expected a single result" ); } else filestat = filelist[0]; return filestat; }
/********************************************** * * Convenience method to upload the output of an inputstream to a named server file. */ public void uploadFile( InputStream instream, String server_file ) throws IOException, FTPConnectionClosedException { log.debug("attempting to upload to " + host + ": " + server_file ); assert server_file != null && server_file.length() > 0; assert instream != null; try { if (! storeFile( server_file, instream )) throw new IOException("store returned false"); } finally { log.info("upload of " + server_file + " to host " + host + " failed" ); } }
private void readReply(Socket socket) throws IOException { // Read response BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), client.getControlEncoding())); String line = in.readLine(); StringBuffer sb = new StringBuffer(line); int length = line.length(); if (length > 3 && line.charAt(3) == '-') { do { line = in.readLine(); sb.append(" / ").append(line); if (line == null) { throw new FTPConnectionClosedException("Connection closed without indication."); } } while (! ( line.length() >= 4 && line.charAt(3) != '-' && Character.isDigit(line.charAt(0)) )); } Logger.defaultLogger().info("Received FTP server response : " + sb.toString()); }
public InputStream retrieveFileStream(String filename) throws FTPConnectionClosedException{ InputStream in=null; String possiableName="catalog.xml"; try { String[] names=ftpc.listNames(); for(String name:names){ if(filename.equals(name)){ possiableName=filename; break; } } } catch (IOException e1) { LOG.warn(StackTraceUtil.getStackTrace(e1)); } try { in=ftpc.retrieveFileStream(possiableName); } catch (FTPConnectionClosedException e){ throw e; }catch (IOException e2){ LOG.warn(StackTraceUtil.getStackTrace(e2)); } return in; }
@Override public BackgroundException map(final IOException e) { final StringBuilder buffer = new StringBuilder(); this.append(buffer, e.getMessage()); if(e instanceof FTPConnectionClosedException) { return new ConnectionRefusedException(buffer.toString(), e); } if(e instanceof FTPException) { return this.handle((FTPException) e, buffer); } if(e instanceof MalformedServerReplyException) { return new InteroperabilityException(buffer.toString(), e); } return new DefaultIOExceptionMappingService().map(e); }
private void __send(String message) throws IOException, FTPConnectionClosedException, SocketException { try { this._controlOutput_.write(message); this._controlOutput_.flush(); } catch (SocketException var3) { if(!this.isConnected()) { throw new FTPConnectionClosedException("Connection unexpectedly closed."); } else { throw var3; } } }
/******************************************** * * Convenience method to stream a file from the server to the * given output stream. */ public void downloadFile( String server_file, OutputStream out_stream ) throws IOException, FTPConnectionClosedException { log.debug("attempting to download '" + server_file + "'" ); try { if (! retrieveFile( server_file, out_stream )) throw new IOException("retrieve returned false"); log.info("successfully downloaded '" + server_file + "'" ); } finally { log.info("download of '" + server_file + "' failed" ); } }
/******************************************** * * Convenience method to download a file from the server and save * it to the specified local file. */ public void downloadFile( String server_file, String local_file ) throws IOException, FTPConnectionClosedException { FileOutputStream outstream = new FileOutputStream( local_file ); try { downloadFile( server_file, outstream ); } finally { outstream.close(); } }
/********************************************** * * Convenience method to upload a local file to the server. */ public void uploadFile( String localFile, String serverFile ) throws IOException, FTPConnectionClosedException { log.debug("attempting to upload local file '" + localFile + "'" ); FileInputStream in = new FileInputStream( localFile ); try { uploadFile( in, serverFile ); } finally { in.close(); } }
private void checkConnect(FTPClient ftp, String server, String login, String password) throws IOException { try { if (ftp.isConnected()) if (ftp.sendNoOp()) return; } catch (FTPConnectionClosedException e) { Logging.warn(e); } ftp.setConnectTimeout(120000); ftp.setControlKeepAliveTimeout(180); ftp.setDataTimeout(120000); ftp.connect(server); ftp.login(login, password); }
public void testConnect() throws Exception { try { client.connect("localhost", getListenerPort()); fail("Must throw"); } catch (FTPConnectionClosedException e) { // OK } }
/** * This tests that the correct IP is returned, that is the IP that the * client has connected to. * * Note that this test will only work if you got more than one NIC and the * server is allowed to listen an all NICs */ public void testPasvIp() throws Exception { String[] ips = TestUtil.getHostAddresses(); for (int i = 0; i < ips.length; i++) { String ip = ips[i]; String ftpIp = ip.replace('.', ','); if (!ip.startsWith("0.")) { try { client.connect(ip, getListenerPort()); } catch (FTPConnectionClosedException e) { // try again Thread.sleep(200); client.connect(ip, getListenerPort()); } client.login(ADMIN_USERNAME, ADMIN_PASSWORD); client.pasv(); assertTrue("Can't find " + ftpIp + " in " + client.getReplyString(), client.getReplyString().indexOf(ftpIp) > -1); client.quit(); client.disconnect(); } } }
public void testLoginWithMaxConnections() throws Exception { FTPClient client1 = new FTPClient(); FTPClient client2 = new FTPClient(); FTPClient client3 = new FTPClient(); FTPClient client4 = new FTPClient(); try { client1.connect("localhost", getListenerPort()); client2.connect("localhost", getListenerPort()); client3.connect("localhost", getListenerPort()); client4.connect("localhost", getListenerPort()); assertTrue(client1.login(TESTUSER1_USERNAME, TESTUSER_PASSWORD)); assertTrue(client2.login(TESTUSER1_USERNAME, TESTUSER_PASSWORD)); assertTrue(client3.login(TESTUSER1_USERNAME, TESTUSER_PASSWORD)); try { assertTrue(client4.login(TESTUSER1_USERNAME, TESTUSER_PASSWORD)); assertEquals(421, client.getReplyCode()); fail("Must throw FTPConnectionClosedException"); } catch (FTPConnectionClosedException e) { // expected } } finally { closeQuitely(client1); closeQuitely(client2); closeQuitely(client3); closeQuitely(client4); } }
public void testDenyBlackList() throws Exception { filter.clear(); filter.setType(IpFilterType.DENY); filter.add(new Subnet(InetAddress.getByName("localhost"), 32)); try { client.connect("localhost", getListenerPort()); fail("Must throw"); } catch (FTPConnectionClosedException e) { // OK } }
public void testDenyEmptyWhiteList() throws Exception { filter.clear(); filter.setType(IpFilterType.ALLOW); try { client.connect("localhost", getListenerPort()); fail("Must throw"); } catch (FTPConnectionClosedException e) { // OK } }
protected void doConnect() throws Exception { try { client.connect("localhost", getListenerPort()); } catch (FTPConnectionClosedException e) { // try again Thread.sleep(200); client.connect("localhost", getListenerPort()); } }
/** * retrieve list reply for path * * @param path * @param entries * @param limit * @param parser * @throws IOException * @throws FtpExceptionCanNotHaveDataConnection * @throws FtpExceptionUnknownForcedDataClose * @throws FtpExceptionControlClosedByForcedDataClose */ public void retrieveList(String path, List<FTPFile> entries, int limit, FTPFileEntryParser parser) throws IOException, FtpExceptionCanNotHaveDataConnection, FtpExceptionUnknownForcedDataClose, FtpExceptionControlClosedByForcedDataClose { Socket socket = __openPassiveDataConnection(FTPCommand.LIST, path); if (socket == null) throw new FtpExceptionCanNotHaveDataConnection("LIST " + ((path == null) ? "" : path)); BufferedReader reader = new BufferedReader(new InputStreamReader( socket.getInputStream())); // force-close data channel socket, when download limit is reached // boolean mandatory_close = false; // List entries = new LinkedList(); int count = 0; String line = parser.readNextEntry(reader); while (line != null) { FTPFile ftpFile = parser.parseFTPEntry(line); // skip non-formatted lines if (ftpFile == null) { line = parser.readNextEntry(reader); continue; } entries.add(ftpFile); count += line.length(); // impose download limit if limit >= 0, otherwise no limit // here, cut off is up to the line when total bytes is just over limit if (limit >= 0 && count > limit) { // mandatory_close = true; break; } line = parser.readNextEntry(reader); } // if (mandatory_close) // you always close here, no matter mandatory_close or not. // however different ftp servers respond differently, see below. socket.close(); // scenarios: // (1) mandatory_close is false, download limit not reached // no special care here // (2) mandatory_close is true, download limit is reached // different servers have different reply codes: try { int reply = getReply(); if (!_notBadReply(reply)) throw new FtpExceptionUnknownForcedDataClose(getReplyString()); } catch (FTPConnectionClosedException e) { // some ftp servers will close control channel if data channel socket // is closed by our end before all data has been read out. Check: // tux414.q-tam.hp.com FTP server (hp.com version whp02) // so must catch FTPConnectionClosedException thrown by getReply() above // disconnect(); throw new FtpExceptionControlClosedByForcedDataClose(e.getMessage()); } }
/** * retrieve file for path * * @param path * @param os * @param limit * @throws IOException * @throws FtpExceptionCanNotHaveDataConnection * @throws FtpExceptionUnknownForcedDataClose * @throws FtpExceptionControlClosedByForcedDataClose */ public void retrieveFile(String path, OutputStream os, int limit) throws IOException, FtpExceptionCanNotHaveDataConnection, FtpExceptionUnknownForcedDataClose, FtpExceptionControlClosedByForcedDataClose { Socket socket = __openPassiveDataConnection(FTPCommand.RETR, path); if (socket == null) throw new FtpExceptionCanNotHaveDataConnection("RETR " + ((path == null) ? "" : path)); InputStream input = socket.getInputStream(); // 20040318, xing, treat everything as BINARY_FILE_TYPE for now // do we ever need ASCII_FILE_TYPE? // if (__fileType == ASCII_FILE_TYPE) // input = new FromNetASCIIInputStream(input); // fixme, should we instruct server here for binary file type? // force-close data channel socket // boolean mandatory_close = false; int len; int count = 0; byte[] buf = new byte[org.apache.commons.net.io.Util.DEFAULT_COPY_BUFFER_SIZE]; while ((len = input.read(buf, 0, buf.length)) != -1) { count += len; // impose download limit if limit >= 0, otherwise no limit // here, cut off is exactly of limit bytes if (limit >= 0 && count > limit) { os.write(buf, 0, len - (count - limit)); // mandatory_close = true; break; } os.write(buf, 0, len); os.flush(); } // if (mandatory_close) // you always close here, no matter mandatory_close or not. // however different ftp servers respond differently, see below. socket.close(); // scenarios: // (1) mandatory_close is false, download limit not reached // no special care here // (2) mandatory_close is true, download limit is reached // different servers have different reply codes: // do not need this // sendCommand("ABOR"); try { int reply = getReply(); if (!_notBadReply(reply)) throw new FtpExceptionUnknownForcedDataClose(getReplyString()); } catch (FTPConnectionClosedException e) { // some ftp servers will close control channel if data channel socket // is closed by our end before all data has been read out. Check: // tux414.q-tam.hp.com FTP server (hp.com version whp02) // so must catch FTPConnectionClosedException thrown by getReply() above // disconnect(); throw new FtpExceptionControlClosedByForcedDataClose(e.getMessage()); } }
private void __getReply(boolean reportReply) throws IOException { this._newReplyString = true; this._replyLines.clear(); String line = this._controlInput_.readLine(); if(line == null) { throw new FTPConnectionClosedException("Connection closed without indication."); } else { int length = line.length(); if(length < 3) { throw new MalformedServerReplyException("Truncated server reply: " + line); } else { String code = null; try { code = line.substring(0, 3); this._replyCode = Integer.parseInt(code); } catch (NumberFormatException var6) { throw new MalformedServerReplyException("Could not parse response code.\nServer Reply: " + line); } this._replyLines.add(line); if(length > 3 && line.charAt(3) == 45) { while(true) { line = this._controlInput_.readLine(); if(line == null) { throw new FTPConnectionClosedException("Connection closed without indication."); } this._replyLines.add(line); if(this.isStrictMultilineParsing()) { if(!this.__strictCheck(line, code)) { break; } } else if(!this.__lenientCheck(line)) { break; } } } this.fireReplyReceived(this._replyCode, this.getReplyString()); if(this._replyCode == 421) { throw new FTPConnectionClosedException("FTP response 421 received. Server closed connection."); } } } }
public void retrieveList(String path, List entries, int limit, FTPFileEntryParser parser) throws IOException, FtpExceptionCanNotHaveDataConnection, FtpExceptionUnknownForcedDataClose, FtpExceptionControlClosedByForcedDataClose { Socket socket = __openPassiveDataConnection(FTPCommand.LIST, path); if (socket == null) throw new FtpExceptionCanNotHaveDataConnection("LIST " + ((path == null) ? "" : path)); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // force-close data channel socket, when download limit is reached boolean mandatory_close = false; //List entries = new LinkedList(); int count = 0; String line = parser.readNextEntry(reader); while (line != null) { FTPFile ftpFile = parser.parseFTPEntry(line); // skip non-formatted lines if (ftpFile == null) { line = parser.readNextEntry(reader); continue; } entries.add(ftpFile); count += line.length(); // impose download limit if limit >= 0, otherwise no limit // here, cut off is up to the line when total bytes is just over limit if (limit >= 0 && count > limit) { mandatory_close = true; break; } line = parser.readNextEntry(reader); } //if (mandatory_close) // you always close here, no matter mandatory_close or not. // however different ftp servers respond differently, see below. socket.close(); // scenarios: // (1) mandatory_close is false, download limit not reached // no special care here // (2) mandatory_close is true, download limit is reached // different servers have different reply codes: try { int reply = getReply(); if (!_notBadReply(reply)) throw new FtpExceptionUnknownForcedDataClose(getReplyString()); } catch (FTPConnectionClosedException e) { // some ftp servers will close control channel if data channel socket // is closed by our end before all data has been read out. Check: // tux414.q-tam.hp.com FTP server (hp.com version whp02) // so must catch FTPConnectionClosedException thrown by getReply() above //disconnect(); throw new FtpExceptionControlClosedByForcedDataClose(e.getMessage()); } }
public void retrieveFile(String path, OutputStream os, int limit) throws IOException, FtpExceptionCanNotHaveDataConnection, FtpExceptionUnknownForcedDataClose, FtpExceptionControlClosedByForcedDataClose { Socket socket = __openPassiveDataConnection(FTPCommand.RETR, path); if (socket == null) throw new FtpExceptionCanNotHaveDataConnection("RETR " + ((path == null) ? "" : path)); InputStream input = socket.getInputStream(); // 20040318, xing, treat everything as BINARY_FILE_TYPE for now // do we ever need ASCII_FILE_TYPE? //if (__fileType == ASCII_FILE_TYPE) // input = new FromNetASCIIInputStream(input); // fixme, should we instruct server here for binary file type? // force-close data channel socket boolean mandatory_close = false; int len; int count = 0; byte[] buf = new byte[org.apache.commons.net.io.Util.DEFAULT_COPY_BUFFER_SIZE]; while((len=input.read(buf,0,buf.length)) != -1){ count += len; // impose download limit if limit >= 0, otherwise no limit // here, cut off is exactly of limit bytes if (limit >= 0 && count > limit) { os.write(buf,0,len-(count-limit)); mandatory_close = true; break; } os.write(buf,0,len); os.flush(); } //if (mandatory_close) // you always close here, no matter mandatory_close or not. // however different ftp servers respond differently, see below. socket.close(); // scenarios: // (1) mandatory_close is false, download limit not reached // no special care here // (2) mandatory_close is true, download limit is reached // different servers have different reply codes: // do not need this //sendCommand("ABOR"); try { int reply = getReply(); if (!_notBadReply(reply)) throw new FtpExceptionUnknownForcedDataClose(getReplyString()); } catch (FTPConnectionClosedException e) { // some ftp servers will close control channel if data channel socket // is closed by our end before all data has been read out. Check: // tux414.q-tam.hp.com FTP server (hp.com version whp02) // so must catch FTPConnectionClosedException thrown by getReply() above //disconnect(); throw new FtpExceptionControlClosedByForcedDataClose(e.getMessage()); } }
private Object _readReply(InputStream in, boolean concatenateLines) throws IOException { // obtain the result BufferedReader reader = new BufferedReader(new InputStreamReader(in, "ISO-8859-1")); 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]); }