package com.chenyang.nse.bussiness.tools.net;

import com.chenyang.nse.bussiness.commmon.ApplicationConstants;
import com.chenyang.nse.bussiness.entity.vo.ResultVO;
import com.chenyang.nse.bussiness.tools.io.FileTool;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPFileEntryParser;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.parser.DefaultFTPFileEntryParserFactory;
import org.apache.commons.net.ftp.parser.ParserInitializationException;

public class FtpTool extends DefaultFTPFileEntryParserFactory {
   public static List<String> list(String url, int port, String username, String password, String path, String substring) throws Exception {
      FTPClient ftpClient = null;
      List<String> list = new ArrayList();

      Object loginresult;
      try {
         new ResultVO();
         ResultVO resultVO = NetTool.isHostConnectable(url, port);
         if (resultVO.getResult()) {
            ftpClient = new FTPClient();
            ftpClient.setDefaultTimeout(200000);
            ftpClient.connect(url, port);
            boolean loginresultNew = ftpClient.login(username, password);
            if (!loginresultNew) {
               Object var30 = null;
               return (List<String>)var30;
            }

            FTPFile[] files = null;

            try {
               if (path != null && !"".equals(path)) {
                  ftpClient.enterLocalPassiveMode();
                  files = ftpClient.listFiles(path);
               } else {
                  ftpClient.enterLocalPassiveMode();
                  files = ftpClient.listFiles();
               }
            } catch (Exception var26) {
               System.out.println("<<<<<<<<<<<<<<<<<<" + path);
            }

            for(FTPFile ftpFile : files) {
               if (ftpFile.getType() == 0) {
                  if (substring != null && !"".equals(substring)) {
                     if (ftpFile.getName().toUpperCase().contains(substring.toUpperCase())) {
                        list.add(ftpFile.getName());
                     }
                  } else {
                     list.add(ftpFile.getName());
                  }
               }
            }

            return list;
         }

         loginresult = null;
      } catch (Exception var27) {
         return list;
      } finally {
         if (ftpClient.isConnected()) {
            try {
               ftpClient.disconnect();
            } catch (IOException var25) {
            }
         }

      }

      return (List<String>)loginresult;
   }

   public static List<String> list(FTPClient ftpClient, String path, String substring) throws Exception {
      List<String> list = new ArrayList();
      FTPFile[] files = null;
      if (path != null && !"".equals(path)) {
         ftpClient.enterLocalPassiveMode();
         files = ftpClient.listFiles(path);
      } else {
         ftpClient.enterLocalPassiveMode();
         files = ftpClient.listFiles();
      }

      for(FTPFile ftpFile : files) {
         if (ftpFile.getType() == 0) {
            if (substring != null && !"".equals(substring)) {
               if (ftpFile.getName().toUpperCase().contains(substring.toUpperCase())) {
                  list.add(ftpFile.getName());
               }
            } else {
               list.add(ftpFile.getName());
            }
         }
      }

      return list;
   }

   public static Map<String, Object> listFiles(String url, int port, String username, String password, String path, String substring, String code) throws Exception {
      FTPClient ftpClient = null;
      Map<String, Object> filemap = new HashMap();

      Object loginresule;
      try {
         new ResultVO();
         ResultVO resultVO = NetTool.isHostConnectable(url, port);
         if (resultVO.getResult()) {
            ftpClient = new FTPClient();
            ftpClient.setControlEncoding(code);
            ftpClient.setControlKeepAliveReplyTimeout(1500000);
            ftpClient.setConnectTimeout(1500000);
            ftpClient.setControlKeepAliveTimeout(1500000L);
            ftpClient.enterLocalPassiveMode();
            if (!ftpClient.isConnected()) {
               ftpClient.connect(url, port);
            }

            boolean loginresuleNew2 = ftpClient.login(username, password);
            if (loginresuleNew2) {
               FTPFile[] files = null;
               List<Map<String, String>> list = new ArrayList();
               if (path != null && !"".equals(path)) {
                  boolean flag = ftpClient.changeWorkingDirectory(path);
                  if (!flag) {
                     filemap.put("fileresult", false);
                  } else {
                     ftpClient.setControlEncoding("GBK");
                     files = ftpClient.listFiles(path);
                     filemap.put("fileresult", true);

                     for(FTPFile ftpFile : files) {
                        Map<String, String> map = new HashMap();
                        if (ftpFile.getType() == 1) {
                           if (!".".equals(ftpFile.getName()) && !"..".equals(ftpFile.getName())) {
                              map.put("name", ftpFile.getName());
                              map.put("detail", ftpFile.getRawListing());
                              list.add(map);
                           }
                        } else if (ftpFile.getType() == 0) {
                           if (substring != null && !"".equals(substring)) {
                              if (ftpFile.getName().toUpperCase().contains(substring.toUpperCase())) {
                                 map.put("name", ftpFile.getName());
                                 map.put("detail", ftpFile.getRawListing());
                                 list.add(map);
                              }
                           } else {
                              map.put("name", ftpFile.getName());
                              map.put("detail", ftpFile.getRawListing());
                              list.add(map);
                           }
                        }
                     }
                  }
               } else {
                  files = ftpClient.listFiles();
               }

               filemap.put("filelist", list);
               return filemap;
            }

            filemap.put("fileresult", false);
            filemap.put("filelist", "ftp服务器用户名或密码错误");
            if (ftpClient != null) {
               ftpClient.disconnect();
            }

            Object files = filemap;
            return (Map<String, Object>)files;
         }

         filemap.put("fileresult", false);
         filemap.put("filelist", resultVO.getMessage());
         loginresule = filemap;
      } catch (Exception var29) {
         return filemap;
      } finally {
         if (ftpClient.isConnected()) {
            try {
               ftpClient.disconnect();
            } catch (IOException var28) {
            }
         }

      }

      return (Map<String, Object>)loginresule;
   }

