org.apache.commons.net.ftp.FTPConnectionClosedException Java Examples

The following examples show how to use org.apache.commons.net.ftp.FTPConnectionClosedException. 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: FTPClientFactory.java    From springboot-ureport with Apache License 2.0 5 votes vote down vote up
/**
	 * 创建一个FTPClient对象
	 */
	@Override
	public FTPClient makeObject() throws Exception {
		FTPClient ftpClient = new FTPClient();
//		ftpClient.setConnectTimeout(clientTimeout);
		ftpClient.connect(properties.getHostname(), properties.getPort());
		int replyCode = ftpClient.getReplyCode();
		if(!FTPReply.isPositiveCompletion(replyCode)){
			ftpClient.disconnect();
			log.warn("FTPServer 拒绝连接 !");
			return null;
		}
		boolean login = ftpClient.login(properties.getUsername(), properties.getPassword());
		if(!login){
			throw new FTPConnectionClosedException("FTPServer 登录失败!");
		}
//		ftpClient.setControlEncoding("UTF-8");
		FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
		conf.setServerLanguageCode("zh");
		ftpClient.configure(conf);
		//ftpClient.setFileType(fileType);
//		ftpClient.setBufferSize(1024);
//		ftpClient.setControlEncoding(encoding);
//		if (passiveMode) {
//           ftpClient.enterLocalPassiveMode();
//        }

		return ftpClient;
	}
 
Example #2
Source File: FTPExceptionMappingService.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@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);
}
 
Example #3
Source File: Client.java    From anthelion with Apache License 2.0 4 votes vote down vote up
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());
  }

}
 
Example #4
Source File: Client.java    From anthelion with Apache License 2.0 4 votes vote down vote up
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());
  }

}
 
Example #5
Source File: Client.java    From nutch-htmlunit with Apache License 2.0 4 votes vote down vote up
/**
     * 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());
      }

    }
 
Example #6
Source File: Client.java    From nutch-htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * 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());
  }

}
 
Example #7
Source File: FTPsClient.java    From iaf with Apache License 2.0 4 votes vote down vote up
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]);
}