package com.chenyang.nse.bussiness.service.console.impl;

import cn.hutool.core.util.ObjectUtil;
import com.chenyang.nse.bussiness.config.PropertiesLoaderUtils;
import com.chenyang.nse.bussiness.dao.core.TCoreDataSourceSchemaDao;
import com.chenyang.nse.bussiness.dao.core.TCoreDataareaSecretkeyRelationDao;
import com.chenyang.nse.bussiness.dao.table.core.TCoreDatasystemDao;
import com.chenyang.nse.bussiness.dao.table.core.dataproject.TCoreDataAreaDao;
import com.chenyang.nse.bussiness.dao.table.core.encryption.ColumnPrimaryKeyInfoDao;
import com.chenyang.nse.bussiness.dao.table.core.encryption.TCoreEncryptionTypeFieldDao;
import com.chenyang.nse.bussiness.entity.db.ColumnInfo;
import com.chenyang.nse.bussiness.entity.orm.table.core.DataareaSecretkeyRelationVo;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDataareaSecretkeyRelation;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDatasystem;
import com.chenyang.nse.bussiness.entity.orm.table.core.dataproject.TCoreDataArea;
import com.chenyang.nse.bussiness.entity.orm.table.core.dataproject.TCoreDataProject;
import com.chenyang.nse.bussiness.entity.orm.table.core.encryption.ColumnPrimaryKeyInfo;
import com.chenyang.nse.bussiness.entity.orm.table.core.encryption.TCoreEncryptionTypeField;
import com.chenyang.nse.bussiness.entity.vo.Field;
import com.chenyang.nse.bussiness.entity.vo.ReturnInterfaceDate;
import com.chenyang.nse.bussiness.entity.vo.TableInfo;
import com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO;
import com.chenyang.nse.bussiness.enumeration.EdbType;
import com.chenyang.nse.bussiness.init.StaticDatasPool;
import com.chenyang.nse.bussiness.service.console.DataareaSecretkeyRelationService;
import com.chenyang.nse.bussiness.service.core.TdataProjectService;
import com.chenyang.nse.bussiness.service.core.strategy.MaksingAppDataRuleService;
import com.chenyang.nse.bussiness.service.core.udf.UdfService;
import com.chenyang.nse.bussiness.tools.io.FileTool;
import com.chenyang.nse.bussiness.tools.jdbc.JdbcTool;
import com.chenyang.nse.bussiness.tools.login.CommonUtils;
import com.chenyang.nse.bussiness.tools.propertyutil.PropertyGhcaUtil;
import com.chenyang.nse.bussiness.tools.string.AesTool;
import com.chenyang.nse.bussiness.tools.string.StringTool;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class DataareaSecretkeyRelationServiceImpl implements DataareaSecretkeyRelationService {
   @Autowired
   TCoreDataareaSecretkeyRelationDao tCoreDataareaSecretkeyRelationDao;
   @Autowired
   TCoreDataAreaDao tCoreDataAreaDao;
   @Autowired
   TCoreEncryptionTypeFieldDao tCoreEncryptionTypeFieldDao;
   @Autowired
   TCoreDatasystemDao tCoreDatasystemDao;
   @Autowired
   TCoreDataSourceSchemaDao tCoreDatasourceSchemaDao;
   @Autowired
   ColumnPrimaryKeyInfoDao columnPrimaryKeyInfoDao;
   @Autowired
   MaksingAppDataRuleService maksingAppDataRuleService;
   @Autowired
   TdataProjectService tdataProjectService;
   @Autowired
   UdfService udfService;

   public List<TCoreDataArea> queryDataAreaSecretKey(String dataarea) {
      List<TCoreDataArea> arealist = this.tCoreDataAreaDao.queryAll(Order.asc("areatype"), Order.desc("createtime"), new Criterion[]{Restrictions.like("dataarea", dataarea, MatchMode.ANYWHERE)});

      for(TCoreDataArea dataArea : arealist) {
         List<DataareaSecretkeyRelationVo> secretkeylist = this.tCoreDataareaSecretkeyRelationDao.queryAllSecretkey(dataArea.getId());
         dataArea.setSecretkeyList(secretkeylist);
      }

      return arealist;
   }

   public boolean save(TCoreDataareaSecretkeyRelation sec) {
      String relationid = sec.getId();
      String defaultttype = sec.getDefaulttype();
      if ("1".equals(defaultttype)) {
         TCoreDataareaSecretkeyRelation temp = (TCoreDataareaSecretkeyRelation)this.tCoreDataareaSecretkeyRelationDao.queryUnique(new Criterion[]{Restrictions.eq("dataarea_id", sec.getDataarea_id()), Restrictions.eq("defaulttype", "1")});
         if (temp != null && !temp.getId().equals(relationid)) {
            temp.setDefaulttype("0");
            this.tCoreDataareaSecretkeyRelationDao.saveOrUpdate(temp);
         }
      }

      if (!"".equals(relationid) && relationid != null) {
         TCoreDataareaSecretkeyRelation sec1 = (TCoreDataareaSecretkeyRelation)this.tCoreDataareaSecretkeyRelationDao.get(relationid);
         sec1.setEnc_name(sec.getEnc_name());
         sec1.setDefaulttype(sec.getDefaulttype());
         sec1.setDataarea_id(sec.getDataarea_id());
         sec1.setEncryption_id(sec.getEncryption_id());
         sec1.setSecretkey_id(sec.getSecretkey_id());
         sec1.setUpdatetime(new Date());
         sec1.setUpdateuser(CommonUtils.loginUsername());
         this.tCoreDataareaSecretkeyRelationDao.update(sec1);
      } else {
         if (!"1".equals(this.checkName(sec))) {
            return false;
         }

         sec.setId(StringTool.getTablePrimaryKey());
         sec.setCreatetime(new Date());
         sec.setCreateuser(CommonUtils.loginUsername());
         this.tCoreDataareaSecretkeyRelationDao.save(sec);
      }

      return true;
   }

   public String checkName(TCoreDataareaSecretkeyRelation rule) {
      if (!ObjectUtil.isEmpty(rule.getDataarea_id())) {
         String dataareaId = rule.getDataarea_id();

         for(TCoreDataareaSecretkeyRelation tCoreDesensitizationRule : this.tCoreDataareaSecretkeyRelationDao.queryAll(new Criterion[]{Restrictions.eq("dataarea_id", dataareaId)})) {
            if (tCoreDesensitizationRule.getEnc_name().equals(rule.getEnc_name())) {
               return "0";
            }
         }

         return "1";
      } else {
         return "0";
      }
   }

   public void delete(String relationid) {
      TCoreDataareaSecretkeyRelation relation = (TCoreDataareaSecretkeyRelation)this.tCoreDataareaSecretkeyRelationDao.get(relationid);
      String dataarea_id = relation.getDataarea_id();
      List<TCoreDataareaSecretkeyRelation> list = this.tCoreDataareaSecretkeyRelationDao.queryAll(new Criterion[]{Restrictions.eq("dataarea_id", dataarea_id)});
      if (list != null && list.size() > 0) {
         ((TCoreDataareaSecretkeyRelation)list.get(0)).setDefaulttype("1");
         this.tCoreDataareaSecretkeyRelationDao.update(list.get(0));
      }

      this.tCoreDataareaSecretkeyRelationDao.removeById(relationid);
   }

   public void setBatchEncryption(Map<String, String> params) {
      String projectid = (String)params.get("projectid");
      TCoreDataProject project = this.tdataProjectService.selectOneDataProject(projectid);
      String taskid = (String)params.get("taskid");
      String filename = (String)params.get("filename");
      if (taskid != null && !"".equals(taskid)) {
         Properties props = new Properties();

         try {
            props = PropertiesLoaderUtils.loadAllProperties("config.properties");
         } catch (IOException e) {
            e.printStackTrace();
         }

         String filepath = "";
         File file = new File(props.getProperty("TaskVersion") + projectid);
         filepath = props.getProperty("TaskVersion") + taskid + File.separator + filename;
         if (FileTool.isFileExit(filepath)) {
            InputStreamReader newRead = null;

            try {
               newRead = new InputStreamReader(new FileInputStream(filepath), "GBK");
            } catch (UnsupportedEncodingException e1) {
               e1.printStackTrace();
            } catch (FileNotFoundException e1) {
               e1.printStackTrace();
            }

            BufferedReader newBufferedReader = new BufferedReader(newRead);
            String newInformationLine = "";
            String[] str = null;
            List<Map<String, String>> relationlist = new ArrayList();

            try {
               while((newInformationLine = newBufferedReader.readLine()) != null) {
                  str = newInformationLine.split(",", -1);
                  if (!"".equals(str[3])) {
                     Map<String, String> map1 = new HashMap();
                     map1.put("dataareaid", str[3]);
                     map1.put("dataareaname", str[4]);
                     List<DataareaSecretkeyRelationVo> relationList = this.tCoreDataareaSecretkeyRelationDao.queryAllSecretkeyDefault(str[3]);
                     if (null != relationList && relationList.size() > 0) {
                        if (project.getProjectType().equals("udf")) {
                           if (!this.udfService.getClassItem(str[8]).isInited(str[8], str[0], str[1])) {
                              continue;
                           }

                           str[1] = this.udfService.getUdfTable(str[1]);
                        }

                        map1.put("relationid", ((DataareaSecretkeyRelationVo)relationList.get(0)).getId());
                        map1.put("enc_name", ((DataareaSecretkeyRelationVo)relationList.get(0)).getEnc_name());
                        map1.put("encryption_id", ((DataareaSecretkeyRelationVo)relationList.get(0)).getEncryption_id());
                        map1.put("encryption_name", ((DataareaSecretkeyRelationVo)relationList.get(0)).getEncryption_name());
                        map1.put("secretkey_id", ((DataareaSecretkeyRelationVo)relationList.get(0)).getSecretkey_id());
                        map1.put("secretkey_name", ((DataareaSecretkeyRelationVo)relationList.get(0)).getSecret_key_name());
                        map1.put("projectid", projectid);
                        map1.put("tschemas", str[0]);
                        map1.put("names", str[1]);
                        map1.put("table_field_id", str[2]);
                        map1.put("dataSystemid", str[8]);
                        relationlist.add(map1);
                     }
                  }
               }

               for(Map<String, String> map : relationlist) {
                  String datasystemid = (String)map.get("dataSystemid");
                  TCoreDatasystem tCoreDatasystem = (TCoreDatasystem)this.tCoreDatasystemDao.get(datasystemid);
                  String tableCat = (String)map.get("tschemas");
                  String tableName = (String)map.get("names");
                  String columnName = (String)map.get("table_field_id");
                  List<TCoreEncryptionTypeField> tCoreEncryptionTypeFieldList = this.tCoreEncryptionTypeFieldDao.queryAll(new Criterion[]{Restrictions.eq("projectid", projectid), Restrictions.eq("datasystem_id", datasystemid), Restrictions.eq("tschemas", tableCat), Restrictions.eq("names", tableName), Restrictions.eq("table_field_id", columnName)});
                  if (!Objects.isNull(tCoreEncryptionTypeFieldList) && tCoreEncryptionTypeFieldList.size() > 0) {
                     if (!"0".equals(((TCoreEncryptionTypeField)tCoreEncryptionTypeFieldList.get(0)).getState())) {
                        continue;
                     }

                     this.tCoreEncryptionTypeFieldDao.remove(tCoreEncryptionTypeFieldList.get(0));
                  }

                  if (!columnName.toLowerCase(Locale.ROOT).contains(PropertyGhcaUtil.copySuffix) && !columnName.toLowerCase(Locale.ROOT).contains(PropertyGhcaUtil.initialSuffix) && !columnName.toLowerCase(Locale.ROOT).contains(PropertyGhcaUtil.cipherSuffix) && !columnName.toLowerCase(Locale.ROOT).contains(PropertyGhcaUtil.digestSuffix)) {
                     TCoreEncryptionTypeField tCoreEncryptionTypeField = new TCoreEncryptionTypeField();
                     tCoreEncryptionTypeField.setId(StringTool.getTablePrimaryKey());
                     tCoreEncryptionTypeField.setEncryptiontypename((String)map.get("encryption_name"));
                     tCoreEncryptionTypeField.setCreatetime(new Date());
                     tCoreEncryptionTypeField.setCreateuser(CommonUtils.loginUsername());
                     tCoreEncryptionTypeField.setEncryption_secretkey_id((String)map.get("secretkey_id"));
                     tCoreEncryptionTypeField.setState("0");
                     tCoreEncryptionTypeField.setIslike("0");
                     tCoreEncryptionTypeField.setDatasystem_id(datasystemid);
                     tCoreEncryptionTypeField.setSecretkeyname((String)map.get("secretkey_name"));
                     tCoreEncryptionTypeField.setProjectid(projectid);
                     tCoreEncryptionTypeField.setTschemas(tableCat);
                     tCoreEncryptionTypeField.setNames(tableName);
                     tCoreEncryptionTypeField.setFlag("0");
                     tCoreEncryptionTypeField.setTable_field_id(columnName);
                     tCoreEncryptionTypeField.setCombination_id(tableName + "." + columnName);
                     tCoreEncryptionTypeField.setDatasystemname(tCoreDatasystem.getSysname());
                     if (!"MONGODB".equals(tCoreDatasystem.getDbtype()) && !"ES".equals(tCoreDatasystem.getDbtype())) {
                        List<ColumnInfoVO> list = this.maksingAppDataRuleService.queryColumnInfo(datasystemid, tableCat, tableName);
                        List<ColumnInfoVO> pklist = (List)list.stream().filter((c) -> "1".equals(c.getPrimarykey())).collect(Collectors.toList());
                        List<ColumnInfoVO> indexlist = (List)list.stream().filter((c) -> "2".equals(c.getPrimarykey())).collect(Collectors.toList());
                        if (!"HIVE".equals(tCoreDatasystem.getDbtype())) {
                           if (null == pklist || pklist.size() == 0) {
                              ColumnPrimaryKeyInfo columnPrimaryKeyInfo = (ColumnPrimaryKeyInfo)this.columnPrimaryKeyInfoDao.queryUnique(new Criterion[]{Restrictions.eq("project_id", projectid), Restrictions.eq("datasystem_id", datasystemid), Restrictions.eq("tschema", tableCat), Restrictions.eq("tname", tableName)});
                              if (null == columnPrimaryKeyInfo || StringUtils.isBlank(columnPrimaryKeyInfo.getPrimary_key_columns())) {
                                 continue;
                              }
                           }

                           if (null != pklist) {
                              List<String> pkstrings = (List)pklist.stream().map(ColumnInfo::getColumnname).collect(Collectors.toList());
                              if (pkstrings.contains(columnName)) {
                                 continue;
                              }
                           }
                        }

                        if (null != indexlist) {
                           List<String> indexstrings = (List)indexlist.stream().map(ColumnInfo::getColumnname).collect(Collectors.toList());
                           if (indexstrings.contains(columnName) && tCoreDatasystem.getDbtype().equals("GREENPLUM")) {
                              continue;
                           }
                        }

                        Optional<ColumnInfoVO> optionalColumnInfoVO = list.stream().filter((c) -> c.getColumnname().equals(columnName)).findFirst();
                        if (optionalColumnInfoVO.isPresent()) {
                           ColumnInfoVO columnInfoVO = (ColumnInfoVO)optionalColumnInfoVO.get();
                           String type = columnInfoVO.getTypename();
                           if (!"CHAR".equals(type.toUpperCase(Locale.ROOT)) && !"VARCHAR".equals(type.toUpperCase(Locale.ROOT)) && !"STRING".equals(type.toUpperCase(Locale.ROOT)) && !"NVARCHAR".equals(type.toUpperCase(Locale.ROOT)) && !"VARCHAR2".equals(type.toUpperCase(Locale.ROOT)) && !"JSON".equals(type.toUpperCase(Locale.ROOT)) && !"BLOB".equals(type.toUpperCase(Locale.ROOT))) {
                              continue;
                           }

                           tCoreEncryptionTypeField.setColumn_type(type);
                           tCoreEncryptionTypeField.setColumn_size(columnInfoVO.getColumnsize());
                           tCoreEncryptionTypeField.setRealitycolumnsize(columnInfoVO.getColumnsize());
                        }
                     } else if ("MONGODB".equals(tCoreDatasystem.getDbtype())) {
                        if (columnName.equals(PropertyGhcaUtil.mongodbpk)) {
                           continue;
                        }
                     } else if ("ES".equals(tCoreDatasystem.getDbtype())) {
                        if (columnName.equals("_id")) {
                           continue;
                        }

                        List<ColumnInfoVO> list = this.maksingAppDataRuleService.queryColumnInfo(datasystemid, tableCat, tableName);
                        Optional<ColumnInfoVO> optionalColumnInfoVO = list.stream().filter((c) -> c.getColumnname().equals(columnName)).findFirst();
                        ColumnInfoVO columnInfoVO = (ColumnInfoVO)optionalColumnInfoVO.get();
                        String type = columnInfoVO.getTypename();
                        if (!"TEXT".equals(type)) {
                           continue;
                        }
                     }

                     this.tCoreEncryptionTypeFieldDao.save(tCoreEncryptionTypeField);
                  }
               }

               return;
            } catch (IOException e) {
               e.printStackTrace();
            } finally {
               closeStream(newBufferedReader, newRead);
            }
         }
      }

   }

   public void setdefault(String relationid) {
      TCoreDataareaSecretkeyRelation relation = (TCoreDataareaSecretkeyRelation)this.tCoreDataareaSecretkeyRelationDao.get(relationid);
      List<TCoreDataareaSecretkeyRelation> list = this.tCoreDataareaSecretkeyRelationDao.queryAll(new Criterion[]{Restrictions.eq("dataarea_id", relation.getDataarea_id()), Restrictions.eq("defaulttype", "1")});
      if (list != null && list.size() > 0) {
         for(TCoreDataareaSecretkeyRelation tCoreDataareaSecretkeyRelation : list) {
            tCoreDataareaSecretkeyRelation.setDefaulttype("0");
            this.tCoreDataareaSecretkeyRelationDao.update(tCoreDataareaSecretkeyRelation);
         }
      }

      relation.setDefaulttype("1");
      this.tCoreDataareaSecretkeyRelationDao.update(relation);
   }

   public void setBatchClassifyEncryption(Map<String, String> params) {
      String projectid = (String)params.get("projectid");
      TCoreDataProject project = this.tdataProjectService.selectOneDataProject(projectid);
      String datasystemid = (String)params.get("datasystemid");
      String sensitiveLevel = (String)params.get("sensitiveLevel");
      List<String> stringList = new ArrayList();
      if (StringUtils.isNotBlank(sensitiveLevel)) {
         String[] sensitiveLevels = sensitiveLevel.split(",");
         stringList = Arrays.asList(sensitiveLevels);
      }

      TCoreDatasystem tCoreDatasystem = (TCoreDatasystem)this.tCoreDatasystemDao.get(datasystemid);
      List<ReturnInterfaceDate> columnAndClassifyAndLevelAndAreaRelationList = StaticDatasPool.columnAndClassifyAndLevelAndAreaRelationList;

      List<ReturnInterfaceDate> listNew = (List)columnAndClassifyAndLevelAndAreaRelationList.stream().filter((c) -> c.getDatabaseIp().equals(tCoreDatasystem.getDbip())).filter((c) -> c.getDatabasePort().equals(tCoreDatasystem.getDbport())).filter((c) -> c.getDatabaseType().equals(tCoreDatasystem.getDbtype())).collect(Collectors.toList());
      for(ReturnInterfaceDate interfaceDate : listNew) {
         String schemaname = interfaceDate.getSchemaName();

         for(Field field : interfaceDate.getField()) {
            String tablename = field.getTableName();

            for(TableInfo tableInfo : field.getTableInfos()) {
               if (project.getProjectType().equals("udf")) {
                  if (!this.udfService.getClassItem(datasystemid).isInited(datasystemid, schemaname, tablename)) {
                     continue;
                  }

                  tablename = this.udfService.getUdfTable(tablename);
               }

               String columnname = tableInfo.getColumnName();
               List<TCoreEncryptionTypeField> tCoreEncryptionTypeFieldList = this.tCoreEncryptionTypeFieldDao.queryAll(new Criterion[]{Restrictions.eq("projectid", projectid), Restrictions.eq("datasystem_id", datasystemid), Restrictions.eq("tschemas", schemaname), Restrictions.eq("names", tablename), Restrictions.eq("table_field_id", columnname)});
               if (!Objects.isNull(tCoreEncryptionTypeFieldList) && tCoreEncryptionTypeFieldList.size() > 0) {
                  if (!"1".equals(((TCoreEncryptionTypeField)tCoreEncryptionTypeFieldList.get(0)).getState())) {
                     continue;
                  }

                  this.tCoreEncryptionTypeFieldDao.remove(tCoreEncryptionTypeFieldList.get(0));
               }

               if (!columnname.toLowerCase(Locale.ROOT).contains(PropertyGhcaUtil.copySuffix) && !columnname.toLowerCase(Locale.ROOT).contains(PropertyGhcaUtil.initialSuffix) && !columnname.toLowerCase(Locale.ROOT).contains(PropertyGhcaUtil.cipherSuffix) && !columnname.toLowerCase(Locale.ROOT).contains(PropertyGhcaUtil.digestSuffix) && (stringList.size() <= 0 || sensitiveLevel.contains(tableInfo.getSensitiveLevel()))) {
                  String dataareaname = tableInfo.getDataAreaName();
                  TCoreDataArea dataArea = (TCoreDataArea)this.tCoreDataAreaDao.queryUnique(new Criterion[]{Restrictions.eq("dataarea", dataareaname)});
                  List<DataareaSecretkeyRelationVo> relationList = this.tCoreDataareaSecretkeyRelationDao.queryAllSecretkeyDefault(dataArea.getId());
                  if (relationList != null && relationList.size() != 0) {
                     TCoreEncryptionTypeField tCoreEncryptionTypeField = new TCoreEncryptionTypeField();
                     tCoreEncryptionTypeField.setId(StringTool.getTablePrimaryKey());
                     tCoreEncryptionTypeField.setEncryptiontypename(((DataareaSecretkeyRelationVo)relationList.get(0)).getEncryption_name());
                     tCoreEncryptionTypeField.setCreatetime(new Date());
                     tCoreEncryptionTypeField.setCreateuser(CommonUtils.loginUsername());
                     tCoreEncryptionTypeField.setEncryption_secretkey_id(((DataareaSecretkeyRelationVo)relationList.get(0)).getSecretkey_id());
                     tCoreEncryptionTypeField.setState("0");
                     tCoreEncryptionTypeField.setIslike("0");
                     tCoreEncryptionTypeField.setDatasystem_id(datasystemid);
                     tCoreEncryptionTypeField.setSecretkeyname(((DataareaSecretkeyRelationVo)relationList.get(0)).getSecret_key_name());
                     tCoreEncryptionTypeField.setProjectid(projectid);
                     tCoreEncryptionTypeField.setTschemas(schemaname);
                     tCoreEncryptionTypeField.setNames(tablename);
                     tCoreEncryptionTypeField.setFlag("0");
                     tCoreEncryptionTypeField.setTable_field_id(columnname);
                     tCoreEncryptionTypeField.setCombination_id(tablename + "." + columnname);
                     tCoreEncryptionTypeField.setDatasystemname(tCoreDatasystem.getSysname());
                     if (!"MONGODB".equals(tCoreDatasystem.getDbtype()) && !"ES".equals(tCoreDatasystem.getDbtype())) {
                        List<ColumnInfoVO> list = this.maksingAppDataRuleService.queryColumnInfo(datasystemid, schemaname, tablename);
                        List<ColumnInfoVO> pklist = (List)list.stream().filter((c) -> "1".equals(c.getPrimarykey())).collect(Collectors.toList());
                        List<ColumnInfoVO> indexlist = (List)list.stream().filter((c) -> "2".equals(c.getPrimarykey())).collect(Collectors.toList());
                        if (null == pklist || pklist.size() == 0) {
                           ColumnPrimaryKeyInfo columnPrimaryKeyInfo = (ColumnPrimaryKeyInfo)this.columnPrimaryKeyInfoDao.queryUnique(new Criterion[]{Restrictions.eq("project_id", projectid), Restrictions.eq("datasystem_id", datasystemid), Restrictions.eq("tschema", schemaname), Restrictions.eq("tname", tablename)});
                           if (null == columnPrimaryKeyInfo || StringUtils.isBlank(columnPrimaryKeyInfo.getPrimary_key_columns())) {
                              continue;
                           }
                        }

                        if (null != pklist) {
                           List<String> pkstrings = (List)pklist.stream().map(ColumnInfo::getColumnname).collect(Collectors.toList());
                           if (pkstrings.contains(columnname)) {
                              continue;
                           }
                        }

                        if (null != indexlist) {
                           List<String> indexstrings = (List)indexlist.stream().map(ColumnInfo::getColumnname).collect(Collectors.toList());
                           if (indexstrings.contains(columnname) && tCoreDatasystem.getDbtype().equals("GREENPLUM")) {
                              continue;
                           }
                        }

                        Optional<ColumnInfoVO> optionalColumnInfoVO = list.stream().filter((c) -> c.getColumnname().equals(columnname)).findFirst();
                        if (optionalColumnInfoVO.isPresent()) {
                           ColumnInfoVO columnInfoVO = (ColumnInfoVO)optionalColumnInfoVO.get();
                           String type = columnInfoVO.getTypename();
                           if (!"CHAR".equals(type.toUpperCase(Locale.ROOT)) && !"VARCHAR".equals(type.toUpperCase(Locale.ROOT)) && !"STRING".equals(type.toUpperCase(Locale.ROOT)) && !"NVARCHAR".equals(type.toUpperCase(Locale.ROOT)) && !"VARCHAR2".equals(type.toUpperCase(Locale.ROOT)) && !"JSON".equals(type.toUpperCase(Locale.ROOT)) && !"BLOB".equals(type.toUpperCase(Locale.ROOT))) {
                              continue;
                           }

                           tCoreEncryptionTypeField.setColumn_type(type);
                           tCoreEncryptionTypeField.setColumn_size(columnInfoVO.getColumnsize());
                           tCoreEncryptionTypeField.setRealitycolumnsize(columnInfoVO.getColumnsize());
                        }
                     } else if ("MONGODB".equals(tCoreDatasystem.getDbtype())) {
                        if (columnname.equals(PropertyGhcaUtil.mongodbpk)) {
                           continue;
                        }
                     } else if ("ES".equals(tCoreDatasystem.getDbtype())) {
                        if (columnname.equals("_id")) {
                           continue;
                        }

                        List<ColumnInfoVO> list = this.maksingAppDataRuleService.queryColumnInfo(datasystemid, schemaname, tablename);
                        Optional<ColumnInfoVO> optionalColumnInfoVO = list.stream().filter((c) -> c.getColumnname().equals(columnname)).findFirst();
                        ColumnInfoVO columnInfoVO = (ColumnInfoVO)optionalColumnInfoVO.get();
                        String type = columnInfoVO.getTypename();
                        if (!"TEXT".equals(type)) {
                           continue;
                        }
                     }

                     this.tCoreEncryptionTypeFieldDao.save(tCoreEncryptionTypeField);
                  }
               }
            }
         }
      }

   }

   private static void closeStream(Closeable... closeables) {
      if (closeables != null) {
         try {
            for(Closeable closeable : closeables) {
               if (closeable != null) {
                  closeable.close();
               }
            }
         } catch (Exception e) {
            e.printStackTrace();
         }
      }

   }

   public Connection getConnectionByDataSystemId(String datasystemid) {
      TCoreDatasystem datasystem = (TCoreDatasystem)this.tCoreDatasystemDao.get(datasystemid);

      try {
         String dbcode = datasystem.getDbtype();
         if (EdbType.KAFKA.getDbname().equalsIgnoreCase(dbcode)) {
            return null;
         } else {
            String ip = datasystem.getDbip();
            String port = datasystem.getDbport();
            String servername = datasystem.getDbservername();
            String server = datasystem.getServername();
            String url = "";
            switch (datasystem.getDbtype()) {
               case "INFORMIX":
                  url = EdbType.getUrlByEdbcode(dbcode, ip, port, servername, server);
                  break;
               case "TERADATA":
                  url = EdbType.getUrlByEdbcode(dbcode, ip, port, servername, server, datasystem.getPagecode());
                  break;
               default:
                  url = EdbType.getUrlByEdbcode(dbcode, ip, port, servername);
            }

            String username = datasystem.getUsername();
            String password = AesTool.decrypt(datasystem.getPassword(), "ghca");
            String driver = EdbType.getEdbTypeByDbcode(dbcode).getDbdriver();
            if ("HIVE".equals(datasystem.getDbtype()) && "on".equals(datasystem.getIskerberos())) {
               System.setProperty("java.security.krb5.conf", datasystem.getXmlpath() + "/krb5.conf");
               Connection conn = JdbcTool.getKerberosConn(url + ";principal=" + datasystem.getPrincipal(), driver, datasystem.getLoginprincipal(), datasystem.getXmlpath());
               return conn;
            } else if (dbcode.equals("RAPIDSDB")) {
               Connection conn = JdbcTool.getConnection(driver, url, username, "");
               return conn;
            } else {
               Connection conn = JdbcTool.getConnection(driver, url, username, password);
               return conn;
            }
         }
      } catch (Exception var13) {
         return null;
      }
   }
}
