Esempio n. 1
2
  @Override
  public void afterPropertiesSet() throws Exception {
    if (ftpClient == null) {
      ftpClient = new FTPClient();
    }

    ftpClient.configure(config);

    ftpClient.addProtocolCommandListener(
        new ProtocolCommandListener() {
          @Override
          public void protocolCommandSent(ProtocolCommandEvent event) {
            log.info("Send FTP command: " + event.getCommand());
          }

          @Override
          public void protocolReplyReceived(ProtocolCommandEvent event) {
            log.info("Received FTP command reply: " + event.getReplyCode());
          }
        });
  }
  /**
   * configures the supplied FTPClient with the various attributes set in the supplied FTP task.
   *
   * @param client the FTPClient to be configured
   * @param task the FTP task whose attributes are used to configure the client
   * @return the client as configured.
   */
  static FTPClient configure(FTPClient client, FTPTaskConfig task) {
    task.log("custom configuration", Project.MSG_VERBOSE);
    FTPClientConfig config;
    String systemTypeKey = task.getSystemTypeKey();
    if (systemTypeKey != null && !"".equals(systemTypeKey)) {
      config = new FTPClientConfig(systemTypeKey);
      task.log("custom config: system key = " + systemTypeKey, Project.MSG_VERBOSE);
    } else {
      config = new FTPClientConfig();
      task.log("custom config: system key = default (UNIX)", Project.MSG_VERBOSE);
    }

    String defaultDateFormatConfig = task.getDefaultDateFormatConfig();
    if (defaultDateFormatConfig != null) {
      config.setDefaultDateFormatStr(defaultDateFormatConfig);
      task.log(
          "custom config: default date format = " + defaultDateFormatConfig, Project.MSG_VERBOSE);
    }

    String recentDateFormatConfig = task.getRecentDateFormatConfig();
    if (recentDateFormatConfig != null) {
      config.setRecentDateFormatStr(recentDateFormatConfig);
      task.log(
          "custom config: recent date format = " + recentDateFormatConfig, Project.MSG_VERBOSE);
    }

    String serverLanguageCodeConfig = task.getServerLanguageCodeConfig();
    if (serverLanguageCodeConfig != null) {
      if (!"".equals(serverLanguageCodeConfig)
          && !FTPClientConfig.getSupportedLanguageCodes().contains(serverLanguageCodeConfig)) {
        throw new BuildException("unsupported language code" + serverLanguageCodeConfig);
      }
      config.setServerLanguageCode(serverLanguageCodeConfig);
      task.log(
          "custom config: server language code = " + serverLanguageCodeConfig, Project.MSG_VERBOSE);
    }

    String serverTimeZoneConfig = task.getServerTimeZoneConfig();
    if (serverTimeZoneConfig != null) {
      config.setServerTimeZoneId(serverTimeZoneConfig);
      task.log("custom config: server time zone ID = " + serverTimeZoneConfig, Project.MSG_VERBOSE);
    }

    String shortMonthNamesConfig = task.getShortMonthNamesConfig();
    if (shortMonthNamesConfig != null) {
      config.setShortMonthNames(shortMonthNamesConfig);
      task.log("custom config: short month names = " + shortMonthNamesConfig, Project.MSG_VERBOSE);
    }
    client.configure(config);
    return client;
  }
Esempio n. 3
1
 private void connectFtpServer() {
   try {
     ftpClient = new FTPClient();
     FTPClientConfig ftpClientConfig = new FTPClientConfig();
     ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
     ftpClient.configure(ftpClientConfig);
     URL url = getURL();
     if (url.getPort() <= 0) {
       ftpClient.connect(url.getHost());
     } else {
       ftpClient.connect(url.getHost(), url.getPort());
     }
     if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
       throw new VFSRuntimeException("连接失败!");
     }
     if (url.getUserInfo() != null) {
       String userInfo[] = url.getUserInfo().split(":");
       String userName = null;
       String password = null;
       if (userInfo.length >= 1) {
         userName = userInfo[0];
       }
       if (userInfo.length >= 2) {
         password = userInfo[1];
       }
       if (!ftpClient.login(userName, password)) {
         throw new VFSRuntimeException("登录失败:" + url.toString());
       }
       if (!ftpClient.setFileType(FTP.BINARY_FILE_TYPE)) {
         throw new VFSRuntimeException("设置二进制类型失败");
       }
       ftpClient.setBufferSize(BUF_SIZE);
       ftpClient.setControlEncoding("utf-8");
     }
   } catch (Exception e) {
     throw new VFSRuntimeException(e);
   }
 }
  public void run() {
    try {
      FTPClient c = new FTPClient();
      c.configure(ftpConfig);

      logger.debug("Trying to connect");
      c.connect("127.0.0.1", 21211);
      logger.debug("Connected");

      c.setSoTimeout(5000);

      if (!FTPReply.isPositiveCompletion(c.getReplyCode())) {
        logger.debug("Houston, we have a problem. D/C");
        c.disconnect();
        throw new Exception();
      }

      if (c.login("drftpd", "drftpd")) {
        logger.debug("Logged-in, now waiting 5 secs and kill the thread.");
        _sc.addSuccess();
        Thread.sleep(5000);
        c.disconnect();
      } else {
        logger.debug("Login failed, D/C!");
        throw new Exception();
      }
    } catch (Exception e) {
      logger.debug(e, e);
      _sc.addFailure();
    }

    logger.debug("exiting");
  }
