package com.palacesun.engine.gateway;

import com.palacesun.engine.common.ClientUtil;
import com.palacesun.engine.common.GatewaySocketCallback;
import com.palacesun.engine.common.TelnetUtil;
import com.palacesun.engine.gateway.cache.CacheFromEncryptionGateway;
import com.palacesun.engine.gateway.cache.UserOriginalVO;
import com.palacesun.engine.gateway.netty.NettyStartApplicationRunner;
import com.palacesun.engine.gateway.util.GatewaySocketLogUtil;
import com.palacesun.engine.test.TestJdbcEventListener;
import com.palacesun.engine.wrapper.PreparedStatementWrapper;
import com.chenyang.fastjson.JSON;
import com.chenyang.fastjson.JSONArray;
import com.chenyang.fastjson.JSONObject;
import com.chenyang.fastjson.TypeReference;
import com.palacesun.masking.adapter.StringUtils;
import com.palacesun.masking.tools.EngineUtil;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

public class EncryptionGatewayManager {
   protected static Logger logger = Logger.getLogger(EncryptionGatewayManager.class.getName());
   static final String GATEWAY_PUSH_APPUSER_ORIGINAL_INFOS_URI = "/jar_socket_controller/pullAppUserOriginalInfos";
   static final String GATEWAY_PUSH_GATEWAYUSER_ORIGINAL_INFOS_URI = "/jar_socket_controller/pullGatewayOriginalInfos";
   static final String GATEWAY_PUSH_GLOBAL_ORIGINAL_INFOS_URI = "/jar_socket_controller/pullGlobalOriginalConfig";
   static final String GATEWAY_NOTICE_PULL_STATUS = "/jar_socket_controller/noticePullStatus";
   public static int ROOT_PORT = 65536;
   public static Map<String, String> CONFIG_PROPERTIES = new HashMap();
   public static Map<String, String> ROOT_CONFIG_PROPERTIES = new HashMap();
   public static boolean sendUrl = false;
   static long lastTime = 0L;

   public EncryptionGatewayManager() {
      run();
   }

   public static void run() {
      InnerThread innerThread = new InnerThread();
      innerThread.start();
   }

   public static void scheduledTask() throws InterruptedException {
      while(true) {
         try {
            Thread.sleep(Long.parseLong(getParameterValue("pullInterval")));
            pullTask();
         } catch (Exception e) {
            e.printStackTrace();
            GatewaySocketLogUtil.writeLog("*****************************定时任务遭遇Exception异常***************************");
         } catch (Throwable e) {
            e.printStackTrace();
            GatewaySocketLogUtil.writeLog("*****************************定时任务遭遇Throwable异常***************************");
         }
      }
   }

   public static void pullTask() {
      GatewaySocketLogUtil.writeLog("【【【【一次拉取开始！！！！！！】】】】");

      try {
         String ip = getParameterValue("gatewayurl").split("://")[1].split(":")[0];
         String port = getParameterValue("gatewayurl").split("://")[1].split(":")[1];
         if (TelnetUtil.telnet(ip, Integer.parseInt(port), 10000)) {
            if (noticeMyStatus("2")) {
               GatewaySocketLogUtil.writeLog("平台通知加密规则有变化，需要重新拉取");

               try {
                  EngineUtil.initRule();
                  TestJdbcEventListener.sqlColumSecretKeyMap.clear();
                  PreparedStatementWrapper.sqlIndexKeyMap.clear();
               } catch (Exception var3) {
                  GatewaySocketLogUtil.writeLog("拉取加密规则失败");
               }
            } else {
               GatewaySocketLogUtil.writeLog("平台通知加密规则无变化，不需要重新拉取");
            }

            pullAppUserOriginalInfos();
            pullGatewayUserOriginalInfos();
            pullGlobalOriginalConfig();
            noticeMyStatus("3");
         } else {
            GatewaySocketLogUtil.writeLog("连接加密网关 " + getParameterValue("gatewayurl") + "超时，本次拉取终止！");
         }

         GatewaySocketLogUtil.writeLog("【【【【一次拉取结束！！！！！！】】】】");
         GatewaySocketLogUtil.writeBlankRows();
      } catch (Exception var4) {
         noticeMyStatus("4");
         GatewaySocketLogUtil.writeLog("【【【【一次拉取遭遇Exception异常！！！！！！】】】】");
      } catch (Throwable var5) {
         noticeMyStatus("4");
         GatewaySocketLogUtil.writeLog("【【【【一次拉取遭遇Throwable异常！！！！！！】】】】");
      }

   }

