Exemple #1
11
  /**
   * Description: 从FTP服务器下载指定文件夹下的所有文件
   *
   * @param url FTP服务器hostname
   * @param port FTP服务器端口
   * @param username FTP登录账号
   * @param password FTP登录密码
   * @param remotePath FTP服务器上的相对路径
   * @param localPath 下载后保存到本地的路径
   * @param fileName 保存为该文件名的文件
   * @return
   */
  public static boolean downFile(
      String url,
      int port,
      String username,
      String password,
      String remotePath,
      String localPath,
      String fileName) {
    boolean success = false;
    FTPClient ftp = null;
    try {
      int reply;
      ftp = getConnection(url, port, username, password);
      reply = ftp.getReplyCode();
      if (!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        return success;
      }
      boolean changeWorkDirState = false;
      changeWorkDirState = ftp.changeWorkingDirectory(remotePath); // 转移到FTP服务器目录
      System.out.println(changeWorkDirState == true ? "切换FTP目录 成功" : "切换FTP目录 失败");
      if (changeWorkDirState == false) return false;
      FTPFile[] fs = ftp.listFiles();
      for (FTPFile ff : fs) {
        if (ff.getName().equals(fileName)) {
          File localFile = new File(localPath + "/" + ff.getName());

          OutputStream is = new FileOutputStream(localFile);
          ftp.retrieveFile(ff.getName(), is);
          is.close();
        }
      }

      ftp.logout();
      success = true;
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (ftp.isConnected()) {
        try {
          ftp.disconnect();
        } catch (IOException ioe) {
        }
      }
    }
    return success;
  }