   public static Map<String, Object> listFiles(FTPClient ftpClient, String path, String substring, String code) throws Exception {
      ftpClient.setControlEncoding(code);
      Map<String, Object> filemap = new HashMap();
      new ResultVO();
      FTPFile[] files = null;
      List<Map<String, String>> list = new ArrayList();
      if (path != null && !"".equals(path)) {
         boolean flag = ftpClient.changeWorkingDirectory(path);
         if (!flag) {
            filemap.put("fileresult", false);
         } else {
            files = ftpClient.listFiles(path);
            filemap.put("fileresult", true);

            for(FTPFile ftpFile : files) {
               Map<String, String> map = new HashMap();
               if (ftpFile.getType() == 1) {
                  if (!".".equals(ftpFile.getName()) && !"..".equals(ftpFile.getName())) {
                     map.put("name", ftpFile.getName());
                     map.put("detail", ftpFile.getRawListing());
                     list.add(map);
                  }
               } else if (ftpFile.getType() == 0) {
                  if (substring != null && !"".equals(substring)) {
                     if (ftpFile.getName().toUpperCase().contains(substring.toUpperCase())) {
                        map.put("name", ftpFile.getName());
                        map.put("detail", ftpFile.getRawListing());
                        list.add(map);
                     }
                  } else {
                     map.put("name", ftpFile.getName());
                     map.put("detail", ftpFile.getRawListing());
                     list.add(map);
                  }
               }
            }
         }

         filemap.put("filelist", list);
      } else {
         files = ftpClient.listFiles();
      }

      return filemap;
   }

   public static Map<String, Object> getFiles(FTPClient ftpClient, String path, String substring, String code) throws Exception {
      Map<String, Object> filemap = new HashMap();
      ftpClient.setControlEncoding(code);
      FTPFile[] files = null;
      List<Map<String, String>> list = new ArrayList();
      if (path != null && !"".equals(path)) {
         boolean flag = ftpClient.changeWorkingDirectory(path);
         if (flag) {
            files = ftpClient.listFiles(path);
            filemap.put("fileresult", true);

            for(FTPFile ftpFile : files) {
               Map<String, String> map = new HashMap();
               if (ftpFile.getType() == 1) {
                  if (!".".equals(ftpFile.getName()) && !"..".equals(ftpFile.getName())) {
                     map.put("name", ftpFile.getName());
                     map.put("detail", ftpFile.getRawListing());
                     list.add(map);
                  }
               } else if (ftpFile.getType() == 0) {
                  if (substring != null && !"".equals(substring)) {
                     if (ftpFile.getName().toUpperCase().contains(substring.toUpperCase())) {
                        map.put("name", ftpFile.getName());
                        map.put("detail", ftpFile.getRawListing());
                        list.add(map);
                     }
                  } else {
                     map.put("name", ftpFile.getName());
                     map.put("detail", ftpFile.getRawListing());
                     list.add(map);
                  }
               }
            }
         } else {
            filemap.put("fileresult", false);
         }
      } else {
         files = ftpClient.listFiles();
      }

      filemap.put("filelist", list);
      return filemap;
   }