   public static void receiveAppUserOriginalInfos(String param) {
      CacheFromEncryptionGateway.appUserOriginalInfos = JSONArray.parseArray(param, UserOriginalVO.class);
   }

   public static void receiveGatewayUserOriginalInfos(String param) {
      CacheFromEncryptionGateway.gatewayUserOriginalInfos = JSONArray.parseArray(param, UserOriginalVO.class);
   }

   public static void receiveGlobalOriginalConfig(String json) {
      Map<String, Integer> globalConfig = (Map)JSON.toJavaObject(JSON.parseObject(json), Map.class);
      CacheFromEncryptionGateway.appUserGlobalOriginalConfig = (Integer)globalConfig.get("globalOriginalConfig");
   }

   public void setGateWayUserGlobalOriginalConfig() {
      CacheFromEncryptionGateway.gatewayUserGlobalOriginalConfig = 1;
   }

   public static void pullAppUserOriginalInfos() {
      GatewaySocketLogUtil.writeBlankRows();
      GatewaySocketLogUtil.writeLog("执行" + (new Exception()).getStackTrace()[0].getMethodName() + "方法开始！");

      try {
         String url = getParameterValue("gatewayurl") + "/jar_socket_controller/pullAppUserOriginalInfos";
         Map<String, String> param = new HashMap();
         param.put("projectId", getParameterValue("projectid"));
         param.put("remotePort", String.valueOf(ROOT_PORT));
         url = url + "?projectId=" + getParameterValue("projectid");
         url = url + "&remotePort=" + ROOT_PORT;
         String result = ClientUtil.doPost(url, JSON.toJSONString(param));
         GatewaySocketLogUtil.writeLog(url + "接口返回的内容为：" + result);
         JSONObject jsonObject = JSONObject.parseObject(result);
         if (!jsonObject.get("data").toString().equals("[]")) {
            JSONArray array = jsonObject.getJSONArray("data");
            List<UserOriginalVO> data = (List)array.toJavaObject(new TypeReference<List<UserOriginalVO>>() {
            });
            CacheFromEncryptionGateway.appUserOriginalInfos = data;
         }
      } catch (Exception var6) {
         GatewaySocketLogUtil.writeLog("执行" + (new Exception()).getStackTrace()[0].getMethodName() + "方法异常！");
      }

      GatewaySocketLogUtil.writeLog("执行" + (new Exception()).getStackTrace()[0].getMethodName() + "方法结束！");
      GatewaySocketLogUtil.writeBlankRows();
   }

   public static void pullGatewayUserOriginalInfos() {
      GatewaySocketLogUtil.writeBlankRows();

      try {
         GatewaySocketLogUtil.writeLog("执行" + (new Exception()).getStackTrace()[0].getMethodName() + "方法开始！");
         String url = getParameterValue("gatewayurl") + "/jar_socket_controller/pullGatewayOriginalInfos";
         Map<String, String> param = new HashMap();
         param.put("projectId", getParameterValue("projectid"));
         param.put("remotePort", String.valueOf(ROOT_PORT));
         url = url + "?projectId=" + getParameterValue("projectid");
         url = url + "&remotePort=" + ROOT_PORT;
         String result = ClientUtil.doPost(url, JSON.toJSONString(param));
         GatewaySocketLogUtil.writeLog(url + "接口返回的内容为：" + result);
         JSONObject jsonObject = JSONObject.parseObject(result);
         if (!jsonObject.get("data").toString().equals("[]")) {
            JSONArray array = jsonObject.getJSONArray("data");
            List<UserOriginalVO> data = (List)array.toJavaObject(new TypeReference<List<UserOriginalVO>>() {
            });
            CacheFromEncryptionGateway.gatewayUserOriginalInfos = data;
         }
      } catch (Exception var6) {
         GatewaySocketLogUtil.writeLog("执行" + (new Exception()).getStackTrace()[0].getMethodName() + "方法异常！");
      }

      GatewaySocketLogUtil.writeLog("执行" + (new Exception()).getStackTrace()[0].getMethodName() + "方法结束！");
      GatewaySocketLogUtil.writeBlankRows();
   }