Esempio n. 5
0
  /**
   * 서버와 연결에 필요한 값들을 가져와 초기화 시킴
   *
   * @param host 서버 주소
   * @param userName 접속에 사용될 아이디
   * @param password 비밀번호
   * @param port 포트번호
   */
  public void init(String host, String userName, String password, int port) {
    client = new FTPClient();
    client.setControlEncoding("UTF-8"); // 한글 encoding....

    FTPClientConfig config = new FTPClientConfig();
    client.configure(config);
    try {
      client.connect(host, port);
      client.login(userName, password);
    } catch (SocketException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Esempio n. 6
0
 public String ftpGet(
     String remoteAddr,
     int remotePort,
     String remotePath,
     String remoteFileName,
     String localPath,
     String username,
     String password)
     throws SocketException, IOException {
   FTPClient ftp = new FTPClient();
   FTPClientConfig config = new FTPClientConfig();
   ftp.configure(config);
   try {
     ftp.connect(remoteAddr, remotePort);
     log.debug("Connected to " + remoteAddr + ":" + remotePort + ".\n" + ftp.getReplyString());
     int reply = ftp.getReplyCode();
     if (!FTPReply.isPositiveCompletion(reply)) {
       ftp.disconnect();
       log.error("FTP server refused connection.");
       throw new RuntimeException("FTP server refused connection.");
     }
     ftp.login(username, password);
     reply = ftp.getReplyCode();
     if (!FTPReply.isPositiveCompletion(reply)) {
       ftp.disconnect();
       log.error("FTP server refused connection.");
       throw new RuntimeException("FTP server refused connection.");
     }
     if (!ftp.setFileType(FTP.BINARY_FILE_TYPE)) {
       log.error("set BINARY_FILE_TYPE error.");
       throw new RuntimeException("FTP server refused connection.");
     }
     // ftp.setFileTransferMode(FTPClient.STREAM_TRANSFER_MODE);
     ftp.enterLocalPassiveMode();
     String remote = remotePath + "/" + remoteFileName;
     String local = localPath + "/" + remoteFileName;
     String returnName = genFileName(local);
     File f = new File(returnName);
     FileOutputStream fos = FileUtils.openOutputStream(f);
     try {
       long startTime = System.currentTimeMillis();
       if (!ftp.retrieveFile(remote, fos)) {
         log.error("get " + remote + " error.");
         throw new RuntimeException("get " + remote + " error.");
       }
       log.debug("get remote file[" + remote + "], local file[" + local + "] .");
       long finishedTime = System.currentTimeMillis();
       log.debug("remote time :" + (finishedTime - startTime) / 1000f + " sec.");
     } finally {
       IOUtils.closeQuietly(fos);
     }
     ftp.logout();
     return returnName;
   } finally {
     if (ftp.isConnected()) {
       try {
         ftp.disconnect();
       } catch (IOException ioe) {
       }
     }
   }
 }
Esempio n. 7
0
  /** @param args */
  public static void main(String[] args) throws Exception {

    Properties prop = PropertiesLoader.loadProp("ftp.config.properties");
    String serverAddress = prop.getProperty("ftp.address");
    int serverPort = Integer.parseInt(prop.getProperty("ftp.port"));
    String userId = prop.getProperty("ftp.id");
    String userPassword = prop.getProperty("ftp.password");

    String localDir = prop.getProperty("ftp.localDir");
    String remoteDir = prop.getProperty("ftp.remoteDir");
    String logDir = prop.getProperty("ftp.logDir");

    FTPClient ftp = new FTPClient();
    FTPClientConfig config = new FTPClientConfig();
    ftp.configure(config);
    boolean error = false;
    try {
      int reply;
      ftp.connect(serverAddress, serverPort);

      System.out.println("Connected to " + prop.getProperty("ftp.address") + ".");

      reply = ftp.getReplyCode();
      System.out.print(ftp.getReplyString());

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

      if (!ftp.login(userId, userPassword)) {
        ftp.logout();
        throw new Exception("FTP 서버에 로그인하지 못했습니다.");
      }

      ftp.changeWorkingDirectory(remoteDir);

      FTPFile[] files = ftp.listFiles();
      System.out.println("Number of files in dir: " + files.length);

      // Open log file
      String logFile = new SimpleDateFormat("yyyyMMddhhmm").format(new Date());

      FileWriter fw = new FileWriter(logDir + "/" + logFile + ".txt", true);

      for (int i = 0; i < files.length; i++) {

        if (files[i].isDirectory()) {

        } else {
          System.out.println(files[i].getName());
          File file = new File(localDir + File.separator + files[i].getName());
          FileOutputStream fos = new FileOutputStream(file);
          ftp.retrieveFile(files[i].getName(), fos);
          fos.close();
          // Format the date
          String theTime =
              DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)
                  .format(new Date());
          fw.write("FTP'd " + files[i].getName() + " at " + theTime + "\n");
        }
      }
      fw.close();
      System.out.println("done!");
      ftp.logout();
    } catch (IOException e) {
      error = true;
      e.printStackTrace();
    } finally {
      if (ftp.isConnected()) {
        try {
          ftp.disconnect();
        } catch (IOException ioe) {
          // do nothing
        }
      }
      // System.exit(error ? 1 : 0);
    }
  }