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

import com.chenyang.nse.bussiness.entity.vo.ResultVO;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
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.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.IOUtils;

public class SFTPUtil {
   private static ChannelSftp sftp;
   private static Session session;
   private static String username;
   private static String password;
   private static String privateKey;
   private static String host;
   private static int port;

   public SFTPUtil(String username, String password, String host, int port) {
      SFTPUtil.username = username;
      SFTPUtil.password = password;
      SFTPUtil.host = host;
      SFTPUtil.port = port;
   }

   public SFTPUtil(String username, String host, int port, String privateKey) {
      SFTPUtil.username = username;
      SFTPUtil.host = host;
      SFTPUtil.port = port;
      SFTPUtil.privateKey = privateKey;
   }

   public SFTPUtil() {
   }

   public static ResultVO login() {
      ResultVO resultvo = new ResultVO();

      try {
         JSch jsch = new JSch();
         if (privateKey != null) {
            jsch.addIdentity(privateKey);
         }

         session = jsch.getSession(username, host, port);
         if (password != null) {
            session.setPassword(password);
         }

         Properties config = new Properties();
         config.put("StrictHostKeyChecking", "no");
         config.put("PreferredAuthentications", "publickey,keyboard-interactive,password");
         session.setConfig(config);
         session.connect();
         Channel channel = session.openChannel("sftp");
         channel.connect();
         sftp = (ChannelSftp)channel;
         boolean result = session.isConnected();
         resultvo.setResult(result);
         return resultvo;
      } catch (JSchException 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 String execCmd(String command) {
      String resultJson = null;
      ChannelExec channelExec = null;
      InputStream in = null;
      if (command != null) {
         try {
            login();
            channelExec = (ChannelExec)session.openChannel("exec");
            channelExec.setCommand(command);
            channelExec.setErrStream(System.err);
            channelExec.connect();
            in = channelExec.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            resultJson = reader.readLine();
         } catch (Exception e) {
            e.printStackTrace();
         } finally {
            if (null != channelExec) {
               channelExec.disconnect();
            }

         }
      }

      return resultJson;
   }

   private static String getServerData(String filePath) {
      ChannelSftp sftp = null;
      StringBuffer buffer = new StringBuffer();

      try {
         if (!session.isConnected()) {
            login();
         }

         Channel channel = session.openChannel("sftp");
         channel.connect();
         sftp = (ChannelSftp)channel;
         InputStream inputStream = sftp.get(filePath);
         BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
         String line = "";

         while((line = in.readLine()) != null) {
            buffer.append(line);
         }

         inputStream.close();
         in.close();
         System.out.println(" 执行结果为: " + buffer.toString());
      } catch (IOException e) {
         e.printStackTrace();
      } catch (JSchException e) {
         e.printStackTrace();
      } catch (SftpException e) {
         e.printStackTrace();
      } finally {
         if (null != sftp) {
            sftp.quit();
         }

         closeSession();
      }

      return buffer.toString();
   }

   public static void closeSession() {
      if (session != null) {
         session.disconnect();
      }

   }

   public void logout() {
      if (sftp != null && sftp.isConnected()) {
         sftp.disconnect();
      }

      if (session != null && session.isConnected()) {
         session.disconnect();
      }

   }

   public void upload(String directory, String sftpFileName, InputStream input) throws SftpException {
      try {
         sftp.cd(directory);
      } catch (SftpException var5) {
         System.out.print("directory is not exist");
         sftp.mkdir(directory);
         sftp.cd(directory);
      }

      sftp.put(input, sftpFileName);
      System.out.printf("file:{} is upload successful", sftpFileName);
   }

   public void upload(String directory, String uploadFile) throws FileNotFoundException, SftpException {
      File file = new File(uploadFile);
      this.upload(directory, file.getName(), (InputStream)(new FileInputStream(file)));
   }

   public void upload(String directory, String sftpFileName, byte[] byteArr) throws SftpException {
      this.upload(directory, sftpFileName, (InputStream)(new ByteArrayInputStream(byteArr)));
   }

   public void upload(String directory, String sftpFileName, String dataStr, String charsetName) throws UnsupportedEncodingException, SftpException {
      this.upload(directory, sftpFileName, (InputStream)(new ByteArrayInputStream(dataStr.getBytes(charsetName))));
   }

   public void download(String directory, String downloadFile, String saveFile) throws SftpException, FileNotFoundException {
      if (directory != null && !"".equals(directory)) {
         sftp.cd(directory);
      }

      File file = new File(saveFile);
      sftp.get(downloadFile, new FileOutputStream(file));
   }

   public byte[] download(String directory, String downloadFile) throws SftpException, IOException {
      if (directory != null && !"".equals(directory)) {
         sftp.cd(directory);
      }

      InputStream is = sftp.get(downloadFile);
      byte[] fileData = IOUtils.toByteArray(is);
      System.out.printf("file:{} is download successful", downloadFile);
      return fileData;
   }

   public void delete(String directory, String deleteFile) throws SftpException {
      sftp.cd(directory);
      sftp.rm(deleteFile);
   }

   public Vector<?> listFiles(String directory) throws SftpException {
      return sftp.ls(directory);
   }

   public String getPwd() throws SftpException {
      return sftp.pwd();
   }

   public void getCd(String path) throws SftpException {
      sftp.cd(path);
   }

   public List<String> list(String directory) throws SftpException {
      List<String> list = new ArrayList();
      Vector listfile = sftp.ls(directory);

      try {
         for(Object obj : listfile) {
            if (obj instanceof ChannelSftp.LsEntry) {
               String fileName = ((ChannelSftp.LsEntry)obj).getFilename();
               if (!fileName.equals(".") && !fileName.equals("..") && fileName.contains(".")) {
                  list.add(fileName);
               }
            }
         }
      } catch (Exception var7) {
      }

      return list;
   }

   public boolean isExitFile(String directory) {
      boolean isexit = true;

      try {
         sftp.stat(directory);
      } catch (SftpException e) {
         isexit = false;
         e.printStackTrace();
      }

      return isexit;
   }

   public int getDataCount(String directory) throws Exception {
      int count = 0;
      InputStream is = null;
      BufferedReader tBufferedReader = null;
      InputStreamReader isr = null;

      try {
         is = sftp.get(directory);
         isr = new InputStreamReader(is);
         tBufferedReader = new BufferedReader(isr);
         new String("");

         while(tBufferedReader.readLine() != null) {
            ++count;
         }
      } catch (SftpException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         if (tBufferedReader != null) {
            tBufferedReader.close();
         }

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

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

      }

      return count;
   }

   public List<String> getData(String directory, String code) throws Exception {
      List<String> content = new ArrayList();
      InputStream is = null;
      InputStreamReader isr = null;
      BufferedReader tBufferedReader = null;

      try {
         is = sftp.get(directory);
         isr = new InputStreamReader(is, code);
         tBufferedReader = new BufferedReader(isr);
         new String("");

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

         tBufferedReader.close();
      } catch (SftpException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         if (tBufferedReader != null) {
            tBufferedReader.close();
         }

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

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

      }

      return content;
   }

   public List<String> getDataBySkiprows(String directory, String skiprows, String code) throws Exception {
      List<String> content = new ArrayList();
      int count = 1;

      try {
         InputStream is = sftp.get(directory);
         InputStreamReader isr = new InputStreamReader(is, code);
         BufferedReader tBufferedReader = new BufferedReader(isr);
         new String("");

         String sTempOneLine;
         for(; (sTempOneLine = tBufferedReader.readLine()) != null; ++count) {
            if (count > Integer.parseInt(skiprows)) {
               content.add(sTempOneLine);
            }
         }

         is.close();
         tBufferedReader.close();
      } catch (SftpException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }

      return content;
   }

   public InputStream getInputStream(String directory) throws Exception {
      InputStream streatm = sftp.get(directory);
      return streatm;
   }

   public InputStream getDataInputStream(String directory) throws Exception {
      InputStream is = null;
      is = sftp.get(directory);
      return is;
   }

   public boolean isFile(String longname, String name) {
      boolean flag = false;
      if (!".".equals(name) && !"..".equals(name) && !".".equals(name.substring(0, 1))) {
         Pattern pattern = Pattern.compile("[^\\s]*");
         Matcher matcher = pattern.matcher(longname);
         List<String> detaillist = new ArrayList();
         int j = 0;

         while(matcher.find() && j < 5) {
            if (!"".equals(matcher.group())) {
               detaillist.add(matcher.group());
               ++j;
            }
         }

         if (!"d".equals(((String)detaillist.get(0)).substring(0, 1)) && !"l".equals(((String)detaillist.get(0)).substring(0, 1))) {
            flag = true;
         } else {
            flag = false;
         }
      }

      return flag;
   }

   public static void main(String[] args) throws SftpException, IOException {
      SFTPUtil sftp = new SFTPUtil("infa", "infa", "192.168.2.106", 22);
      SftpATTRS attrs = null;
      attrs = SFTPUtil.sftp.stat("/data/infa_file/a/SHIJIAN1.txt");
      System.out.println(attrs);
   }
}