   public static void pullGlobalOriginalConfig() {
      GatewaySocketLogUtil.writeBlankRows();

      try {
         GatewaySocketLogUtil.writeLog("执行" + (new Exception()).getStackTrace()[0].getMethodName() + "方法开始！");
         String url = getParameterValue("gatewayurl") + "/jar_socket_controller/pullGlobalOriginalConfig";
         Map<String, Object> param = new HashMap();
         param.put("projectId", getParameterValue("projectid"));
         param.put("remotePort", String.valueOf(ROOT_PORT));
         url = url + "?projectId=" + getParameterValue("projectid");
         url = url + "&remotePort=" + ROOT_PORT;
         String result = ClientUtil.doPost(url, JSON.toJSONString(param));
         GatewaySocketLogUtil.writeLog(url + "接口返回的内容为：" + result);
         JSONObject jsonObject = JSONObject.parseObject(result);
         Integer globalOriginalConfig = (Integer)jsonObject.get("data");
         CacheFromEncryptionGateway.appUserGlobalOriginalConfig = globalOriginalConfig;
      } catch (Exception var5) {
         GatewaySocketLogUtil.writeLog("执行" + (new Exception()).getStackTrace()[0].getMethodName() + "方法异常！");
      }

      GatewaySocketLogUtil.writeLog("执行" + (new Exception()).getStackTrace()[0].getMethodName() + "方法结束！");
      GatewaySocketLogUtil.writeBlankRows();
   }

   public static boolean isPullMode() {
      return getParameterValue("dataSynchronousMode").equalsIgnoreCase("pull");
   }

   public static void loadProperties() {
      InputStream root = null;
      BufferedReader rootBF = null;
      InputStream fr = null;
      BufferedReader bf = null;

      try {
         root = EncryptionGatewayManager.class.getResourceAsStream("/gatewayconfig/config.properties");
         rootBF = new BufferedReader(new InputStreamReader(root));

         String rootStr;
         while((rootStr = rootBF.readLine()) != null) {
            if (!rootStr.startsWith("#") && StringUtils.isNotEmpty(rootStr) && rootStr.split("=").length == 2) {
               ROOT_CONFIG_PROPERTIES.put(rootStr.split("=")[0].trim(), rootStr.split("=")[1].trim());
            }
         }

         try {
            if (ROOT_CONFIG_PROPERTIES.get("encryption.config.location") != null && !"".equals(ROOT_CONFIG_PROPERTIES.get("encryption.config.location"))) {
               fr = new FileInputStream((String)ROOT_CONFIG_PROPERTIES.get("encryption.config.location"));
               if (fr != null) {
                  bf = new BufferedReader(new InputStreamReader(fr));
               }
            }

            String str;
            while((str = bf.readLine()) != null) {
               if (!str.startsWith("#") && StringUtils.isNotEmpty(str) && str.split("=").length == 2) {
                  CONFIG_PROPERTIES.put(str.split("=")[0].trim(), str.split("=")[1].trim());
               }
            }
         } catch (IOException var22) {
            logger.info("没有设置外部配置文件，未能读取到外部配置文件信息");
         } finally {
            if (rootBF != null) {
               rootBF.close();
            }

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

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

            if (fr != null) {
               fr.close();
            }
         } catch (IOException e) {
            e.printStackTrace();
         }

      }

   }

   public static boolean noticeMyStatus(final String status) {
      String projectId = getParameterValue("projectid");
      String remotePort = "";

      try {
         int portInt = ROOT_PORT;
         remotePort = String.valueOf(ROOT_PORT);
      } catch (Exception e) {
         e.printStackTrace();
      } catch (Throwable e) {
         e.printStackTrace();
      }

      GatewaySocketLogUtil.writeLog("通知加密网关更改同步状态为" + status + "，参数为：projectId=" + projectId + ",remotePort=" + remotePort + ",status=" + status);
      String url = getParameterValue("gatewayurl") + "/jar_socket_controller/noticePullStatus" + "?projectId=" + projectId + "&remotePort=" + remotePort + "&status=" + status;
      String result = ClientUtil.doPost(url, JSON.toJSONString(new HashMap()), new GatewaySocketCallback() {
         public void isSucc(String data) {
            if ("2".equals(status)) {
               GatewaySocketLogUtil.writeLog("加密网关成功收到拉取数据的请求");
            } else if ("3".equals(status)) {
               GatewaySocketLogUtil.writeLog("加密网关成功收到数据拉取完成的通知!通知内容为" + data);
            }

         }

         public void isFail() {
         }

         public void clean() {
            GatewaySocketLogUtil.writeLog("当前应用ip在白名单外，加密网关要求清空配置");
            CacheFromEncryptionGateway.appUserGlobalOriginalConfig = 0;
            CacheFromEncryptionGateway.gatewayUserOriginalInfos = new ArrayList();
            CacheFromEncryptionGateway.appUserOriginalInfos = new ArrayList();
            CacheFromEncryptionGateway.gatewayUserGlobalOriginalConfig = 0;
            EngineUtil.encryptonBeanList.clear();
            EngineUtil.encryptionMap.clear();
         }
      });
      return !"noRefresh".equalsIgnoreCase(result);
   }