Exemple #2
0
  public static String downloadFromFTP(String url, String jarPath) {
    String[] splits = url.split("/");
    String filename = splits[splits.length - 1];
    FTPClient client = new FTPClient();
    FileOutputStream fos = null;

    try {
      client.connect(host);
      client.login(username, passwd);

      //
      // The remote filename to be downloaded.
      //
      fos = new FileOutputStream(jarPath + "/" + filename);
      //
      // Download file from FTP server
      //
      client.retrieveFile(url, fos);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (fos != null) {
          fos.close();
        }
        client.disconnect();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return filename;
  }
  /**
   * Function retrieved file on the remote server NOTE: This function closes output stream after
   * retrieving file content
   *
   * @param fileName
   * @param fileOutput
   * @return
   * @throws SocketException
   * @throws IOException
   */
  public boolean retrieveFile(String fileName, OutputStream fileOutput)
      throws SocketException, IOException {
    boolean fileRetrieved = false;

    connect2Server();

    if (oFtp.isConnected()) {

      try {

        fileRetrieved = oFtp.retrieveFile(fileName, fileOutput);

        if (fileRetrieved) {
          logMessage("File '" + fileName + "' retrieved");
        } else {
          logError(
              "Can't retrieve file "
                  + fileName
                  + " FTP reply code: "
                  + oFtp.getReplyCode()
                  + " Ftp message: "
                  + oFtp.getReplyString());
        }
        fileOutput.close();
      } catch (IOException ioe) {
        log.warning("FTPUtil - retrieveFile(): " + ioe.toString());
        return false;
      }
    }
    this.closeFtpConnection();
    return fileRetrieved;
  }
Exemple #4
0
  private static void downloadFileViaFTP(FTPClient ftpClient) throws IOException {
    // TODO Auto-generated method stub
    // APPROACH #1: using retrieveFile(String, OutputStream)
    String remoteFile1 = "/export/home/fuse/ge.txt";
    File downloadFile1 = new File("D:/ftppppp.txt");
    OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
    boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
    outputStream1.close();

    if (success) {
      System.out.println("File #1 has been downloaded successfully.");
    } else {
      System.out.println("Download failed !!");
    }

    //        // APPROACH #2: using InputStream retrieveFileStream(String)
    //        String remoteFile2 = "/test/song.mp3";
    //        File downloadFile2 = new File("D:/Downloads/song.mp3");
    //        OutputStream outputStream2 = new BufferedOutputStream(new
    // FileOutputStream(downloadFile2));
    //        InputStream inputStream = ftpClient.retrieveFileStream(remoteFile2);
    //        byte[] bytesArray = new byte[4096];
    //        int bytesRead = -1;
    //        while ((bytesRead = inputStream.read(bytesArray)) != -1) {
    //            outputStream2.write(bytesArray, 0, bytesRead);
    //        }
    //
    //        success = ftpClient.completePendingCommand();
    //        if (success) {
    //            System.out.println("File #2 has been downloaded successfully.");
    //        }
    //        outputStream2.close();
    //        inputStream.close();
  }
  /**
   * Download a file from the server
   *
   * @param fileName
   * @param isTextFile
   * @return
   */
  public boolean getFile(String remoteFileName, String localFileName, boolean isTextFile)
      throws FtpException {

    byte[] data = new byte[BUFFER];
    int count;
    File tmpFile =
        new File(localFileName.substring(0, localFileName.lastIndexOf(File.separatorChar)));

    if (!tmpFile.exists()) {
      tmpFile.mkdirs();
    }

    try {
      if (isTextFile) {
        ftp.setFileType(FTPClient.ASCII_FILE_TYPE);
      } else {
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
      }

      boolean isValidWrt =
          ftp.retrieveFile(
              remoteFileName, new BufferedOutputStream(new FileOutputStream(localFileName)));
      if (!isValidWrt) {
        close();
        throw new FtpException("remote file or local file is not exist !");
      }
      InputStream ftpReader = ftp.retrieveFileStream(remoteFileName);
      if (ftpReader == null) {
        throw new FtpException("no file");
      }
      BufferedInputStream downloadFileIn = new BufferedInputStream(ftpReader, BUFFER);
      BufferedOutputStream downloadFileOut =
          new BufferedOutputStream(new FileOutputStream(localFileName), BUFFER);
      while ((count = downloadFileIn.read(data, 0, BUFFER)) != -1) {
        downloadFileOut.write(data, 0, count);
        downloadFileOut.flush();
      }
      ftpReader.close();
      downloadFileIn.close();
      downloadFileOut.close();
      if (!ftp.completePendingCommand()) {
        close();
        throw new FtpException("remote file or local file is not exist!");
      }

    } catch (Exception ex) {
      close();
      ex.printStackTrace();
      logger.info(
          "\\== ERROR WHILE EXECUTE FTP ==// (File Name:"
              + remoteFileName
              + " ==> "
              + localFileName
              + ") >>>>>>>>>>>>>"
              + ex.getLocalizedMessage());
      throw new FtpException("ftp file exception:" + ex.getMessage());
    }
    return true;
  }
Exemple #6
0
  public static boolean downloadFile(FTPClient ftp, OutputStream output, String filename)
      throws IOException {
    // FTP协议里面,规定文件名编码为iso-8859-1,所以目录名或文件名需要转码
    String isoFileName = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
    ftp.retrieveFile(isoFileName, output);

    if (!ftp.completePendingCommand()) {
      FTPLogger.error("File transfer failed, file name: " + filename);
      return false;
    }
    return true;
  }
  /**
   * @param remotePath 远程文件路径ַ ex:/upload/2012/xxxx.jpg
   * @param out 文件输出流
   * @return
   */
  public static boolean downFile(String remotePath, OutputStream out) {
    Boolean flag = Boolean.FALSE;
    // 得到文件名 ex: xxxx.jpg
    String fileName = getLastName(remotePath);
    // 得到文件存储路径 ex:/upload/2012
    String remoteStorePath = getFilePath(remotePath);
    FTPClient ftpClient = null;
    try {
      ftpClient = getFTPClient();
      // 得到返回答复码
      int reply = ftpClient.getReplyCode();

      if (!FTPReply.isPositiveCompletion(reply)) {
        try {
          ftpClient.disconnect();
          return flag;
        } catch (IOException e) {
          e.printStackTrace();
          return flag;
        }
      }

      ftpClient.changeWorkingDirectory(remoteStorePath);

      // ftpClient.setFileType(FTP.BINARY_FILE_TYPE);//

      FTPFile[] fs = ftpClient.listFiles();
      for (FTPFile file : fs) {
        if (fileName.equalsIgnoreCase(file.getName())) {
          flag = ftpClient.retrieveFile(fileName, out);

          break;
        }
      }
      ftpClient.logout();
    } catch (IOException e) {
      e.printStackTrace();

    } finally {
      if (null != ftpClient && ftpClient.isConnected()) {
        try {
          ftpClient.disconnect();
        } catch (IOException ioe) {
        }
      }
    }

    return flag;
  }
  /**
   *
   *
   * <pre>
   * <b>Description:</b>
   * Function connect to ftp and get attribute value from xml file by tag name
   * <b>Creation date: </b>02.07.2008
   * <b>Modification date: </b>02.07.2008
   * </pre>
   *
   * @param String sDirPath -- dirrectory where file located
   * @param String sFileName -- XML file name
   * @param String sTag -- searching tag in file
   * @param String sAttribute -- tag attribute
   * @author Oleksii Zozulenko.
   * @return String sAttrValue -- attribute value, or null if error
   * @exception Exception
   */
  public String getXMLAttributeValue(
      String sDirPath, String sFileName, String sTag, String sAttribute) throws Exception {
    try {
      String sAttrValue = null;

      FTPClient oFtp = this.initFtpClientLoginChangeWorkingDirectory(sDirPath);

      ByteArrayOutputStream oBuf = new ByteArrayOutputStream();

      if (!oFtp.retrieveFile(sFileName, oBuf)) {
        log.setError("Could not read file `" + sFileName + "`");
        oFtp.disconnect();
        return null;
      }

      oFtp.disconnect();

      String sBuf = oBuf.toString();

      oBuf.close();

      if (!sBuf.contains(sTag)) {
        log.setError("File `" + sFileName + "` not contains tag `" + sTag + "`");
        return null;
      }

      sBuf = sBuf.substring(sBuf.indexOf(sTag));

      if (!sBuf.contains(sAttribute)) {
        log.setError(
            "File `"
                + sFileName
                + "` not contains tag `"
                + sTag
                + "` with attribute `"
                + sAttribute
                + "`");
        return null;
      }
      sBuf = sBuf.substring(sBuf.indexOf(sAttribute + "=\"") + (sAttribute + "=\"").length());
      sAttrValue = sBuf.substring(0, sBuf.indexOf("\""));

      return sAttrValue;
    } catch (Exception oEx) {
      throw oEx;
    }
  }
  /**
   * Description: 从FTP服务器下载文件
   *
   * @param host FTP服务器hostname
   * @param port FTP服务器端口
   * @param username FTP登录账号
   * @param password FTP登录密码
   * @param remotePath FTP服务器上的相对路径
   * @param fileName 要下载的文件名
   * @param localPath 下载后保存到本地的路径
   * @return
   */
  public static boolean downloadFile(
      String host,
      int port,
      String username,
      String password,
      String remotePath,
      String fileName,
      String localPath) {
    boolean result = false;
    FTPClient ftp = new FTPClient();
    try {
      int reply;
      ftp.connect(host, port);
      // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
      ftp.login(username, password); // 登录
      reply = ftp.getReplyCode();
      if (!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        return result;
      }
      ftp.changeWorkingDirectory(remotePath); // 转移到FTP服务器目录
      FTPFile[] fs = ftp.listFiles();
      for (FTPFile ff : fs) {
        if (ff.getName().equals(fileName)) {
          File localFile = new File(localPath + "/" + ff.getName());

          OutputStream is = new FileOutputStream(localFile);
          ftp.retrieveFile(ff.getName(), is);
          is.close();
        }
      }

      ftp.logout();
      result = true;
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (ftp.isConnected()) {
        try {
          ftp.disconnect();
        } catch (IOException ioe) {
        }
      }
    }
    return result;
  }
Exemple #10
0
  /**
   * Description: 从FTP服务器下载单个文件
   *
   * @param url FTP服务器hostname
   * @param port FTP服务器端口
   * @param username FTP登录账号
   * @param password FTP登录密码
   * @param remotePath FTP服务器上的相对路径+文件名 example:/imagename.jpg
   * @param localPath 下载后保存到本地的路径
   * @param fileName 保存为该文件名的文件
   * @return
   */
  public static boolean downSingleFile(
      String url,
      int port,
      String username,
      String password,
      String remotePath,
      String localPath,
      String fileName) {
    boolean success = false;
    FTPClient ftp = null;
    FileOutputStream fos = null;
    try {
      int reply;
      ftp = getConnection(url, port, username, password);
      reply = ftp.getReplyCode();
      if (!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        return success;
      }
      boolean changeWorkDirState = false;
      fos = new FileOutputStream(localPath + "/" + fileName);

      ftp.setBufferSize(1024);
      // 设置文件类型(二进制)
      ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
      ftp.retrieveFile(remotePath, fos);
      changeWorkDirState = ftp.changeWorkingDirectory(remotePath); // 转移到FTP服务器目录

      ftp.logout();
      success = true;
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (ftp.isConnected()) {
        try {
          ftp.disconnect();
        } catch (IOException ioe) {
        }
      }
    }
    return success;
  }
Exemple #11
0
 /**
  * Download a remote file to a local OutputStream.
  *
  * @param remote Name of remote file.
  * @param local Local OutputStream.
  * @param isBinaryFile Indication if the file is binary
  * @throws FtpException
  */
 public void download(String remote, OutputStream local, boolean isBinaryFile)
     throws FtpException {
   if (ftp == null) {
     throw new FtpException(NOT_CONNECTED);
   }
   try {
     if (isBinaryFile) {
       ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
     }
     boolean ok = ftp.retrieveFile(remote, local);
     if (!ok) {
       String msg = ftp.getReplyString();
       throw new FtpException(msg);
     }
     local.close();
   } catch (FileNotFoundException fnfe) {
     throw new FtpException(fnfe);
   } catch (IOException ioe) {
     throw new FtpException(ioe);
   }
 }
  /**
   *
   *
   * <pre>
   * <b>Description:</b>
   * Function check file content on ftp folder
   * <b>Creation date: </b>02.05.08
   * <b>Modification date: </b>02.05.08
   * </pre>
   *
   * @param String sDirPath � directory contains file
   * @param String sFileName � file name
   * @param String sText - text which contains in file
   * @author Vitalii Fedorets
   * @return boolean � true if file contains text
   */
  public boolean checkTextInFile(String sDirPath, String sFileName, String sText) throws Exception {
    try {
      FTPClient oFtp = this.initFtpClientLoginChangeWorkingDirectory(sDirPath);

      ByteArrayOutputStream oBuf = new ByteArrayOutputStream();

      if (!oFtp.retrieveFile(sFileName, oBuf)) {
        log.setError("Could not read file `" + sFileName + "`");
        oFtp.disconnect();
        return false;
      }

      oFtp.disconnect();

      String sBuf = oBuf.toString();

      oBuf.close();

      return sBuf.contains(sText);
    } catch (Exception oEx) {
      throw oEx;
    }
  }
  /**
   * download file from remote host without progress percentage display
   *
   * @param folder remote directory
   * @param fileName the file you want to download
   * @param destfolder the destination folder you will store the file
   */
  public void downloadFile(String folder, String fileName, String destfolder) {
    try {
      ftp.enterLocalPassiveMode();
      ftp.changeWorkingDirectory(folder);
      LogUtils.log("Changing to directory:[" + folder + "]");
      String realFile = destfolder + File.separator + fileName;
      File localFile = new File(realFile);
      FileOutputStream fos = new FileOutputStream(localFile);
      FileInputStream fis = new FileInputStream(localFile);
      LogUtils.log("Start downloading..");
      FTPFile[] fs = ftp.listFiles();
      for (FTPFile f : fs) {
        if (f.getName().equals(fileName)) {
          ftp.retrieveFile(f.getName(), fos);
          LogUtils.log("Download done!");
          break;
        }
      }
      fos.close();

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemple #14
0
 public static Map<String, Object> getFile(DispatchContext dctx, Map<String, ?> context) {
   Locale locale = (Locale) context.get("locale");
   String localFilename = (String) context.get("localFilename");
   OutputStream localFile = null;
   try {
     localFile = new FileOutputStream(localFilename);
   } catch (IOException ioe) {
     Debug.logError(ioe, "[getFile] Problem opening local file", module);
     return ServiceUtil.returnError(
         UtilProperties.getMessage(resource, "CommonFtpFileCannotBeOpen", locale));
   }
   List<String> errorList = new LinkedList<String>();
   FTPClient ftp = new FTPClient();
   try {
     Integer defaultTimeout = (Integer) context.get("defaultTimeout");
     if (UtilValidate.isNotEmpty(defaultTimeout)) {
       Debug.logInfo(
           "[getFile] Set default timeout to: " + defaultTimeout.intValue() + " milliseconds",
           module);
       ftp.setDefaultTimeout(defaultTimeout.intValue());
     }
     ftp.connect((String) context.get("hostname"));
     if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
       errorList.add(UtilProperties.getMessage(resource, "CommonFtpConnectionRefused", locale));
     } else {
       String username = (String) context.get("username");
       String password = (String) context.get("password");
       if (!ftp.login(username, password)) {
         errorList.add(
             UtilProperties.getMessage(
                 resource,
                 "CommonFtpLoginFailure",
                 UtilMisc.toMap("username", username, "password", password),
                 locale));
       } else {
         Boolean binaryTransfer = (Boolean) context.get("binaryTransfer");
         boolean binary = (binaryTransfer == null) ? false : binaryTransfer.booleanValue();
         if (binary) {
           ftp.setFileType(FTP.BINARY_FILE_TYPE);
         }
         Boolean passiveMode = (Boolean) context.get("passiveMode");
         boolean passive = (passiveMode == null) ? false : passiveMode.booleanValue();
         if (passive) {
           ftp.enterLocalPassiveMode();
         }
         if (!ftp.retrieveFile((String) context.get("remoteFilename"), localFile)) {
           errorList.add(
               UtilProperties.getMessage(
                   resource,
                   "CommonFtpFileNotSentSuccesfully",
                   UtilMisc.toMap("replyString", ftp.getReplyString()),
                   locale));
         }
       }
       ftp.logout();
     }
   } catch (IOException ioe) {
     Debug.logWarning(ioe, "[getFile] caught exception: " + ioe.getMessage(), module);
     errorList.add(
         UtilProperties.getMessage(
             resource,
             "CommonFtpProblemWithTransfer",
             UtilMisc.toMap("errorString", ioe.getMessage()),
             locale));
   } finally {
     try {
       if (ftp.isConnected()) {
         ftp.disconnect();
       }
     } catch (Exception e) {
       Debug.logWarning(e, "[getFile] Problem with FTP disconnect: ", module);
     }
     try {
       localFile.close();
     } catch (Exception e) {
       Debug.logWarning(e, "[getFile] Problem closing local file: ", module);
     }
   }
   if (errorList.size() > 0) {
     Debug.logError(
         "[getFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList,
         module);
     return ServiceUtil.returnError(errorList);
   }
   return ServiceUtil.returnSuccess();
 }
Exemple #15
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) {
       }
     }
   }
 }
  public boolean ftpDownload() {

    boolean status = false;
    final String username = "******";
    final String password = "******";
    final String hostname = "ftp.memelab.ca";
    final int port = 21;

    String SFTPWORKINGDIR = "/public_html/jessescott/storage/android";

    FTPClient ftp = new FTPClient();
    try {
      ftp.connect(hostname, port);
      ftp.login(username, password);

      ftp.changeWorkingDirectory(SFTPWORKINGDIR);
      ftp.setFileType(FTP.BINARY_FILE_TYPE);
      ftp.setBufferSize(1024);
      ftp.enterLocalPassiveMode();

      OutputStream output = null;
      FTPFile[] files = ftp.listFiles();

      // Set Log Directory & File
      File logFile = new File(LOG_DIRECTORY + "logfile.txt");
      Log.d("FTP", "LOG should exist at " + logFile.getAbsolutePath());
      if (!logFile.exists()) {
        try {
          logFile.createNewFile();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }

      for (FTPFile f : files) {
        // Log Names
        Log.d("FTP", f.toFormattedString());

        // Set Path
        String remoteFile = f.getName();
        Log.d("FTP", "REMOTE file " + remoteFile);
        String localFile = MEDIA_DIRECTORY;
        localFile += remoteFile;
        Log.d("FTP", " is being put in LOCAL path " + localFile);
        output = new BufferedOutputStream(new FileOutputStream(localFile));

        // Set Time
        Time now = new Time(Time.getCurrentTimezone());
        now.setToNow();

        // Set Logger
        BufferedWriter logger = new BufferedWriter(new FileWriter(logFile, true));
        logger.append("Download for " + localFile + " started at " + now.format("%k:%M:%S"));
        logger.newLine();
        Long startTime = System.currentTimeMillis();

        // HTTP
        System.setProperty("http.keepAlive", "false");

        // Get Files
        Boolean success = ftp.retrieveFile(remoteFile, output);
        status = success;
        if (success) {
          Log.d("FTP", "SUCCESS");
          now.setToNow();
          Long elapsedTime = (System.currentTimeMillis() - startTime) / 1000;
          logger.append("Download for " + localFile + " finished at " + now.format("%k:%M:%S"));
          logger.newLine();
          logger.append("for an elapsedTime of " + elapsedTime + " seconds");
          logger.newLine();
          logger.newLine();
        }

        // Close Logger
        logger.flush();
        logger.close();

        // Close Buffer
        if (ftp != null) {
          output.close();
        }
      }

      ftp.logout();
      ftp.disconnect();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return status;
  }
Exemple #17
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);
    }
  }