   public static ResultVO ftpConnect(String url, int port, String username, String password) {
      FTPClient ftpClient = new FTPClient();
      ResultVO resultvo = new ResultVO();

      try {
         ftpClient.connect(url, port);
         boolean loginresult = ftpClient.login(username, password);
         resultvo.setResult(loginresult);
         return resultvo;
      } catch (IOException e) {
         e.printStackTrace();
         resultvo.setMessage(getExceptionSrintStackTrace(e));
         resultvo.setResult(false);
         return resultvo;
      }
   }

   public static String getExceptionSrintStackTrace(Exception e) {
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      e.printStackTrace(pw);
      return sw.toString();
   }

   public static Throwable getExceptionType(Exception e) {
      return e;
   }

   public static String getExceptionMessage(Exception e) {
      return e.getMessage();
   }

   public static boolean uploadFile(String url, int port, String username, String password, String path, String filename, InputStream input) {
      boolean success = false;
      FTPClient ftp = new FTPClient();

      boolean var10;
      try {
         ftp.connect(url, port);
         ftp.login(username, password);
         int reply = ftp.getReplyCode();
         if (FTPReply.isPositiveCompletion(reply)) {
            ftp.changeWorkingDirectory(path);
            ftp.setFileType(2);
            ftp.setControlEncoding("UTF-8");
            ftp.storeFile(filename, input);
            input.close();
            ftp.logout();
            success = true;
            return success;
         }

         ftp.disconnect();
         var10 = success;
      } catch (IOException e) {
         e.printStackTrace();
         return success;
      } finally {
         if (ftp.isConnected()) {
            try {
               ftp.disconnect();
            } catch (IOException var20) {
            }
         }

      }

      return var10;
   }

   public static void uploadFile(FTPClient ftp, String path, String filename, InputStream input) throws Exception {
      ftp.changeWorkingDirectory(path);
      ftp.setFileType(2);
      ftp.setControlEncoding("UTF-8");
      ftp.storeFile(filename, input);
   }

   public static void createFile(String url, int port, String username, String password, String path, String filename, String title) {
      InputStream input = null;

      try {
         String temppath = ApplicationConstants.webRoot + filename;
         FileTool.createFile(temppath);
         FileTool.writeContentToFile(temppath, title);
         input = new FileInputStream(new File(temppath));
         uploadFile(url, port, username, password, path, filename, input);
         FileTool.removeFile(path);
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } finally {
         try {
            input.close();
         } catch (IOException e) {
            e.printStackTrace();
         }

      }

   }