   public static boolean checkParameterFlag(String param) {
      String logFlag = (String)CONFIG_PROPERTIES.get(param);
      if (logFlag != null && !"".equals(logFlag) && !"0".equals(logFlag)) {
         return true;
      } else {
         logFlag = (String)ROOT_CONFIG_PROPERTIES.get(param);
         return logFlag != null && !"".equals(logFlag) && !"0".equals(logFlag);
      }
   }

   public static String getParameterValue(String param) {
      if (CONFIG_PROPERTIES.isEmpty() && ROOT_CONFIG_PROPERTIES.isEmpty()) {
         loadProperties();
      }

      String value = (String)CONFIG_PROPERTIES.get(param);
      if (value != null && !"".equals(value)) {
         return value;
      } else {
         value = (String)ROOT_CONFIG_PROPERTIES.get(param);
         return value != null && !"".equals(value) ? value : "";
      }
   }

   public static void logDatabaseUrl(String databaseUrl) {
      if (!sendUrl) {
         String projectId = getParameterValue("projectid");
         String remotePort = "";
         remotePort = String.valueOf(ROOT_PORT);
         if (StringUtils.isNotEmpty(getParameterValue("rootport"))) {
            remotePort = getParameterValue("rootport");
         }

         try {
            GatewaySocketLogUtil.writeLog("记录用户的数据库连接url，参数为：projectId=" + projectId + ",remotePort=" + remotePort);
            String url = getParameterValue("gatewayurl") + "/jar_socket_controller/noticePullStatus" + "?projectId=" + projectId + "&remotePort=" + remotePort + "&status=2";
            Map<String, Object> param = new HashMap();
            param.put("databaseUrl", databaseUrl);
            ClientUtil.doPost(url, JSON.toJSONString(param));
         } catch (Exception var6) {
            GatewaySocketLogUtil.writeLog("执行" + (new Exception()).getStackTrace()[0].getMethodName() + "方法异常！");
         }

         sendUrl = true;
      }
   }

   public static void logClientError(String errorMsg) {
      long now = System.currentTimeMillis();
      if (lastTime == 0L || now - lastTime <= 10000L) {
         String projectId = getParameterValue("projectid");
         String remotePort = "";
         remotePort = String.valueOf(ROOT_PORT);
         if (StringUtils.isNotEmpty(getParameterValue("rootport"))) {
            remotePort = getParameterValue("rootport");
         }

         try {
            GatewaySocketLogUtil.writeLog("记录用户的数据库连接url，参数为：projectId=" + projectId + ",remotePort=" + remotePort);
            String url = getParameterValue("gatewayurl") + "/jar_socket_controller/noticePullStatus" + "?projectId=" + projectId + "&remotePort=" + remotePort + "&status=2";
            Map<String, Object> param = new HashMap();
            param.put("clientError", errorMsg);
            ClientUtil.doPost(url, JSON.toJSONString(param));
            lastTime = System.currentTimeMillis();
         } catch (Exception var8) {
            GatewaySocketLogUtil.writeLog("执行" + (new Exception()).getStackTrace()[0].getMethodName() + "方法异常！");
         }

         sendUrl = true;
      }
   }

   public static void main(String[] args) {
      String str = "encryption.drivers=";
      String[] split = str.split("=");

      for(String var10000 : split) {
         System.out.println(split.length);
      }

   }

   public static class InnerThread extends Thread {
      public void run() {
         try {
            while(true) {
               if (!StringUtils.isNotEmpty(EncryptionGatewayManager.getParameterValue("rootport"))) {
                  Thread.sleep(100L);
               } else {
                  EncryptionGatewayManager.ROOT_PORT = Integer.parseInt(EncryptionGatewayManager.getParameterValue("rootport"));
                  EncryptionGatewayManager.pullTask();
                  if (EncryptionGatewayManager.isPullMode()) {
                     EncryptionGatewayManager.scheduledTask();
                  } else {
                     NettyStartApplicationRunner.run();
                  }
                  break;
               }
            }
         } catch (Exception e) {
            e.printStackTrace();
         }

      }
   }
}