Exemple #18
0
  @Override
  public void execute(Map<String, InputView> arg0, Map<String, OutputView> arg1) {

    // get connection cred's and hostname
    String serverUri = getStringPropertyValue("Connection");
    ResDef resdef = this.getLocalResourceObject(serverUri);
    String sourcedir = getStringPropertyValue("DirSource");
    String targetdir = getStringPropertyValue("DirTarget");
    FTPClient client = new FTPClient();
    // ftps

    try {
      FTPSClient ftpsclient = new FTPSClient();
    } catch (NoSuchAlgorithmException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    FTPFile[] files = null;
    try {
      client.connect(resdef.getPropertyValue("Host").toString());

      client.login(
          resdef.getPropertyValue("Username").toString(),
          resdef.getPropertyValue("Password").toString());
      client.enterLocalPassiveMode();
      info(Boolean.toString(client.isConnected()));
      if (sourcedir != null) files = client.listFiles(sourcedir);
      else files = client.listFiles();
      for (FTPFile f : files) {
        info(f.getName());
      }
    } catch (SocketException e) {
      // TODO Auto-generated catch block
      // e.printStackTrace();
      info(e.getMessage());
    } catch (IOException e) {
      // TODO Auto-generated catch block
      info(e.getMessage());
    }
    // Process input record
    InputView inView = arg0.values().iterator().next();
    if (inView == null) {
      info("No input view");
    }
    info("Input View: " + inView.getName());
    String file = inView.readRecord().getString("FileName").toString();
    info(file);

    // write files to local FS
    OutputStream output = null;
    for (int i = 0; i < files.length; i++) {
      if (files[i].getName().compareTo(file) == 0 || files[i].getName().compareTo("*") == 0)
        if (!files[i].getName().startsWith(".") && files[i].getType() != 1) {
          try {
            if (targetdir != null)
              output = new FileOutputStream(new File(targetdir + files[i].getName()));
            else output = new FileOutputStream(new File(files[i].getName()));
            client.retrieveFile(files[i].getName(), output);
          } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
    }

    try {
      output.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    // Create output view

    OutputView outputView = arg1.values().iterator().next();
    Record outRec = outputView.createRecord();
    for (int i = 0; i < files.length; i++) {
      outRec.set("Name", files[i].getName());
      if (files[i].getType() == 0) outRec.set("Type", "Directory");
      else outRec.set("Type", "File");
      outRec.set("User", files[i].getUser());
      outRec.set("Group", files[i].getGroup());
      outRec.set("Size", Long.toString(files[i].getSize()));
      outRec.set("TimeStamp", files[i].getTimestamp().getTime().toString());
      if (files[i].getName().compareTo(file) == 0) outputView.writeRecord(outRec);
    }
    outputView.completed();

    info(file);
  }