   public static void createFile(FTPClient ftp, String path, String filename) {
      InputStream input = null;

      try {
         String temppath = ApplicationConstants.webRoot + filename;
         FileTool.createFile(temppath);
         FileTool.writeContentToFile(temppath, "");
         input = new FileInputStream(new File(temppath));
         uploadFile(ftp, path, filename, input);
         FileTool.removeFile(path);
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            input.close();
         } catch (IOException e) {
            e.printStackTrace();
         }

      }

   }

   public static void createFolder(String ip, int port, String username, String password, String path, String foldername) {
      FTPClient ftpClient = new FTPClient();

      try {
         ftpClient.connect(ip, port);
         if (ftpClient.login(username, password) && path != null && path.compareTo("") != 0 && ftpClient.changeWorkingDirectory(path)) {
            ftpClient.makeDirectory(foldername);
         }
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            ftpClient.disconnect();
         } catch (IOException e) {
            e.printStackTrace();
         }

      }

   }

   public static void removeFile(String ip, int port, String username, String password, String path, String filename) {
      FTPClient ftpClient = new FTPClient();

      try {
         ftpClient.connect(ip, port);
         if (ftpClient.login(username, password)) {
            ftpClient.deleteFile(path + filename);
         }
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            ftpClient.disconnect();
         } catch (IOException e) {
            e.printStackTrace();
         }

      }

   }

   public static boolean isFileExist(String ip, int port, String username, String password, String path, String filename) {
      try {
         for(String item : list(ip, port, username, password, path, filename)) {
            if (item.equals(filename)) {
               return true;
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }

      return false;
   }

   public static boolean isFileExist(FTPClient ftp, String path, String filename) {
      try {
         for(String item : list(ftp, path, filename)) {
            if (item.equals(filename)) {
               return true;
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }

      return false;
   }

   public static boolean downFile(String url, int port, String username, String password, String remotePath, String fileName, String localPath) {
      boolean success = false;
      FTPClient ftp = new FTPClient();

      boolean fs;
      try {
         ftp.connect(url, port);
         ftp.login(username, password);
         int reply = ftp.getReplyCode();
         if (FTPReply.isPositiveCompletion(reply)) {
            ftp.changeWorkingDirectory(remotePath);
            FTPFile[] fs2 = ftp.listFiles();

            for(FTPFile ff : fs2) {
               if (ff.getName().equals(fileName)) {
                  File localFile = new File(localPath);
                  OutputStream is = new FileOutputStream(localFile);
                  ftp.retrieveFile(ff.getName(), is);
                  is.close();
               }
            }

            ftp.logout();
            success = true;
            return success;
         }

         ftp.disconnect();
         fs = success;
      } catch (IOException e) {
         e.printStackTrace();
         return success;
      } finally {
         if (ftp.isConnected()) {
            try {
               ftp.disconnect();
            } catch (IOException var25) {
            }
         }

      }

      return fs;
   }

   public static boolean downFile(FTPClient ftp, String remotePath, String fileName, String localPath) {
      boolean success = false;

      try {
         FTPFile[] fs = ftp.listFiles();

         for(FTPFile ff : fs) {
            if (ff.getName().equals(fileName)) {
               File localFile = new File(localPath);
               OutputStream is = new FileOutputStream(localFile + File.separator + fileName);
               ftp.retrieveFile(ff.getName(), is);
               if (is != null) {
                  is.close();
               }
            }
         }

         success = true;
      } catch (IOException e) {
         e.printStackTrace();
      }

      return success;
   }

   public static int getDataCount(String url, int port, String username, String password, String path, String filename) throws Exception {
      new ResultVO();
      ResultVO resultVO = NetTool.isHostConnectable(url, port);
      if (resultVO == null) {
         return 0;
      } else {
         FTPClient ftpClient = new FTPClient();
         InputStream is = null;
         ftpClient.connect(url, port);
         boolean loginresult = ftpClient.login(username, password);
         ftpClient.setControlEncoding("UTF-8");
         ftpClient.setFileType(2);
         ftpClient.enterLocalPassiveMode();
         ftpClient.changeWorkingDirectory(path);
         is = ftpClient.retrieveFileStream(filename);
         if (!loginresult) {
            return 0;
         } else {
            int count = 0;
            BufferedReader tBufferedReader = new BufferedReader(new InputStreamReader(is));
            new String("");

            while(tBufferedReader.readLine() != null) {
               ++count;
            }

            return count;
         }
      }
   }

   public static int getDataCount(FTPClient ftpClient, String path, String filename) throws Exception {
      InputStream is = null;
      ftpClient.setControlEncoding("UTF-8");
      ftpClient.setFileType(2);
      ftpClient.enterLocalPassiveMode();
      ftpClient.changeWorkingDirectory(path);
      is = ftpClient.retrieveFileStream(filename);
      int count = 0;
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader tBufferedReader = new BufferedReader(isr);
      new String("");

      while(tBufferedReader.readLine() != null) {
         ++count;
      }

      if (tBufferedReader != null) {
         tBufferedReader.close();
      }

      if (isr != null) {
         isr.close();
      }

      if (is != null) {
         is.close();
         ftpClient.completePendingCommand();
      }

      return count;
   }

   public static List<String> getData(String url, int port, String username, String password, String path, String filename, String code) throws Exception {
      List<String> content = new ArrayList();
      FTPClient ftpClient = new FTPClient();
      InputStream is = null;
      ftpClient.connect(url, port);
      boolean loginresult = ftpClient.login(username, password);
      ftpClient.setControlEncoding(code);
      ftpClient.setFileType(2);
      ftpClient.enterLocalPassiveMode();
      ftpClient.changeWorkingDirectory(path);
      is = ftpClient.retrieveFileStream(filename);
      if (!loginresult) {
         return null;
      } else {
         BufferedReader tBufferedReader = new BufferedReader(new InputStreamReader(is));
         new String("");

         String sTempOneLine;
         while((sTempOneLine = tBufferedReader.readLine()) != null) {
            content.add(sTempOneLine);
         }

         tBufferedReader.close();
         is.close();
         return content;
      }
   }

   public static List<String> getData(FTPClient ftpClient, String path, String filename, String code) throws Exception {
      List<String> content = new ArrayList();
      InputStream is = null;
      ftpClient.setControlEncoding(code);
      ftpClient.setFileType(2);
      ftpClient.enterLocalPassiveMode();
      ftpClient.changeWorkingDirectory(path);
      is = ftpClient.retrieveFileStream(filename);
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader tBufferedReader = new BufferedReader(isr);
      new String("");

      String sTempOneLine;
      while((sTempOneLine = tBufferedReader.readLine()) != null) {
         content.add(sTempOneLine);
      }

      if (tBufferedReader != null) {
         tBufferedReader.close();
      }

      if (isr != null) {
         isr.close();
      }

      if (is != null) {
         is.close();
         ftpClient.completePendingCommand();
      }

      return content;
   }

   public static InputStream getDataInputStream(String url, int port, String username, String password, String path, String filename, String code) throws Exception {
      FTPClient ftpClient = null;
      InputStream is = null;

      try {
         ftpClient = new FTPClient();
         ftpClient.enterLocalPassiveMode();
         ftpClient.connect(url, port);
         ftpClient.login(username, password);
         ftpClient.setControlEncoding(code);
         ftpClient.setFileType(2);
         ftpClient.enterLocalPassiveMode();
         ftpClient.changeWorkingDirectory(path);
         is = ftpClient.retrieveFileStream(filename);
      } catch (Exception var18) {
      } finally {
         if (ftpClient.isConnected()) {
            try {
               ftpClient.disconnect();
            } catch (IOException var17) {
            }
         }

      }

      return is;
   }

   public static InputStream getDataInputStream(FTPClient ftpClient, String path, String filename, String code) throws Exception {
      InputStream is = null;
      ftpClient.changeWorkingDirectory(path);
      is = ftpClient.retrieveFileStream(filename);
      return is;
   }

   public static void main(String[] args) throws Exception {
      File file = new File("D:\\lixin\\201910110910163.xlsx");
      FileInputStream fis = new FileInputStream(file);
      uploadFile("192.168.2.5", 21, "admin", "admin", "/", "abc.xls", fis);
   }

   public FTPFileEntryParser createFileEntryParser(String key) {
      if (key == null) {
         throw new ParserInitializationException("Parser key cannot be null");
      } else {
         Class parserClass = null;
         FTPFileEntryParser parser = null;

         try {
            parserClass = Class.forName(key);
            parser = (FTPFileEntryParser)parserClass.newInstance();
         } catch (ClassNotFoundException var7) {
            try {
               String ukey = null;
               if (null != key) {
                  ukey = key.toUpperCase(Locale.ENGLISH);
               }

               System.out.println("--------------------the ukey is :" + ukey);
               if (ukey.indexOf("UNIX") < 0 && ukey.indexOf("TYPE: L8") < 0) {
                  if (ukey.indexOf("VMS") >= 0) {
                     parser = this.createVMSVersioningFTPEntryParser();
                  } else if (ukey.indexOf("WINDOWS") < 0 && ukey.indexOf("MSDOS") < 0 && ukey.indexOf("FTP SERVER, HUAWEI CO") < 0) {
                     if (ukey.indexOf("OS/2") >= 0) {
                        parser = this.createOS2FTPEntryParser();
                     } else if (ukey.indexOf("OS/400") < 0 && ukey.indexOf("AS/400") < 0) {
                        if (ukey.indexOf("MVS") >= 0) {
                           parser = this.createMVSEntryParser();
                        } else {
                           if (ukey.indexOf("NETWARE") < 0) {
                              throw new ParserInitializationException("Unknown parser type: " + key);
                           }

                           parser = this.createNetwareFTPEntryParser();
                        }
                     } else {
                        parser = this.createOS400FTPEntryParser();
                     }
                  } else {
                     parser = this.createNTFTPEntryParser();
                  }
               } else {
                  System.out.println("the ukey is :" + ukey);
                  parser = this.createUnixFTPEntryParser();
               }
            } catch (NoClassDefFoundError nf) {
               throw new ParserInitializationException("Error initializing parser", nf);
            }
         } catch (NoClassDefFoundError e) {
            throw new ParserInitializationException("Error initializing parser", e);
         } catch (ClassCastException e) {
            throw new ParserInitializationException(parserClass.getName() + " does not implement the interface org.apache.commons.net.ftp.FTPFileEntryParser.", e);
         } catch (Throwable e) {
            throw new ParserInitializationException("Error initializing parser", e);
         }

         return parser;
      }
   }
}
