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

import ch.qos.logback.classic.Logger;
import com.chenyang.nse.bussiness.config.PropertiesLoaderUtils;
import com.chenyang.nse.bussiness.dao.table.core.encryption.TCoreJiaMiJieMiJinDuDao;
import com.chenyang.nse.bussiness.entity.db.PrimaryKeyInfo;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDatasystem;
import com.chenyang.nse.bussiness.entity.orm.table.core.encryption.ColumnPrimaryKeyInfo;
import com.chenyang.nse.bussiness.entity.orm.table.core.encryption.TCoreJiaMiJieMiJinDu;
import com.chenyang.nse.bussiness.entity.vo.strategy.ColumnInfoVO;
import com.chenyang.nse.bussiness.enumeration.EdbType;
import com.chenyang.nse.bussiness.service.core.encryption.TCoreEncryptionService;
import com.chenyang.nse.bussiness.service.core.encryption.impl.TCoreEncryptionContext;
import com.chenyang.nse.bussiness.service.core.strategy.MaksingAppDataRuleService;
import com.chenyang.nse.bussiness.tools.encryption.EncProvider;
import com.chenyang.nse.bussiness.tools.encryption.EncUtils;
import com.chenyang.nse.bussiness.tools.jdbc.JdbcTool;
import com.chenyang.nse.bussiness.tools.logger.LoggerBuilder;
import com.chenyang.nse.bussiness.tools.propertyutil.PropertyGhcaUtil;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;

public class RemoveLoadingBatchTask implements Runnable {
   private String copySuffix = "";
   private String cipherSuffix = "";
   protected static final String COMPLETE = "6";
   protected static final String RUNNING = "-2";
   protected static final String FAIL = "44";
   private int jiamiTasktotalCounts = 0;
   private int jiamiTaskFinishCounts = 0;
   private int failCount = 0;
   private boolean isKeepReadData = true;
   private int startRow = 0;
   private int maxPackageCount = 100000;
   private String dataSystemId;
   private String projectId;
   private JdbcTemplate jdbcTemplate;
   private String tableName;
   private String columnName;
   private String columnType;
   private String columnSize;
   private Connection connection;
   private TCoreDatasystem tCoreDatasystem;
   private String schema;
   private String[] primaryKeys;
   private List<ColumnInfoVO> columnInfoList;
   private List<com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO> allColumnList;
   List<ColumnPrimaryKeyInfo> columnPrimaryKeyInfoList;
   HashSet<ColumnEncryption> columnSet = null;
   Properties props = new Properties();
   CountDownLatch countDownLatch;
   EncTaskStateContainer container;

   public RemoveLoadingBatchTask(String projectId, String dataSystemId, TCoreDatasystem tCoreDatasystem, String schema, String tableName, String[] primaryKeys, List<ColumnInfoVO> columnInfoList, CountDownLatch countDownLatch, List<ColumnPrimaryKeyInfo> columnPrimaryKeyInfoList, List<com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO> allColumnList) {
      this.copySuffix = PropertyGhcaUtil.copySuffix;
      this.cipherSuffix = PropertyGhcaUtil.cipherSuffix;
      this.projectId = projectId;
      this.dataSystemId = dataSystemId;
      this.tCoreDatasystem = tCoreDatasystem;
      this.schema = schema;
      this.tableName = tableName;
      this.columnInfoList = columnInfoList;
      this.primaryKeys = primaryKeys;
      this.connection = JdbcTool.getConnection(tCoreDatasystem);
      this.columnPrimaryKeyInfoList = columnPrimaryKeyInfoList;
      this.countDownLatch = countDownLatch;
      this.allColumnList = allColumnList;

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

      this.jdbcTemplate = (JdbcTemplate)ApplicationContextProvider.getBean(JdbcTemplate.class);
      this.container = EncTaskTracker.instance().container();
      this.container.add(projectId, schema, tableName, columnInfoList);
      EncTaskTracker.instance().register(this.container);
   }

   public void run() {
      try {
         this.runTask();
      } finally {
         EncTaskTracker.instance().over(this.container.getTask());
      }

   }

   public void runTask() {
      this.countDownLatch.countDown();
      List<ColumnInfoVO> rollbackCols = new ArrayList();
      String loggerPath = System.getProperty("user.dir") + File.separator + "encryprocesslog" + File.separator + this.projectId + File.separator + this.dataSystemId;
      Logger encryptionlogger = (new LoggerBuilder()).getLogger(loggerPath, this.schema + "." + this.tableName);
      Thread.currentThread().setName("pool-" + this.tableName + "-thread");
      new Properties();

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

      encryptionlogger.info("执行批量解密任务开始start>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
      encryptionlogger.info("执行批量解密任务开始start↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓");
      encryptionlogger.info("启动执行线程！！");
      TCoreJiaMiJieMiJinDuDao tCoreJiaMiJieMiJinDuDao = (TCoreJiaMiJieMiJinDuDao)ApplicationContextProvider.getBean(TCoreJiaMiJieMiJinDuDao.class);
      TCoreEncryptionService tCoreEncryptionService = (TCoreEncryptionService)ApplicationContextProvider.getBean(TCoreEncryptionContext.class);
      MaksingAppDataRuleService maksingAppDataRuleService = (MaksingAppDataRuleService)ApplicationContextProvider.getBean(MaksingAppDataRuleService.class);
      new HashMap();
      Boolean doresult = true;
      String selectSQL = "";
      String updateSQL = "";
      StringBuilder selectStrBuilder = new StringBuilder();
      StringBuilder updateStrBuilder = new StringBuilder();
      Boolean isOracle = true;
      if (!this.tCoreDatasystem.getDbtype().equals(EdbType.ORACLE.toString())) {
         isOracle = false;
      }

      Boolean isPostgres = true;
      if (!this.tCoreDatasystem.getDbtype().equals(EdbType.POSTGRESQL.toString())) {
         isPostgres = false;
      }

      Boolean isGreenplum = true;
      if (!this.tCoreDatasystem.getDbtype().equals(EdbType.GREENPLUM.toString())) {
         isGreenplum = false;
      }

      Boolean isMssqlserver = true;
      if (!this.tCoreDatasystem.getDbtype().equals(EdbType.MSSQLSERVER.toString())) {
         isMssqlserver = false;
      }

      Boolean isDM = true;
      if (!this.tCoreDatasystem.getDbtype().equals(EdbType.DM.toString())) {
         isDM = false;
      }

      Boolean isKingbase = true;
      if (!this.tCoreDatasystem.getDbtype().equals(EdbType.KINGBASE.toString())) {
         isKingbase = false;
      }

      Boolean isDB2 = true;
      if (!this.tCoreDatasystem.getDbtype().equals(EdbType.DB2.toString())) {
         isDB2 = false;
      }

      Boolean isGBASE8S = true;
      if (!this.tCoreDatasystem.getDbtype().equals(EdbType.GBASE8S.toString())) {
         isGBASE8S = false;
      }

      Boolean isOCEANBASE = true;
      if (!this.tCoreDatasystem.getDbtype().equals(EdbType.OCEANBASE.toString())) {
         isOCEANBASE = false;
      }

      Boolean isMysql = true;
      if (!this.tCoreDatasystem.getDbtype().equals(EdbType.MYSQL.toString())) {
         isMysql = false;
      }

      Boolean isHivetdh = true;
      if (!this.tCoreDatasystem.getDbtype().equals(EdbType.HIVE_TDH.toString())) {
         isHivetdh = false;
      }

      if (this.primaryKeys.length > 0) {
         for(int i = 0; i < this.primaryKeys.length; ++i) {
            if (isOracle) {
               selectStrBuilder.append("\"" + this.primaryKeys[i] + "\"");
            } else if (isPostgres) {
               selectStrBuilder.append("\"" + this.primaryKeys[i] + "\"");
            } else if (isMssqlserver) {
               selectStrBuilder.append(this.primaryKeys[i]);
            } else if (isDM) {
               selectStrBuilder.append("\"" + this.primaryKeys[i] + "\"");
            } else {
               selectStrBuilder.append(this.primaryKeys[i]);
            }

            if (i != this.primaryKeys.length - 1) {
               selectStrBuilder.append(",");
            }
         }
      }

      if (this.tCoreDatasystem.getDbtype().equals(EdbType.DM.toString())) {
         String substring = selectStrBuilder.toString();
         String[] arr = substring.split(",");
         List list = new ArrayList();

         for(int i = 0; i < arr.length; ++i) {
            String s = arr[i].trim();
            if (!list.contains(s)) {
               list.add(s);
            }
         }

         substring = StringUtils.strip(list.toString(), "[]");
         selectStrBuilder.setLength(0);
         selectStrBuilder.append(substring);
      }

      int count = 0;
      String updateSql1 = "";
      if (this.primaryKeys.length > 0) {
         updateSql1 = updateSql1 + " WHERE ";

         for(int i = 0; i < this.primaryKeys.length; ++i) {
            if (isOracle) {
               updateSql1 = updateSql1 + "\"" + this.primaryKeys[i] + "\"=? ";
            } else if (isPostgres) {
               updateSql1 = updateSql1 + "\"" + this.primaryKeys[i] + "\"=? ";
            } else if (isGreenplum) {
               updateSql1 = updateSql1 + "\"" + this.primaryKeys[i] + "\"=? ";
            } else if (isMssqlserver) {
               updateSql1 = updateSql1 + this.primaryKeys[i] + "=? ";
            } else if (isHivetdh) {
               updateSql1 = updateSql1 + this.primaryKeys[i] + "=? ";
            } else if (isDM) {
               updateSql1 = updateSql1 + "\"" + this.primaryKeys[i] + "\"=? ";
            } else {
               updateSql1 = updateSql1 + this.primaryKeys[i] + "=? ";
            }

            ++count;
            if (count < this.primaryKeys.length) {
               updateSql1 = updateSql1 + " AND ";
            }
         }
      }

      StringBuilder addColumnString = new StringBuilder();
      StringBuilder addColumnStrings = new StringBuilder();
      List<StringBuilder> addCopy = new ArrayList();
      Set<String> columnMap = JdbcTool.getColumnMap(this.connection, this.schema, this.tableName);
      StringBuilder stringBuilderpsk = new StringBuilder();
      stringBuilderpsk.append(" order by ");
      if (this.primaryKeys.length > 0) {
         for(int i = 0; i < this.primaryKeys.length; ++i) {
            if (this.tCoreDatasystem.getDbtype().equals(EdbType.ORACLE.toString())) {
               stringBuilderpsk.append("\"" + this.primaryKeys[i] + "\"").append(",");
            } else if (!this.tCoreDatasystem.getDbtype().equals(EdbType.POSTGRESQL.toString()) && !this.tCoreDatasystem.getDbtype().equals(EdbType.GAUSS.toString())) {
               if (this.tCoreDatasystem.getDbtype().equals(EdbType.GREENPLUM.toString())) {
                  stringBuilderpsk.append("\"" + this.primaryKeys[i] + "\"").append(",");
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.MSSQLSERVER.toString())) {
                  stringBuilderpsk.append(this.primaryKeys[i]).append(",");
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.HIVE.toString())) {
                  stringBuilderpsk.append(this.primaryKeys[i]).append(",");
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.HIVE_TDH.toString())) {
                  stringBuilderpsk.append(this.primaryKeys[i]).append(",");
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.DM.toString())) {
                  stringBuilderpsk.append("\"" + this.primaryKeys[i] + "\"").append(",");
               } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.KINGBASE.toString())) {
                  stringBuilderpsk.append("\"" + this.primaryKeys[i] + "\"").append(",");
               } else {
                  stringBuilderpsk.append(this.primaryKeys[i]).append(",");
               }
            } else {
               stringBuilderpsk.append("\"" + this.primaryKeys[i] + "\"").append(",");
            }
         }
      }

      stringBuilderpsk.deleteCharAt(stringBuilderpsk.length() - 1);
      String pks = stringBuilderpsk.toString() + " ";

      for(int i = 0; i < this.columnInfoList.size(); ++i) {
         this.columnName = ((ColumnInfoVO)this.columnInfoList.get(i)).getColumnName();
         this.columnType = ((ColumnInfoVO)this.columnInfoList.get(i)).getColumnType();
         this.columnSize = ((ColumnInfoVO)this.columnInfoList.get(i)).getColumnSize();
         tCoreEncryptionService.updateFlag(this.projectId, this.dataSystemId, this.schema, this.tableName, this.columnName, "-2");
         String columNamecopy = this.columnName + this.copySuffix;
         if (isOracle) {
            columNamecopy = "\"" + columNamecopy + "\"";
         }

         if (isPostgres) {
            columNamecopy = "\"" + columNamecopy + "\"";
         }

         String copyColumn = this.columnName + this.copySuffix;
         if (!columnMap.contains(copyColumn) && !columnMap.contains(columNamecopy)) {
            String columnSizestr = "";
            if ("VARCHAR2".equalsIgnoreCase(this.columnType) || "varchar".equalsIgnoreCase(this.columnType) || "char".equalsIgnoreCase(this.columnType)) {
               columnSizestr = "(" + this.columnSize + ")";
            }

            if (isOracle) {
               addColumnStrings.append(columNamecopy).append(",");
               addColumnString.append(" add ").append(columNamecopy).append(" ").append(this.columnType).append(columnSizestr);
            } else if (isPostgres) {
               addColumnStrings.append(columNamecopy).append(",");
               addColumnString.append(" add ").append(columNamecopy).append(" ").append(this.columnType).append(columnSizestr);
            } else if (!this.tCoreDatasystem.getDbtype().equals(EdbType.GAUSS.toString()) && !this.tCoreDatasystem.getDbtype().equals(EdbType.KINGBASE.toString()) && !this.tCoreDatasystem.getDbtype().equals(EdbType.GREENPLUM.toString())) {
               if (isMssqlserver) {
                  addColumnStrings.append(columNamecopy).append(",");
                  addColumnString.append(" add ").append(columNamecopy).append(" ").append(this.columnType).append(columnSizestr);
               } else if (isHivetdh) {
                  addColumnStrings.append(columNamecopy).append(",");
                  addColumnString.append(" add ").append(columNamecopy).append(" ").append(this.columnType).append(columnSizestr);
               } else if (isDM) {
                  addColumnStrings.append(columNamecopy).append(",");
                  addColumnString.append(" add ").append(columNamecopy).append(" ").append(this.columnType).append(columnSizestr);
               } else {
                  addColumnStrings.append(columNamecopy).append(",");
                  addColumnString.append(" add ").append(columNamecopy).append(" ").append(this.columnType).append(columnSizestr);
               }
            } else {
               columnSizestr = columnSizestr.indexOf("2147483647") > -1 ? "" : columnSizestr;
               addColumnStrings.append(columNamecopy).append(",");
               addColumnString.append(" add ").append(columNamecopy).append(" ").append(this.columnType).append(columnSizestr);
            }
         }

         addCopy.add(addColumnString);
         addColumnString = new StringBuilder("");
         updateStrBuilder.append(columNamecopy).append("=?,");
      }

      List<TCoreJiaMiJieMiJinDu> tCoreJiaList = tCoreJiaMiJieMiJinDuDao.queryTCoreJiaMiJieMiJinD(this.dataSystemId, this.projectId, this.schema, this.tableName);
      if (null == tCoreJiaList && tCoreJiaList.size() == 0) {
         TCoreJiaMiJieMiJinDu tCoreJiaMiJieMiJinDu = new TCoreJiaMiJieMiJinDu();
         tCoreJiaMiJieMiJinDu.setProjectid(this.projectId);
         tCoreJiaMiJieMiJinDu.setDatasystemid(this.dataSystemId);
         tCoreJiaMiJieMiJinDu.setSchemahh(this.schema);
         tCoreJiaMiJieMiJinDu.setTablename(this.tableName);
         tCoreJiaMiJieMiJinDu.setFlag("1");
         tCoreJiaMiJieMiJinDuDao.save(tCoreJiaMiJieMiJinDu);
      }

      TCoreJiaMiJieMiJinDu tCoreJiaMiJieMiJin = new TCoreJiaMiJieMiJinDu();
      List<TCoreJiaMiJieMiJinDu> tCoreJiaMiJieMiJinList = tCoreJiaMiJieMiJinDuDao.queryTCoreJiaMiJieMiJinD(this.dataSystemId, this.projectId, this.schema, this.tableName);
      if (null != tCoreJiaMiJieMiJinList && tCoreJiaMiJieMiJinList.size() > 0) {
         for(int npp = 0; npp < tCoreJiaMiJieMiJinList.size(); ++npp) {
            tCoreJiaMiJieMiJin = (TCoreJiaMiJieMiJinDu)tCoreJiaMiJieMiJinList.get(npp);
         }
      }

      if (null != tCoreJiaMiJieMiJin) {
         tCoreJiaMiJieMiJin.setTotalcounts(this.jiamiTasktotalCounts);
         tCoreJiaMiJieMiJin.setStarttime(new Date());
         tCoreJiaMiJieMiJin.setFlag("1");
         tCoreJiaMiJieMiJinDuDao.update(tCoreJiaMiJieMiJin);
      }

      Statement commStmt = null;
      ResultSet rs = null;
      ResultSet rsCount = null;
      PreparedStatement pstmt = null;
      PreparedStatement updataCopyPstmt = null;
      Connection selcon = null;
      int bacthMaxCount = 100000;
      int curBacthCount = 0;

      try {
         this.connection.setAutoCommit(false);
         Statement stmtCount = null;

         try {
            stmtCount = this.connection.createStatement();
            String selectCountTable = "";
            if (isOracle) {
               selectCountTable = "select count(1) as \"table_rows\" from \"" + this.schema + "\".\"" + this.tableName + "\"";
            } else if (isPostgres) {
               selectCountTable = "select count(1) as \"table_rows\" from \"" + this.schema + "\".\"" + this.tableName + "\"";
            } else if (isGreenplum) {
               selectCountTable = "select count(1) as \"table_rows\" from \"" + this.schema + "\".\"" + this.tableName + "\"";
            } else if (isMssqlserver) {
               selectCountTable = "select count(1) as table_rows from " + this.schema + "." + this.tableName;
            } else if (isHivetdh) {
               selectCountTable = "select count(1) as table_rows from " + this.schema + "." + this.tableName;
            } else if (isDM) {
               selectCountTable = "select count(1) as \"table_rows\" from \"" + this.schema + "\".\"" + this.tableName + "\"";
            } else {
               selectCountTable = "select count(1) as table_rows from " + this.schema + "." + this.tableName;
            }

            for(rsCount = stmtCount.executeQuery(selectCountTable); rsCount.next(); this.jiamiTasktotalCounts = rsCount.getInt("table_rows")) {
            }

            if (null != tCoreJiaMiJieMiJin) {
               tCoreJiaMiJieMiJin.setTotalcounts(this.jiamiTasktotalCounts);
               tCoreJiaMiJieMiJin.setStarttime(new Date());
               tCoreJiaMiJieMiJin.setFlag("1w");
               tCoreJiaMiJieMiJinDuDao.update(tCoreJiaMiJieMiJin);
            }
         } catch (Exception e) {
            e.printStackTrace();
         } finally {
            if (rsCount != null) {
               try {
                  stmtCount.close();
               } catch (SQLException e) {
                  e.printStackTrace();
               }
            }

            if (stmtCount != null) {
               try {
                  stmtCount.close();
               } catch (SQLException e) {
                  e.printStackTrace();
               }
            }

            stmtCount.close();
         }

         for(int i = 0; i < this.columnInfoList.size(); ++i) {
            ColumnInfoVO colInfo = (ColumnInfoVO)this.columnInfoList.get(i);

            try {
               this.isKeepReadData = true;
               this.startRow = 0;
               this.columnName = ((ColumnInfoVO)this.columnInfoList.get(i)).getColumnName();
               boolean isupk = false;
               if (this.columnPrimaryKeyInfoList != null && this.columnPrimaryKeyInfoList.size() > 0 && "1".equals(((ColumnPrimaryKeyInfo)this.columnPrimaryKeyInfoList.get(0)).getFlag())) {
                  List pklist = Arrays.asList(this.primaryKeys);
                  if (pklist.contains(this.columnName)) {
                     isupk = true;
                  }
               }

               try {
                  if (isOracle) {
                     addTableField(this.connection, "\"" + this.schema + "\"", "\"" + this.tableName + "\"", addColumnStrings, (StringBuilder)addCopy.get(i), encryptionlogger, this.tCoreDatasystem, isupk, (ColumnInfoVO)this.columnInfoList.get(i));
                  } else if (isPostgres) {
                     addTableField(this.connection, "\"" + this.schema + "\"", "\"" + this.tableName + "\"", addColumnStrings, (StringBuilder)addCopy.get(i), encryptionlogger, this.tCoreDatasystem, isupk, (ColumnInfoVO)this.columnInfoList.get(i));
                  } else if (isGreenplum) {
                     addTableField(this.connection, "\"" + this.schema + "\"", "\"" + this.tableName + "\"", addColumnStrings, (StringBuilder)addCopy.get(i), encryptionlogger, this.tCoreDatasystem, isupk, (ColumnInfoVO)this.columnInfoList.get(i));
                  } else if (isMssqlserver) {
                     addTableField(this.connection, this.schema, this.tableName, addColumnStrings, (StringBuilder)addCopy.get(i), encryptionlogger, this.tCoreDatasystem, isupk, (ColumnInfoVO)this.columnInfoList.get(i));
                  } else if (isHivetdh) {
                     addTableField(this.connection, this.schema, this.tableName, addColumnStrings, (StringBuilder)addCopy.get(i), encryptionlogger, this.tCoreDatasystem, isupk, (ColumnInfoVO)this.columnInfoList.get(i));
                  } else if (isDM) {
                     addTableField(this.connection, "\"" + this.schema + "\"", "\"" + this.tableName + "\"", addColumnStrings, (StringBuilder)addCopy.get(i), encryptionlogger, this.tCoreDatasystem, isupk, (ColumnInfoVO)this.columnInfoList.get(i));
                  } else {
                     addTableField(this.connection, this.schema, this.tableName, addColumnStrings, (StringBuilder)addCopy.get(i), encryptionlogger, this.tCoreDatasystem, isupk, (ColumnInfoVO)this.columnInfoList.get(i));
                  }
               } catch (SQLException e) {
                  this.updateFieldFlag(((ColumnInfoVO)this.columnInfoList.get(i)).getTcoreencryptionfieldId(), "44");
                  encryptionlogger.error(e.getMessage());
                  continue;
               }

               Boolean bh = false;
               Map<String, String> mt = new HashMap();
               encryptionlogger.info("正常信息:获取表字段信息");

               try {
                  commStmt = this.connection.createStatement();
                  rs = JdbcTool.getColumns(this.connection, this.schema, this.tableName);
                  ResultSetMetaData rsMetadata = rs.getMetaData();
                  int countMT = rsMetadata.getColumnCount();

                  for(int i1 = 1; i1 < countMT + 1; ++i1) {
                     String columnNameCol = rsMetadata.getColumnLabel(i1);
                     String columnTypeCol = rsMetadata.getColumnTypeName(i1);
                     if (!mt.containsKey(columnNameCol)) {
                        mt.put(columnNameCol, columnTypeCol);
                     }
                  }

                  if (this.tCoreDatasystem.getDbtype().equals(EdbType.POSTGRESQL.toString())) {
                     bh = true;
                  }

                  if (isOracle) {
                     updateSQL = "UPDATE \"" + this.schema + "\".\"" + this.tableName + "\" SET \"" + this.columnName + this.copySuffix + "\" =? " + updateSql1;
                  } else if (isPostgres) {
                     updateSQL = "UPDATE \"" + this.schema + "\".\"" + this.tableName + "\" SET \"" + this.columnName + this.copySuffix + "\" =? " + updateSql1;
                  } else if (isGreenplum) {
                     updateSQL = "UPDATE \"" + this.schema + "\".\"" + this.tableName + "\" SET \"" + this.columnName + this.copySuffix + "\" =? " + updateSql1;
                  } else if (isMssqlserver) {
                     updateSQL = "UPDATE " + this.schema + "." + this.tableName + " SET " + this.columnName + this.copySuffix + " =? " + updateSql1;
                  } else if (isHivetdh) {
                     updateSQL = "UPDATE " + this.schema + "." + this.tableName + " SET " + this.columnName + this.copySuffix + " =? " + updateSql1;
                  } else if (isDM) {
                     updateSQL = "UPDATE \"" + this.schema + "\".\"" + this.tableName + "\" SET \"" + this.columnName + this.copySuffix + "\" =? " + updateSql1;
                  } else {
                     updateSQL = "UPDATE " + this.schema + "." + this.tableName + " SET " + this.columnName + this.copySuffix + " =? " + updateSql1;
                  }

                  updataCopyPstmt = this.connection.prepareStatement(updateSQL);
                  if (isOracle) {
                     selectSQL = "SELECT " + selectStrBuilder.toString() + ", \"" + this.columnName + "\" FROM \"" + this.schema + "\".\"" + this.tableName + "\"" + pks;
                  } else if (isPostgres) {
                     selectSQL = "SELECT " + selectStrBuilder.toString() + ", \"" + this.columnName + "\" FROM \"" + this.schema + "\".\"" + this.tableName + "\"" + pks;
                  } else if (isGreenplum) {
                     selectSQL = "SELECT " + selectStrBuilder.toString() + ", \"" + this.columnName + "\" FROM \"" + this.schema + "\".\"" + this.tableName + "\"" + pks;
                  } else if (isMssqlserver) {
                     selectSQL = "SELECT " + selectStrBuilder.toString() + ", " + this.columnName + " FROM " + this.schema + "." + this.tableName + pks;
                  } else if (isHivetdh) {
                     selectSQL = "SELECT " + selectStrBuilder.toString() + ", " + this.columnName + " FROM " + this.schema + "." + this.tableName + pks;
                  } else if (isDM) {
                     String substring = selectStrBuilder.toString() + ",\"" + this.columnName + "\"";
                     String[] arr1 = substring.split(",");
                     List list = new ArrayList();

                     for(int n = 0; n < arr1.length; ++n) {
                        String s = arr1[n].trim();
                        if (!list.contains(s)) {
                           list.add(s);
                        }
                     }

                     substring = StringUtils.strip(list.toString(), "[]");
                     selectSQL = "SELECT " + substring + " FROM \"" + this.schema + "\".\"" + this.tableName + "\"" + pks;
                  } else {
                     selectSQL = "SELECT " + selectStrBuilder.toString() + ", " + this.columnName + " FROM " + this.schema + "." + this.tableName + pks;
                  }
               } catch (Exception exp) {
                  encryptionlogger.info("异常信息：" + exp.getMessage());
                  continue;
               }

               encryptionlogger.info("正常信息：开始查询解密数据");

               while(this.isKeepReadData) {
                  ResultSet rs1 = null;
                  PreparedStatement tableDataStatement = null;
                  String sql1 = "";
                  if (!isOracle && !isPostgres && !isDM) {
                     sql1 = selectStrBuilder.toString() + ", " + ((ColumnInfoVO)this.columnInfoList.get(i)).getColumnName();
                  } else {
                     sql1 = selectStrBuilder.toString() + ", \"" + ((ColumnInfoVO)this.columnInfoList.get(i)).getColumnName() + "\" ";
                  }

                  String sql2 = selectSQL;

                  try {
                     String sqlPaging = null;
                     if (isDB2) {
                        sqlPaging = "SELECT " + sql1 + " FROM ( select row_number() over() as RN ,TT.* FROM  (" + sql2 + " ) TT ) where RN>" + this.startRow + " AND RN <= " + (this.startRow + this.maxPackageCount);
                     } else if (!isOracle && !isDM) {
                        if (!isPostgres && !this.tCoreDatasystem.getDbtype().equals(EdbType.GAUSS.toString())) {
                           if (EdbType.GREENPLUM.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype())) {
                              sqlPaging = sql2 + " limit " + this.maxPackageCount + " OFFSET " + this.startRow;
                           } else if (!EdbType.MYSQL.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype()) && !EdbType.KINGBASE.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype()) && !EdbType.GAUSS.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype()) && !EdbType.HIVE.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype()) && !EdbType.MARIADB.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype()) && !EdbType.HIVE_TDH.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype())) {
                              if (EdbType.MSSQLSERVER.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype())) {
                                 sqlPaging = sql2 + " ORDER BY " + sql1 + " OFFSET " + this.startRow + " ROWS FETCH NEXT " + this.maxPackageCount + " ROWS ONLY";
                              }
                           } else {
                              sqlPaging = sql2 + " limit " + this.startRow + "," + this.maxPackageCount;
                           }
                        } else {
                           sqlPaging = sql2 + " offset " + this.startRow + " limit " + this.maxPackageCount;
                        }
                     } else if (isDM) {
                        String[] arr1 = sql1.split(",");
                        List list = new ArrayList();

                        for(int n = 0; n < arr1.length; ++n) {
                           String s = arr1[n].trim();
                           if (!list.contains(s)) {
                              list.add(s);
                           }
                        }

                        sql1 = StringUtils.strip(list.toString(), "[]");
                        sqlPaging = "SELECT " + sql1 + " FROM ( select ROWNUM RN ,TT.* FROM  (" + sql2 + " ) TT ) where RN>" + this.startRow + " AND RN <= " + (this.startRow + this.maxPackageCount);
                     } else {
                        sqlPaging = "SELECT " + sql1 + " FROM ( select ROWNUM RN ,TT.* FROM  (" + sql2 + " ) TT ) where RN>" + this.startRow + " AND RN <= " + (this.startRow + this.maxPackageCount);
                     }

                     this.startRow += this.maxPackageCount;
                     System.out.println("-------- 读取数据SQL：" + sqlPaging);
                     if (isMssqlserver) {
                        tableDataStatement = this.connection.prepareStatement(sqlPaging, 1004, 1007);
                     } else {
                        tableDataStatement = this.connection.prepareStatement(sqlPaging, 1004, 1008);
                     }

                     tableDataStatement.setFetchSize(10000);
                     rs1 = tableDataStatement.executeQuery();
                     if (!this.isCanKeepRead(rs1)) {
                        this.isKeepReadData = false;
                        break;
                     }

                     if ("HIVE".equals(this.tCoreDatasystem.getDbtype()) || "HIVE_TDH".equals(this.tCoreDatasystem.getDbtype())) {
                        if (!rs1.next()) {
                           break;
                        }

                        try {
                           String secretkeyId = ((ColumnInfoVO)this.columnInfoList.get(i)).getSecretKeyId();
                           String encryptionType = ((ColumnInfoVO)this.columnInfoList.get(i)).getEncryptionType();
                           String secretKey = ((ColumnInfoVO)this.columnInfoList.get(i)).getSecretKey();
                           String isLike = ((ColumnInfoVO)this.columnInfoList.get(i)).getIsLike();
                           String value = rs1.getString(((ColumnInfoVO)this.columnInfoList.get(i)).getColumnName());
                           String keepfirst = ((ColumnInfoVO)this.columnInfoList.get(i)).getKeepfirst();
                           String encdigit = ((ColumnInfoVO)this.columnInfoList.get(i)).getEncdigit();
                           String twoindex = ((ColumnInfoVO)this.columnInfoList.get(i)).getTwoindex();
                           value = this.doDecryptionMethod(encryptionType, secretKey, value, isLike, keepfirst, encdigit, twoindex);
                           updataCopyPstmt.setString(1, value);

                           for(int j = 0; j < this.primaryKeys.length; ++j) {
                              if (bh) {
                                 String cname = this.primaryKeys[j];
                                 com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO columnInfoVO = (com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO)this.allColumnList.stream().filter((c) -> c.getColumnname().equals(cname)).findFirst().get();
                                 if (!columnInfoVO.getTypename().toLowerCase(Locale.ROOT).contains("int") && !columnInfoVO.getTypename().toLowerCase(Locale.ROOT).equals("serial") && !columnInfoVO.getTypename().toLowerCase(Locale.ROOT).equals("imos_id") && !columnInfoVO.getTypename().toLowerCase(Locale.ROOT).equals("bigserial")) {
                                    updataCopyPstmt.setString(j + 2, rs1.getString(this.primaryKeys[j]));
                                 } else {
                                    updataCopyPstmt.setLong(j + 2, (long)Integer.parseInt(rs1.getString(this.primaryKeys[j])));
                                 }
                              } else {
                                 updataCopyPstmt.setString(j + 2, rs1.getString(this.primaryKeys[j]));
                              }
                           }

                           updataCopyPstmt.addBatch();
                           ++this.jiamiTaskFinishCounts;
                           ++curBacthCount;
                        } catch (Exception q) {
                           encryptionlogger.info("异常信息" + q.getMessage());
                           curBacthCount = 0;
                           continue;
                        }

                        if (curBacthCount == bacthMaxCount) {
                           try {
                              updataCopyPstmt.executeBatch();
                              this.connection.commit();
                           } catch (Exception t) {
                              encryptionlogger.error(t.getMessage());
                              encryptionlogger.warn("提交到" + this.jiamiTaskFinishCounts + "行，执行异常!");
                              encryptionlogger.warn("{}行解密数据提交失败!", curBacthCount);
                              if (null != tCoreJiaMiJieMiJin) {
                                 tCoreJiaMiJieMiJin.setExceptionstring(t.toString());
                                 tCoreJiaMiJieMiJinDuDao.update(tCoreJiaMiJieMiJin);
                              }

                              doresult = false;
                              TCoreJiaMiJieMiJinDu tCoreJiaMiJie = new TCoreJiaMiJieMiJinDu();
                              List<TCoreJiaMiJieMiJinDu> tCoreJiaMiJieList = tCoreJiaMiJieMiJinDuDao.queryTCoreJiaMiJieMiJinD(this.dataSystemId, this.projectId, this.schema, this.tableName);
                              int cpplll = tCoreJiaMiJieList.size();
                              if (cpplll > 0) {
                                 for(int npplll = 0; npplll < cpplll; ++npplll) {
                                    tCoreJiaMiJie = (TCoreJiaMiJieMiJinDu)tCoreJiaMiJieList.get(npplll);
                                 }
                              }

                              tCoreJiaMiJie.setState("-1");
                              this.jiamiTaskFinishCounts -= curBacthCount;
                              tCoreJiaMiJieMiJin.setFinishcounts(this.jiamiTaskFinishCounts);
                              tCoreJiaMiJieMiJinDuDao.update(tCoreJiaMiJie);
                              curBacthCount = 0;
                              this.isKeepReadData = false;
                              break;
                           }

                           curBacthCount = 0;
                           if (null != tCoreJiaMiJieMiJin && doresult) {
                              tCoreJiaMiJieMiJin.setFinishcounts(this.jiamiTaskFinishCounts);
                              tCoreJiaMiJieMiJin.setState("0");
                              tCoreJiaMiJieMiJinDuDao.update(tCoreJiaMiJieMiJin);
                           }

                           encryptionlogger.info("字段" + this.columnName + "解密完成行数为：" + this.jiamiTaskFinishCounts);
                        }
                     }

                     while(rs1.next()) {
                        try {
                           String secretkeyId = ((ColumnInfoVO)this.columnInfoList.get(i)).getSecretKeyId();
                           String encryptionType = ((ColumnInfoVO)this.columnInfoList.get(i)).getEncryptionType();
                           String secretKey = ((ColumnInfoVO)this.columnInfoList.get(i)).getSecretKey();
                           String isLike = ((ColumnInfoVO)this.columnInfoList.get(i)).getIsLike();
                           String value = rs1.getString(((ColumnInfoVO)this.columnInfoList.get(i)).getColumnName());
                           String keepfirst = ((ColumnInfoVO)this.columnInfoList.get(i)).getKeepfirst();
                           String encdigit = ((ColumnInfoVO)this.columnInfoList.get(i)).getEncdigit();
                           String twoindex = ((ColumnInfoVO)this.columnInfoList.get(i)).getTwoindex();
                           value = this.doDecryptionMethod(encryptionType, secretKey, value, isLike, keepfirst, encdigit, twoindex);
                           updataCopyPstmt.setString(1, value);

                           for(int j = 0; j < this.primaryKeys.length; ++j) {
                              if (bh) {
                                 String cname = this.primaryKeys[j];
                                 com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO columnInfoVO = (com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO)this.allColumnList.stream().filter((c) -> c.getColumnname().equals(cname)).findFirst().get();
                                 if (!columnInfoVO.getTypename().toLowerCase(Locale.ROOT).contains("int") && !columnInfoVO.getTypename().toLowerCase(Locale.ROOT).equals("serial") && !columnInfoVO.getTypename().toLowerCase(Locale.ROOT).equals("imos_id") && !columnInfoVO.getTypename().toLowerCase(Locale.ROOT).equals("bigserial")) {
                                    updataCopyPstmt.setString(j + 2, rs1.getString(this.primaryKeys[j]));
                                 } else {
                                    updataCopyPstmt.setLong(j + 2, (long)Integer.parseInt(rs1.getString(this.primaryKeys[j])));
                                 }
                              } else {
                                 updataCopyPstmt.setString(j + 2, rs1.getString(this.primaryKeys[j]));
                              }
                           }

                           updataCopyPstmt.addBatch();
                           ++this.jiamiTaskFinishCounts;
                           ++curBacthCount;
                        } catch (Exception q) {
                           encryptionlogger.info("异常信息" + q.getMessage());
                           curBacthCount = 0;
                           continue;
                        }

                        if (curBacthCount == bacthMaxCount) {
                           try {
                              updataCopyPstmt.executeBatch();
                              this.connection.commit();
                           } catch (Exception t) {
                              encryptionlogger.error(t.getMessage());
                              encryptionlogger.warn("提交到" + this.jiamiTaskFinishCounts + "行，执行异常!");
                              encryptionlogger.warn("{}行解密数据提交失败!", curBacthCount);
                              if (null != tCoreJiaMiJieMiJin) {
                                 tCoreJiaMiJieMiJin.setExceptionstring(t.toString());
                                 tCoreJiaMiJieMiJinDuDao.update(tCoreJiaMiJieMiJin);
                              }

                              doresult = false;
                              TCoreJiaMiJieMiJinDu tCoreJiaMiJie = new TCoreJiaMiJieMiJinDu();
                              List<TCoreJiaMiJieMiJinDu> tCoreJiaMiJieList = tCoreJiaMiJieMiJinDuDao.queryTCoreJiaMiJieMiJinD(this.dataSystemId, this.projectId, this.schema, this.tableName);
                              int cpplll = tCoreJiaMiJieList.size();
                              if (cpplll > 0) {
                                 for(int npplll = 0; npplll < cpplll; ++npplll) {
                                    tCoreJiaMiJie = (TCoreJiaMiJieMiJinDu)tCoreJiaMiJieList.get(npplll);
                                 }
                              }

                              tCoreJiaMiJie.setState("-1");
                              this.jiamiTaskFinishCounts -= curBacthCount;
                              tCoreJiaMiJieMiJin.setFinishcounts(this.jiamiTaskFinishCounts);
                              tCoreJiaMiJieMiJinDuDao.update(tCoreJiaMiJie);
                              curBacthCount = 0;
                              this.isKeepReadData = false;
                              break;
                           }

                           curBacthCount = 0;
                           if (null != tCoreJiaMiJieMiJin && doresult) {
                              tCoreJiaMiJieMiJin.setFinishcounts(this.jiamiTaskFinishCounts);
                              tCoreJiaMiJieMiJin.setState("0");
                              tCoreJiaMiJieMiJinDuDao.update(tCoreJiaMiJieMiJin);
                           }

                           encryptionlogger.info("字段" + this.columnName + "解密完成行数为：" + this.jiamiTaskFinishCounts);
                        }
                     }
                  } catch (Exception q) {
                     encryptionlogger.info("异常信息" + q.getMessage());
                     this.isKeepReadData = false;
                     break;
                  } finally {
                     if (rs1 != null) {
                        try {
                           rs1.close();
                        } catch (SQLException e) {
                           e.printStackTrace();
                        }
                     }

                     if (tableDataStatement != null) {
                        try {
                           tableDataStatement.close();
                        } catch (SQLException e) {
                           e.printStackTrace();
                        }
                     }

                  }
               }

               if (curBacthCount > 0) {
                  try {
                     updataCopyPstmt.executeBatch();
                     this.connection.commit();
                  } catch (Exception e) {
                     encryptionlogger.error(e.getMessage());
                     encryptionlogger.warn("提交到" + this.jiamiTaskFinishCounts + "行，执行异常!");
                     encryptionlogger.warn("{}行解密数据提交失败!", curBacthCount);
                     if (null != tCoreJiaMiJieMiJin) {
                        tCoreJiaMiJieMiJin.setExceptionstring(e.toString());
                        tCoreJiaMiJieMiJinDuDao.update(tCoreJiaMiJieMiJin);
                     }

                     doresult = false;
                     TCoreJiaMiJieMiJinDu tCoreJiaMiJie = new TCoreJiaMiJieMiJinDu();
                     List<TCoreJiaMiJieMiJinDu> tCoreJiaMiJieList = tCoreJiaMiJieMiJinDuDao.queryTCoreJiaMiJieMiJinD(this.dataSystemId, this.projectId, this.schema, this.tableName);
                     int cpplll = tCoreJiaMiJieList.size();
                     if (cpplll > 0) {
                        for(int npplll = 0; npplll < cpplll; ++npplll) {
                           tCoreJiaMiJie = (TCoreJiaMiJieMiJinDu)tCoreJiaMiJieList.get(npplll);
                        }
                     }

                     tCoreJiaMiJie.setState("-1");
                     tCoreJiaMiJieMiJin.setFinishcounts(this.jiamiTaskFinishCounts - curBacthCount);
                     this.failCount += curBacthCount;
                     tCoreJiaMiJieMiJin.setFailcounts(this.failCount);
                     tCoreJiaMiJieMiJinDuDao.update(tCoreJiaMiJie);
                     continue;
                  }
               } else {
                  this.connection.commit();
               }

               String flag = doresult ? "6" : "44";
               encryptionlogger.info("字段" + this.columnName + "解密完成！");
               encryptionlogger.info("字段" + this.columnName + "解密完成总行数：" + this.jiamiTaskFinishCounts);
               if (null != tCoreJiaMiJieMiJin && doresult) {
                  tCoreJiaMiJieMiJin.setFinishcounts(this.jiamiTaskFinishCounts);
                  tCoreJiaMiJieMiJin.setState("1");
                  tCoreJiaMiJieMiJin.setEndtime(new Date());
                  tCoreJiaMiJieMiJinDuDao.update(tCoreJiaMiJieMiJin);
               }

               tCoreEncryptionService.updateFlag(this.projectId, this.dataSystemId, this.schema, this.tableName, this.columnName, flag);
               String check = this.checkDecryption(this.tCoreDatasystem, (ColumnInfoVO)this.columnInfoList.get(i), encryptionlogger);
               if (!"ok".equals(check)) {
                  encryptionlogger.error("字段" + this.columnName + "解密校验失败");
                  this.updateFieldFlag(((ColumnInfoVO)this.columnInfoList.get(i)).getTcoreencryptionfieldId(), "11");
               } else {
                  encryptionlogger.info("字段" + this.columnName + "解密校验成功");
                  tCoreEncryptionService.updateFlag(this.projectId, this.dataSystemId, this.schema, this.tableName, this.columnName, flag);
                  if (null != tCoreJiaMiJieMiJin && doresult) {
                     tCoreJiaMiJieMiJin.setFinishcounts(this.jiamiTaskFinishCounts);
                     tCoreJiaMiJieMiJin.setState("1");
                     tCoreJiaMiJieMiJin.setEndtime(new Date());
                     tCoreJiaMiJieMiJinDuDao.update(tCoreJiaMiJieMiJin);
                  }

                  encryptionlogger.info("字段" + this.columnName + "解密替换开始");
                  String primaryKeyFlag = "0";
                  String primary_key_columns = "";
                  String primary_key_col = "";
                  List<com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO> allColumns = maksingAppDataRuleService.queryColumnInfo(this.dataSystemId, this.schema, this.tableName);

                  for(com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO allColumn : allColumns) {
                     if (allColumn.getPrimarykey().equals("1")) {
                        primary_key_columns = primary_key_columns + allColumn.getColumnname() + ",";
                        primary_key_col = "\"" + primary_key_columns + allColumn.getColumnname() + "\",";
                     }
                  }

                  if (!"".equals(primary_key_col) && primary_key_col.charAt(primary_key_col.length() - 1) == ',') {
                     primary_key_col = primary_key_col.substring(0, primary_key_col.length() - 1);
                  }

                  if (!"".equals(primary_key_columns)) {
                     if (primary_key_columns.charAt(primary_key_columns.length() - 1) == ',') {
                        primary_key_columns = primary_key_columns.substring(0, primary_key_columns.length() - 1);
                     }

                     String[] fileds = primary_key_columns.split(",");
                     if (fileds.length > 0) {
                        for(String filed11 : fileds) {
                           if (((ColumnInfoVO)this.columnInfoList.get(i)).getColumnName().equals(filed11)) {
                              primaryKeyFlag = "1";
                           }
                        }
                     }
                  }

                  encryptionlogger.info("字段" + this.columnName + " 获取Cipher字段长度");
                  String columnSizeCipherStr = "";
                  Connection conn = null;

                  try {
                     conn = JdbcTool.getConnection(this.tCoreDatasystem);
                     String tableName = this.tableName;
                     String columnName = ((ColumnInfoVO)this.columnInfoList.get(i)).getColumnName();
                     String columnType = ((ColumnInfoVO)this.columnInfoList.get(i)).getColumnType();
                     String columnSize = "";
                     String alterColumnToCipherSql = "";

                     try {
                        try {
                           columnSize = colInfo.getColumnSize();
                           columnSizeCipherStr = "(" + EncUtils.strColumnSize(this.tCoreDatasystem.getDbtype(), columnType, columnSize, ((ColumnInfoVO)this.columnInfoList.get(i)).getIsLike(), primaryKeyFlag, ((ColumnInfoVO)this.columnInfoList.get(i)).getEncryptionType()) + ")";
                           encryptionlogger.info("字段" + columnName + " 修改字段名为:" + columnName + this.cipherSuffix);
                           if (isOracle) {
                              alterColumnToCipherSql = "ALTER TABLE \"" + this.schema + "\".\"" + tableName + "\"  RENAME COLUMN \"" + columnName + "\" TO \"" + columnName + this.cipherSuffix + "\"";
                           } else if (!isPostgres && !this.tCoreDatasystem.getDbtype().equals(EdbType.GAUSS.toString()) && !isGreenplum) {
                              if (isMssqlserver) {
                                 alterColumnToCipherSql = "EXEC sp_rename '[" + this.schema + "].[" + tableName + "].[" + columnName + "]', '" + columnName + this.cipherSuffix + "', 'COLUMN'";
                              } else if (isHivetdh) {
                                 alterColumnToCipherSql = "ALTER TABLE " + this.schema + "." + tableName + "  change " + columnName + " " + columnName + this.cipherSuffix + " " + columnType + columnSizeCipherStr;
                              } else if (isDM) {
                                 alterColumnToCipherSql = "ALTER TABLE \"" + this.schema + "\".\"" + tableName + "\"  alter column \"" + columnName + "\" rename to \"" + columnName + this.cipherSuffix + "\"";
                              } else if (isMysql) {
                                 alterColumnToCipherSql = this.alterColumnToCipherSqlProject(this.schema, tableName, columnName, columnType, columnSizeCipherStr, this.cipherSuffix, isupk);
                              } else if (isKingbase) {
                                 alterColumnToCipherSql = "ALTER TABLE \"" + this.schema + "\".\"" + tableName + "\"  RENAME COLUMN \"" + columnName + "\" TO \"" + columnName + this.cipherSuffix + "\"";
                              } else {
                                 alterColumnToCipherSql = this.alterColumnToCipherSqlProject(this.schema, tableName, columnName, columnType, columnSizeCipherStr, this.cipherSuffix, isupk);
                              }
                           } else {
                              alterColumnToCipherSql = "ALTER TABLE \"" + this.schema + "\".\"" + tableName + "\"  RENAME COLUMN \"" + columnName + "\" TO \"" + columnName + this.cipherSuffix + "\"";
                           }

                           commStmt.executeUpdate(alterColumnToCipherSql);
                           if (EdbType.GAUSS.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype()) || isKingbase || isMssqlserver || isGreenplum || isPostgres) {
                              this.connection.commit();
                           }
                        } catch (Exception e) {
                           encryptionlogger.info("字段" + columnName + "解密替换失败:字段" + columnName + " 修改字段名为:" + columnName + this.cipherSuffix + " 失败");
                           encryptionlogger.error(e.getMessage());
                           encryptionlogger.error("异常信息" + e.getMessage());
                           encryptionlogger.info("字段" + columnName + "解密替换失败： 失败， sql语句：" + alterColumnToCipherSql);
                           this.updateFieldFlag(((ColumnInfoVO)this.columnInfoList.get(i)).getTcoreencryptionfieldId(), "9");
                           this.jiamiTaskFinishCounts = 0;
                           e.printStackTrace();
                           continue;
                        }

                        if (primaryKeyFlag.equals("1") && !"".equals(primary_key_columns)) {
                           String primaryKeysqlIndex = "";
                           String primaryKeysql = "";
                           String primaryKeysql1 = "";
                           if (isOracle) {
                              primaryKeysql = "ALTER TABLE \"" + this.schema + "\".\"" + tableName + "\"  drop primary key";
                           } else if (!isPostgres && !isGreenplum) {
                              if (isMssqlserver) {
                                 List<PrimaryKeyInfo> primarykeyInfo = PrimaryKeyInfo.getPrimaryKeyInfoByConnection(conn, this.schema, tableName);
                                 StringBuilder primaryKeysqlBuilder = new StringBuilder();
                                 if (null != primarykeyInfo && primarykeyInfo.size() > 0) {
                                    for(int i3 = 0; i3 < primarykeyInfo.size(); ++i3) {
                                       primaryKeysql = "ALTER TABLE " + this.schema + "." + tableName + " DROP  Constraint " + ((PrimaryKeyInfo)primarykeyInfo.get(i3)).getPkname() + " ";
                                       primaryKeysqlBuilder.append(primaryKeysql);
                                    }

                                    primaryKeysql = primaryKeysqlBuilder.toString();
                                 }
                              } else if (isDM) {
                                 List<PrimaryKeyInfo> primarykeyInfo = PrimaryKeyInfo.getPrimaryKeyInfoByConnection(conn, this.schema, tableName);
                                 if (null != primarykeyInfo && primarykeyInfo.size() > 0) {
                                    for(int i4 = 0; i4 < primarykeyInfo.size(); ++i4) {
                                       primaryKeysqlIndex = "create CLUSTER index \"" + this.schema + "_" + tableName + "_" + columnName + "_index\" on \"" + this.schema + "\".\"" + tableName + "\"(\"" + columnName + this.copySuffix + "\") ";
                                       primaryKeysql = "ALTER TABLE \"" + this.schema + "\".\"" + tableName + "\" DROP  Constraint \"" + ((PrimaryKeyInfo)primarykeyInfo.get(i4)).getPkname() + "\"";
                                       primaryKeysql1 = "drop index \"" + this.schema + "\".\"" + this.schema + "_" + tableName + "_" + columnName + "_index\"";
                                       PreparedStatement preStatementKeyIndex = conn.prepareStatement(primaryKeysqlIndex);
                                       preStatementKeyIndex.executeUpdate();
                                       preStatementKeyIndex.close();

                                       try {
                                          PreparedStatement preStatementKey = conn.prepareStatement(primaryKeysql);
                                          preStatementKey.executeUpdate();
                                          preStatementKey.close();
                                       } catch (Exception var447) {
                                       }

                                       PreparedStatement preStatementKey1 = conn.prepareStatement(primaryKeysql1);
                                       preStatementKey1.executeUpdate();
                                       preStatementKey1.close();
                                    }
                                 }
                              } else if (!isKingbase) {
                                 primaryKeysql = "alter table " + this.schema + "." + tableName + "  drop primary key";
                              } else {
                                 List<PrimaryKeyInfo> primarykeyInfo = PrimaryKeyInfo.getPrimaryKeyInfoByConnection(conn, this.schema, tableName);
                                 StringBuilder primaryKeysqlBuilder = new StringBuilder();
                                 if (null != primarykeyInfo && primarykeyInfo.size() > 0) {
                                    for(int i5 = 0; i5 < primarykeyInfo.size(); ++i5) {
                                       primaryKeysql = "ALTER TABLE \"" + this.schema + "\".\"" + tableName + "\" DROP CONSTRAINT \"" + ((PrimaryKeyInfo)primarykeyInfo.get(i5)).getPkname() + "\" ";
                                       primaryKeysqlBuilder.append(primaryKeysql);
                                    }

                                    primaryKeysql = primaryKeysqlBuilder.toString();
                                 }
                              }
                           } else {
                              primaryKeysql = "ALTER TABLE \"" + this.schema + "\".\"" + tableName + "\"  DROP CONSTRAINT \"" + tableName + "_pkey\"";
                           }

                           if (isDM) {
                              try {
                                 PreparedStatement preStatementKey = conn.prepareStatement(primaryKeysql);
                                 preStatementKey.executeUpdate();
                                 preStatementKey.close();
                              } catch (Exception var446) {
                              }
                           } else {
                              PreparedStatement preStatementKey = conn.prepareStatement(primaryKeysql);
                              preStatementKey.executeUpdate();
                              preStatementKey.close();
                           }
                        }

                        String copyColumnSize = "";
                        String alterCopyToColumnSql = "";

                        try {
                           if (isMysql) {
                              copyColumnSize = "(" + columnSize + ")";
                              if (null != columnType && columnType.toLowerCase().contains("text")) {
                                 copyColumnSize = "";
                              }
                           }

                           if (isOracle) {
                              alterCopyToColumnSql = "ALTER TABLE \"" + this.schema + "\".\"" + tableName + "\"  RENAME COLUMN \"" + columnName + this.copySuffix + "\" TO \"" + columnName + "\"";
                           } else if (!isPostgres && !this.tCoreDatasystem.getDbtype().equals(EdbType.GAUSS.toString()) && !isGreenplum) {
                              if (isMssqlserver) {
                                 alterCopyToColumnSql = "EXEC sp_rename '[" + this.schema + "].[" + tableName + "].[" + columnName + this.copySuffix + "]', '" + columnName + "', 'COLUMN'";
                              } else if (isHivetdh) {
                                 alterCopyToColumnSql = "ALTER TABLE " + this.schema + "." + tableName + "  change " + columnName + this.copySuffix + " " + columnName + " " + columnType + "(" + columnSize + ")";
                              } else if (isDM) {
                                 alterCopyToColumnSql = "ALTER TABLE \"" + this.schema + "\".\"" + tableName + "\"  alter column \"" + columnName + this.copySuffix + "\" rename to \"" + columnName + "\"";
                              } else if (isKingbase) {
                                 alterCopyToColumnSql = "ALTER TABLE \"" + this.schema + "\".\"" + tableName + "\"  RENAME COLUMN \"" + columnName + this.copySuffix + "\" TO \"" + columnName + "\"";
                              } else {
                                 alterCopyToColumnSql = this.alterCopyToColumnSqlProject(this.schema, tableName, columnName, columnType, copyColumnSize, this.copySuffix, isupk);
                              }
                           } else {
                              alterCopyToColumnSql = "ALTER TABLE \"" + this.schema + "\".\"" + tableName + "\"  RENAME COLUMN \"" + columnName + this.copySuffix + "\" TO \"" + columnName + "\"";
                           }

                           commStmt.executeUpdate(alterCopyToColumnSql);
                           if (EdbType.GAUSS.toString().equalsIgnoreCase(this.tCoreDatasystem.getDbtype()) || isKingbase || isMssqlserver || isGreenplum || isPostgres) {
                              this.connection.commit();
                           }
                        } catch (Exception e) {
                           rollbackCols.add(this.columnInfoList.get(i));
                           encryptionlogger.info("字段" + columnName + "解密替换失败:字段" + columnName + this.copySuffix + " 修改字段名为:" + columnName + " 失败");
                           encryptionlogger.error(e.getMessage());
                           encryptionlogger.error("异常信息" + e.getMessage());
                           encryptionlogger.info("字段" + columnName + "解密替换失败： 失败， sql语句：" + alterCopyToColumnSql);
                           this.updateFieldFlag(((ColumnInfoVO)this.columnInfoList.get(i)).getTcoreencryptionfieldId(), "9");
                           encryptionlogger.info("正常信息：copy字段回滚开始");
                           this.updateCipherColumn((ColumnInfoVO)this.columnInfoList.get(i), this.cipherSuffix, commStmt, encryptionlogger);
                           encryptionlogger.info("正常信息：cipher字段回滚结束");
                           this.jiamiTaskFinishCounts = 0;
                           e.printStackTrace();
                           continue;
                        }

                        if (primaryKeyFlag.equals("1") && !"".equals(primary_key_columns)) {
                           String[] fileds = primary_key_columns.split(",");
                           if (fileds.length > 1) {
                              String primaryKeysql111 = "";
                              StringBuilder primaryKeysql333 = new StringBuilder();
                              if (isOracle) {
                                 if (!"".equals(primary_key_col)) {
                                    primaryKeysql111 = "alter table \"" + this.schema + "\".\"" + tableName + "\"  add primary key (" + primary_key_col + ")";
                                 }
                              } else if (!isPostgres && !isGreenplum) {
                                 if (isMssqlserver) {
                                    for(com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO allColumn : allColumns) {
                                       String substring = primary_key_columns.substring(0, primary_key_columns.length() - 1);
                                       String[] split = substring.split(",");

                                       for(String col : split) {
                                          if (col.equals(allColumn.getColumnname())) {
                                             primaryKeysql333.append("ALTER TABLE [" + this.schema + "].[" + tableName + "]  ALTER COLUMN [" + col + "] " + allColumn.getTypename() + "(" + allColumn.getColumnsize() + ") COLLATE Chinese_PRC_CI_AS NOT NULL ");
                                          }
                                       }
                                    }

                                    primaryKeysql111 = "alter table " + this.schema + "." + tableName + "  add primary key (" + primary_key_columns + ")";
                                 } else if (!isDM) {
                                    primaryKeysql111 = "alter table " + this.schema + "." + tableName + "  add primary key (" + primary_key_columns + ")";
                                 } else if (!"".equals(primary_key_columns)) {
                                    String[] arr1 = primary_key_columns.split(",");
                                    List list = new ArrayList();

                                    for(int n = 0; n < arr1.length; ++n) {
                                       String s = arr1[n].trim();
                                       if (!list.contains(s)) {
                                          list.add(s);
                                       }
                                    }

                                    primary_key_columns = StringUtils.strip(list.toString(), "[]");
                                    primaryKeysql111 = "alter table \"" + this.schema + "\".\"" + tableName + "\"  add primary key (" + primary_key_columns + ")";
                                 }
                              } else if (!"".equals(primary_key_col)) {
                                 primaryKeysql111 = "alter table \"" + this.schema + "\".\"" + tableName + "\"  add primary key (" + primary_key_col + ")";
                              }

                              if (primaryKeysql333.length() > 0) {
                                 PreparedStatement preStatementKey333 = conn.prepareStatement(primaryKeysql333.toString());
                                 preStatementKey333.executeUpdate();
                                 preStatementKey333.close();
                              }

                              PreparedStatement preStatementKey111 = conn.prepareStatement(primaryKeysql111);
                              preStatementKey111.executeUpdate();
                              preStatementKey111.close();
                           } else {
                              String primaryKeysql111 = "";
                              StringBuilder primaryKeysql333 = new StringBuilder();
                              if (isOracle) {
                                 primaryKeysql111 = "alter table \"" + this.schema + "\".\"" + tableName + "\"  add primary key (\"" + columnName + "\")";
                              } else if (!isPostgres && !isGreenplum) {
                                 if (!isMssqlserver) {
                                    if (isDM) {
                                       primaryKeysql111 = "alter table \"" + this.schema + "\".\"" + tableName + "\"  add primary key (\"" + columnName + "\")";
                                    } else {
                                       primaryKeysql111 = "alter table " + this.schema + "." + tableName + "  add primary key (" + columnName + ")";
                                    }
                                 } else {
                                    for(com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO allColumn : allColumns) {
                                       if (columnName.equals(allColumn.getColumnname())) {
                                          primaryKeysql333.append("ALTER TABLE [" + this.schema + "].[" + tableName + "]  ALTER COLUMN [" + columnName + "] " + allColumn.getTypename() + "(" + allColumn.getColumnsize() + ") COLLATE Chinese_PRC_CI_AS NOT NULL ");
                                       }
                                    }

                                    primaryKeysql111 = "alter table " + this.schema + "." + tableName + "  add primary key (" + columnName + ")";
                                 }
                              } else {
                                 primaryKeysql111 = "alter table \"" + this.schema + "\".\"" + tableName + "\"  add primary key (\"" + columnName + "\")";
                              }

                              if (null != primaryKeysql333) {
                                 PreparedStatement preStatementKey333 = conn.prepareStatement(primaryKeysql333.toString());
                                 preStatementKey333.executeUpdate();
                                 preStatementKey333.close();
                              }

                              PreparedStatement preStatementKey111 = conn.prepareStatement(primaryKeysql111);
                              preStatementKey111.executeUpdate();
                              preStatementKey111.close();
                           }
                        }

                        this.updateFieldFlag(((ColumnInfoVO)this.columnInfoList.get(i)).getTcoreencryptionfieldId(), "7");
                        this.jiamiTaskFinishCounts = 0;
                        encryptionlogger.info("字段" + columnName + "解密替换完成");
                        encryptionlogger.info("执行批量解密任务结束--------------------------");
                        encryptionlogger.info("--------------------------------------------");
                     } catch (Exception e) {
                        encryptionlogger.info("字段" + columnName + "解密替换失败");
                        encryptionlogger.error("异常信息" + e.getMessage());
                        this.updateFieldFlag(((ColumnInfoVO)this.columnInfoList.get(i)).getTcoreencryptionfieldId(), "10");
                        this.jiamiTaskFinishCounts = 0;
                        e.printStackTrace();
                     }
                  } catch (Exception e) {
                     this.jiamiTaskFinishCounts = 0;
                     throw new RuntimeException(e.getMessage(), e);
                  } finally {
                     if (conn != null) {
                        try {
                           conn.close();
                        } catch (SQLException e) {
                           e.printStackTrace();
                        }
                     }

                  }
               }
            } finally {
               this.container.over(colInfo.getColumnName());
            }
         }
      } catch (Exception e) {
         encryptionlogger.info("解密替换失败");
         encryptionlogger.error(e.getMessage());
         encryptionlogger.warn("提交到" + this.jiamiTaskFinishCounts + "行，执行异常!");
         tCoreEncryptionService.updateFlag(this.projectId, this.dataSystemId, this.schema, this.tableName, this.columnName, "6");

         try {
            this.connection.rollback();
         } catch (SQLException ex) {
            ex.printStackTrace();
         }

         TCoreJiaMiJieMiJinDu tCoreJiaMiJie = new TCoreJiaMiJieMiJinDu();
         List<TCoreJiaMiJieMiJinDu> tCoreJiaMiJieList = tCoreJiaMiJieMiJinDuDao.queryTCoreJiaMiJieMiJinD(this.dataSystemId, this.projectId, this.schema, this.tableName);
         int cpplll = tCoreJiaMiJieList.size();
         if (cpplll > 0) {
            for(int npplll = 0; npplll < cpplll; ++npplll) {
               tCoreJiaMiJie = (TCoreJiaMiJieMiJinDu)tCoreJiaMiJieList.get(npplll);
            }
         }

         tCoreJiaMiJie.setState("-1");
         this.failCount += curBacthCount;
         tCoreJiaMiJie.setFailcounts(this.failCount);
         tCoreJiaMiJieMiJinDuDao.update(tCoreJiaMiJie);
      } finally {
         if (this.connection != null) {
            try {
               this.connection.close();
            } catch (SQLException e) {
               e.printStackTrace();
            }
         }

         if (selcon != null) {
            try {
               selcon.close();
            } catch (SQLException e) {
               e.printStackTrace();
            }
         }

         if (commStmt != null) {
            try {
               commStmt.close();
            } catch (SQLException e) {
               e.printStackTrace();
            }
         }

         if (rs != null) {
            try {
               rs.close();
            } catch (SQLException e) {
               e.printStackTrace();
            }
         }

         if (rsCount != null) {
            try {
               rsCount.close();
            } catch (SQLException e) {
               e.printStackTrace();
            }
         }

         if (pstmt != null) {
            try {
               pstmt.close();
            } catch (SQLException e) {
               e.printStackTrace();
            }
         }

      }

      if (rollbackCols.size() > 0) {
         try {
            Connection rollbackConn = JdbcTool.getConnection(this.tCoreDatasystem);
            Throwable var495 = null;

            try {
               this.rollbackColumns(rollbackConn, rollbackCols, this.cipherSuffix, (List)null, (List)null, (List)null, this.tCoreDatasystem);
            } catch (Throwable var439) {
               var495 = var439;
               throw var439;
            } finally {
               if (rollbackConn != null) {
                  if (var495 != null) {
                     try {
                        rollbackConn.close();
                     } catch (Throwable var438) {
                        var495.addSuppressed(var438);
                     }
                  } else {
                     rollbackConn.close();
                  }
               }

            }
         } catch (Exception e) {
            encryptionlogger.error("替换回滚失败:" + e.getMessage());
         }
      }

   }

   private static void addTableField(Connection con, String schema, String tableName, StringBuilder addColumnStrings, StringBuilder addColumnString, Logger encryptionlogger, TCoreDatasystem tCoreDatasystem, boolean isupk, ColumnInfoVO columnInfoVO) throws SQLException {
      if (null != addColumnString && addColumnString.length() > 0) {
         if ("HIVE_TDH".equals(tCoreDatasystem.getDbtype())) {
            Set<String> columnMap = JdbcTool.getColumnMap(con, schema, tableName);
            String ccipher = columnInfoVO.getColumnName() + PropertyGhcaUtil.cipherSuffix;
            String sql = "";
            String hiveColumnSize = columnInfoVO.getColumnSize();
            hiveColumnSize = "(" + hiveColumnSize + ")";
            if (columnMap.contains(ccipher)) {
               sql = "ALTER TABLE " + schema + "." + tableName + "  change " + columnInfoVO.getColumnName() + PropertyGhcaUtil.cipherSuffix + " " + columnInfoVO.getColumnName() + PropertyGhcaUtil.copySuffix + " " + columnInfoVO.getColumnType() + hiveColumnSize;
            } else {
               sql = "alter table " + schema + "." + tableName + "  add columns(" + columnInfoVO.getColumnName() + PropertyGhcaUtil.copySuffix + " " + columnInfoVO.getColumnType() + hiveColumnSize + ")";
            }

            if (null != addColumnStrings) {
               encryptionlogger.info("新增加密列：" + addColumnStrings + "  sql语句：" + sql);
            }

            PreparedStatement preStatement = con.prepareStatement(sql);
            preStatement.executeUpdate();
            preStatement.close();
         } else {
            String sql = "alter table " + schema + "." + tableName + " " + addColumnString;
            if (isupk) {
               sql = sql + " not null";
            }

            PreparedStatement preStatement = con.prepareStatement(sql);
            preStatement.executeUpdate();
            preStatement.close();
            if (null != addColumnStrings) {
               encryptionlogger.info("新增解密列：" + addColumnStrings + "  sql语句：" + sql);
            }
         }
      }

   }

   private String doDecryptionMethod(String encryptionType, String secretKey, String value, String isLike, String keepfirst, String encdigit, String twoindex) throws Exception {
      if (null != encryptionType && !"".equals(encryptionType) && value != null) {
         value = EncProvider.decryptEcb(encryptionType, secretKey, value, isLike, keepfirst, encdigit, twoindex);
      }

      return value;
   }

   private String checkDecryption(TCoreDatasystem tCoreDatasystem, ColumnInfoVO columnInfoVO, Logger encryptionlogger) {
      encryptionlogger.info("开始校验");
      ResultSet rsCount = null;
      int checkNum = Integer.valueOf(this.props.getProperty("checkNum"));
      int sumNum = 0;
      TCoreEncryptionService tCoreEncryptionService = (TCoreEncryptionService)ApplicationContextProvider.getBean(TCoreEncryptionContext.class);

      try {
         Connection conn = JdbcTool.getConnection(tCoreDatasystem);
         Throwable var9 = null;

         try {
            Statement stmt = conn.createStatement();
            Throwable var11 = null;

            try {
               Boolean bb = true;
               if (!tCoreDatasystem.getDbtype().equals(EdbType.ORACLE.toString())) {
                  bb = false;
               }

               Boolean bbb = true;
               if (!tCoreDatasystem.getDbtype().equals(EdbType.POSTGRESQL.toString()) && !this.tCoreDatasystem.getDbtype().equals(EdbType.GAUSS.toString())) {
                  bbb = false;
               }

               Boolean isGreenplum = true;
               if (!tCoreDatasystem.getDbtype().equals(EdbType.GREENPLUM.toString())) {
                  isGreenplum = false;
               }

               Boolean SQBoolean = true;
               if (!tCoreDatasystem.getDbtype().equals(EdbType.MSSQLSERVER.toString())) {
                  SQBoolean = false;
               }

               Boolean DMBoolean = true;
               if (!tCoreDatasystem.getDbtype().equals(EdbType.DM.toString())) {
                  DMBoolean = false;
               }

               Boolean isHivetdh = true;
               if (!tCoreDatasystem.getDbtype().equals(EdbType.HIVE_TDH.toString())) {
                  isHivetdh = false;
               }

               encryptionlogger.info("正常信息：解密密非空校验开始");
               int iCLimitCount = 0;
               ResultSet rsC = null;

               String copy;
               try {
                  if (bb) {
                     rsC = stmt.executeQuery("SELECT COUNT(1) AS num FROM(SELECT * FROM ( select ROWNUM RN ,TT.* FROM  (SELECT * FROM \"" + this.schema + "\".\"" + this.tableName + "\" WHERE \"" + this.columnName + "\" IS NOT NULL AND \"" + this.columnName + this.copySuffix + "\" IS NULL) TT ) WHERE RN>" + iCLimitCount + " AND RN <= " + checkNum + ")");
                  } else if (bbb) {
                     rsC = stmt.executeQuery("SELECT count(1) AS num FROM (SELECT * FROM " + this.schema + "." + this.tableName + " WHERE " + this.columnName + " IS NOT NULL AND (" + this.columnName + this.copySuffix + " IS NULL  ) offset " + iCLimitCount + " limit " + checkNum + " )t");
                  } else if (isGreenplum) {
                     rsC = stmt.executeQuery("SELECT count(1) AS num FROM (SELECT * FROM " + this.schema + "." + this.tableName + " WHERE " + this.columnName + " IS NOT NULL AND (" + this.columnName + this.copySuffix + " IS NULL  ) limit " + iCLimitCount + " ," + checkNum + " )t");
                  } else if (isHivetdh) {
                     rsC = stmt.executeQuery("SELECT count(1) AS num FROM (SELECT * FROM " + this.schema + "." + this.tableName + " WHERE " + this.columnName + " IS NOT NULL AND (" + this.columnName + this.copySuffix + " IS NULL  ) offset " + iCLimitCount + " limit " + checkNum + " )t");
                  } else if (SQBoolean) {
                     rsC = stmt.executeQuery("SELECT COUNT(1) AS num FROM (SELECT * FROM " + this.schema + "." + this.tableName + " WHERE " + this.columnName + " IS NOT NULL AND (" + this.columnName + this.copySuffix + " IS NULL  ) limit " + iCLimitCount + "," + checkNum + " )t");
                  } else if (DMBoolean) {
                     rsC = stmt.executeQuery("SELECT COUNT(1) AS num FROM(SELECT * FROM ( select ROWNUM RN ,TT.* FROM  (SELECT * FROM \"" + this.schema + "\".\"" + this.tableName + "\" WHERE \"" + this.columnName + "\" IS NOT NULL AND \"" + this.columnName + this.copySuffix + "\" IS NULL) TT ) WHERE RN>" + iCLimitCount + " AND RN <= " + checkNum + ")");
                  } else {
                     rsC = stmt.executeQuery("SELECT count(1) AS num FROM (SELECT * FROM " + this.schema + "." + this.tableName + " WHERE " + this.columnName + " IS NOT NULL AND (" + this.columnName + this.copySuffix + " IS NULL ) limit " + iCLimitCount + "," + checkNum + " )t");
                  }

                  int num;
                  for(num = 0; rsC.next(); num = rsC.getInt("num")) {
                  }

                  if (num > 0) {
                     StringBuilder mg = new StringBuilder();
                     mg.append("数据源：");
                     mg.append(this.schema);
                     mg.append("表：");
                     mg.append(this.tableName);
                     mg.append("列：");
                     mg.append(this.columnName);
                     mg.append("解密后的数据为空，解密失败，准备回滚。");
                     encryptionlogger.info("异常信息：解密非空校验：解密后的数据为空，解密失败，准备回滚。");
                     copy = mg.toString();
                     return copy;
                  }

                  encryptionlogger.info("正常信息：解密非空校验通过");
               } catch (Exception e) {
                  e.printStackTrace();
               } finally {
                  if (rsC != null) {
                     try {
                        rsC.close();
                     } catch (SQLException e) {
                        e.printStackTrace();
                     }
                  }

               }

               encryptionlogger.info("正常信息：加密校验开始");
               int LimitCount = 0;
               ResultSet rs1 = null;

               try {
                  String columnNameN;
                  try {
                     if (bb) {
                        rs1 = stmt.executeQuery("select nn.\"" + this.columnName + "\",nn.\"" + this.columnName + this.copySuffix + "\" from (select t.\"" + this.columnName + "\",t.\"" + this.columnName + this.copySuffix + "\",rownum rn from \"" + this.schema + "\".\"" + this.tableName + "\" t) nn where nn.rn>=" + iCLimitCount + "and nn.rn<" + checkNum);
                     } else if (bbb) {
                        rs1 = stmt.executeQuery("select \"" + this.columnName + "\",\"" + this.columnName + this.copySuffix + "\" from \"" + this.schema + "\".\"" + this.tableName + "\" LIMIT " + checkNum + " OFFSET " + iCLimitCount);
                     } else if (isGreenplum) {
                        rs1 = stmt.executeQuery("select \"" + this.columnName + "\",\"" + this.columnName + this.copySuffix + "\" from \"" + this.schema + "\".\"" + this.tableName + "\" LIMIT " + checkNum + " OFFSET " + iCLimitCount);
                     } else if (SQBoolean) {
                        rs1 = stmt.executeQuery("SELECT " + this.columnName + "," + this.columnName + this.copySuffix + ", 0 AS _NAV_ORDER_F_ FROM " + this.schema + "." + this.tableName + " ORDER BY _NAV_ORDER_F_ OFFSET " + iCLimitCount + " ROWS FETCH NEXT " + checkNum + " ROWS ONLY");
                     } else if (isHivetdh) {
                        rs1 = stmt.executeQuery("select " + this.columnName + "," + this.columnName + this.copySuffix + " from " + this.schema + "." + this.tableName + " LIMIT " + iCLimitCount + " , " + checkNum);
                     } else if (DMBoolean) {
                        rs1 = stmt.executeQuery("select \"" + this.columnName + "\",\"" + this.columnName + this.copySuffix + "\" from \"" + this.schema + "\".\"" + this.tableName + "\" LIMIT " + iCLimitCount + "," + checkNum);
                     } else {
                        rs1 = stmt.executeQuery(this.checkColumn(this.schema, this.tableName, this.columnName, this.columnName + this.copySuffix, iCLimitCount, checkNum));
                     }

                     while(rs1.next()) {
                        copy = rs1.getString(this.columnName + this.copySuffix);
                        if (null != copy) {
                           columnNameN = rs1.getString(this.columnName);
                           if (!columnNameN.equals(copy)) {
                              String secretKeyId = columnInfoVO.getSecretKeyId();
                              Map<String, String> encryptionInfo = tCoreEncryptionService.queryEncryptionInfo(secretKeyId);
                              if (null != encryptionInfo.get("encryptionType") && !"".equals(encryptionInfo.get("encryptionType"))) {
                                 Boolean isEq = EncUtils.compareStringEq(columnNameN, EncProvider.encryptEcb((String)encryptionInfo.get("encryptionType"), (String)encryptionInfo.get("secretkey"), copy, columnInfoVO.getIsLike(), columnInfoVO.getKeepfirst(), columnInfoVO.getEncdigit(), columnInfoVO.getTwoindex()));
                                 if (!isEq) {
                                    StringBuilder mg111 = new StringBuilder();
                                    mg111.append("数据源：");
                                    mg111.append(this.schema);
                                    mg111.append("表：");
                                    mg111.append(this.tableName);
                                    mg111.append("列：");
                                    mg111.append(this.columnName);
                                    mg111.append("解密后的数据加密后与原数据不一致，准备回滚。");
                                    encryptionlogger.info("解密后的数据加密后与原数据不一致，准备回滚。");
                                    String var28 = mg111.toString();
                                    return var28;
                                 }
                              }
                           }
                        }
                     }

                     encryptionlogger.info("正常信息：加密校验通过");
                  } catch (Exception var125) {
                     var125.printStackTrace();
                     encryptionlogger.info("校验出错，结束校验");
                     encryptionlogger.info("错误信息：" + var125.getMessage());
                     columnNameN = "e1";
                     return columnNameN;
                  }
               } finally {
                  if (rs1 != null) {
                     try {
                        rs1.close();
                     } catch (SQLException e) {
                        e.printStackTrace();
                     }
                  }

               }
            } catch (Throwable var129) {
               var11 = var129;
               throw var129;
            } finally {
               if (stmt != null) {
                  if (var11 != null) {
                     try {
                        stmt.close();
                     } catch (Throwable var122) {
                        var11.addSuppressed(var122);
                     }
                  } else {
                     stmt.close();
                  }
               }

            }
         } catch (Throwable var131) {
            var9 = var131;
            throw var131;
         } finally {
            if (conn != null) {
               if (var9 != null) {
                  try {
                     conn.close();
                  } catch (Throwable var121) {
                     var9.addSuppressed(var121);
                  }
               } else {
                  conn.close();
               }
            }

         }
      } catch (Exception e) {
         e.printStackTrace();
         encryptionlogger.info("校验出错，结束校验");
         encryptionlogger.info("错误信息：" + e.getMessage());
         return "e2";
      }

      encryptionlogger.info("结束校验");
      return "ok";
   }

   private String checkCopy(String schema, String tableName, String columnName, String checkColumnName) {
      String sql = String.format("SELECT COUNT(1) AS num FROM %s.%s WHERE %s <> NULL AND (%s = NULL or %s = '')", schema, tableName, columnName, checkColumnName, checkColumnName);
      return sql;
   }

   private String checkColumn(String schema, String tableName, String columnName, String checkColumnName, int iCLimitCount, int limitCount) {
      String sql = String.format("SELECT %s,%s FROM %s.%s limit %s,%s", columnName, checkColumnName, schema, tableName, iCLimitCount, limitCount);
      return sql;
   }

   private String delCopyColumn(String schema, String tableName, String columnName) {
      String sql = String.format("ALTER TABLE %s.%s DROP COLUMN %s", schema, tableName, columnName);
      return sql;
   }

   private String alterColumnToCipherSqlProject(String schema, String tableName, String columnName, String columnType, String columnSize, String cipherSuffix, boolean isupk) {
      String sql = "";
      if (isupk) {
         sql = String.format("ALTER TABLE %s.%s CHANGE COLUMN %s %s %s%s not null", schema, tableName, columnName, columnName + cipherSuffix, columnType, columnSize);
      } else {
         sql = String.format("ALTER TABLE %s.%s CHANGE COLUMN %s %s %s%s", schema, tableName, columnName, columnName + cipherSuffix, columnType, columnSize);
      }

      return sql;
   }

   private String alterCipherToColumnSqlProject(String schema, String tableName, String columnName, String columnType, String columnSize, String cipherSuffix) {
      String sql = String.format("ALTER TABLE %s.%s CHANGE COLUMN %s %s %s%s", schema, tableName, columnName + cipherSuffix, columnName, columnType, columnSize);
      return sql;
   }

   private String columnSizeSql(String schema, String tableName, String columnName) {
      String sql = String.format("SELECT %s FROM %s.%s WHERE 1=2", columnName, schema, tableName);
      return sql;
   }

   private String alterCopyToColumnSqlProject(String schema, String tableName, String columnName, String columnType, String columnSize, String copySuffix, boolean isupk) {
      String sql = "";
      if (isupk) {
         sql = String.format("ALTER TABLE %s.%s CHANGE COLUMN %s %s %s%s not null", schema, tableName, columnName + copySuffix, columnName, columnType, columnSize);
      } else {
         sql = String.format("ALTER TABLE %s.%s CHANGE COLUMN %s %s %s%s", schema, tableName, columnName + copySuffix, columnName, columnType, columnSize);
      }

      return sql;
   }

   private int updateFieldFlag(String id, String flag) {
      int num = this.jdbcTemplate.update("UPDATE t_core_encryption_field SET flag = ? WHERE id = ?", new Object[]{flag, id});
      return num;
   }

   public void deleteCopyColumn(ColumnInfoVO columnInfoVo, String copySuffix, Statement stmt, Logger encryptionlogger) {
      this.updateFieldFlag(columnInfoVo.getTcoreencryptionfieldId(), "44");
      String rollback;
      if (this.tCoreDatasystem.getDbtype().equals(EdbType.ORACLE.toString())) {
         rollback = "ALTER TABLE \"" + this.schema + "\".\"" + this.tableName + "\" DROP (\"" + this.columnName + copySuffix + "\")";
      } else if (!this.tCoreDatasystem.getDbtype().equals(EdbType.POSTGRESQL.toString()) && !this.tCoreDatasystem.getDbtype().equals(EdbType.GAUSS.toString())) {
         if (this.tCoreDatasystem.getDbtype().equals(EdbType.MSSQLSERVER.toString())) {
            rollback = this.delCopyColumn(this.schema, this.tableName, this.columnName + copySuffix);
         } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.DM.toString())) {
            rollback = "ALTER TABLE \"" + this.schema + "\".\"" + this.tableName + "\" DROP COLUMN \"" + this.columnName + copySuffix + "\"";
         } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.MYSQL.toString())) {
            rollback = this.delCopyColumn(this.schema, this.tableName, this.columnName + copySuffix);
         } else {
            rollback = this.delCopyColumn(this.schema, this.tableName, this.columnName + copySuffix);
         }
      } else {
         rollback = "ALTER TABLE \"" + this.schema + "\".\"" + this.tableName + "\" DROP COLUMN \"" + this.columnName + copySuffix + "\"";
      }

      encryptionlogger.info("解密出错，删除解密列：" + columnInfoVo.getColumnName() + copySuffix);

      try {
         stmt.executeUpdate(rollback);
      } catch (SQLException var7) {
         encryptionlogger.info("删除解密列：" + columnInfoVo.getColumnName() + " 失败， sql语句：" + rollback);
      }

   }

   public void updateCipherColumn(ColumnInfoVO columnInfoVo, String cipherSuffix, Statement stmt, Logger encryptionlogger) {
      String columnSizeCipherStr = "";
      this.columnSize = EncUtils.strColumnSize(this.tCoreDatasystem.getDbtype(), this.columnType, this.columnSize, columnInfoVo.getIsLike(), "", columnInfoVo.getEncryptionType());
      columnSizeCipherStr = "(" + this.columnSize + ")";
      encryptionlogger.info("字段" + this.columnName + " 获取Cipher字段长度:" + columnSizeCipherStr);
      this.updateFieldFlag(columnInfoVo.getTcoreencryptionfieldId(), "44");
      String rollback;
      if (this.tCoreDatasystem.getDbtype().equals(EdbType.ORACLE.toString())) {
         rollback = "ALTER TABLE \"" + this.schema + "\".\"" + this.tableName + "\"  RENAME COLUMN \"" + this.columnName + cipherSuffix + "\" TO \"" + this.columnName + "\"";
      } else if (!this.tCoreDatasystem.getDbtype().equals(EdbType.POSTGRESQL.toString()) && !this.tCoreDatasystem.getDbtype().equals(EdbType.GAUSS.toString())) {
         if (this.tCoreDatasystem.getDbtype().equals(EdbType.MSSQLSERVER.toString())) {
            rollback = "EXEC sp_rename '[" + this.schema + "].[" + this.tableName + "].[" + this.columnName + cipherSuffix + "]', '" + this.columnName + "', 'COLUMN'";
         } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.DM.toString())) {
            rollback = "ALTER TABLE \"" + this.schema + "\".\"" + this.tableName + "\"  alter column \"" + this.columnName + cipherSuffix + "\" rename to \"" + this.columnName + "\"";
         } else if (this.tCoreDatasystem.getDbtype().equals(EdbType.MYSQL.toString())) {
            rollback = this.alterCipherToColumnSqlProject(this.schema, this.tableName, this.columnName, this.columnType, columnSizeCipherStr, cipherSuffix);
         } else {
            rollback = this.alterCipherToColumnSqlProject(this.schema, this.tableName, this.columnName, this.columnType, columnSizeCipherStr, cipherSuffix);
         }
      } else {
         rollback = "ALTER TABLE \"" + this.schema + "\".\"" + this.tableName + "\"  RENAME COLUMN \"" + this.columnName + cipherSuffix + "\" TO \"" + this.columnName + "\"";
      }

      encryptionlogger.info("解密替换出错，cipher列回滚：" + columnInfoVo.getColumnName());

      try {
         stmt.executeUpdate(rollback);
      } catch (SQLException throwables) {
         throwables.printStackTrace();
         encryptionlogger.info("cipher列回滚：" + columnInfoVo.getColumnName() + " 失败， sql语句：" + rollback);
         encryptionlogger.info("cipher列回滚失败错误：" + throwables.getMessage());
      }

   }

   private boolean isCanKeepRead(ResultSet rs) throws SQLException {
      try {
         boolean isCan = true;
         if (!"HIVE".equals(this.tCoreDatasystem.getDbtype()) && !"HIVE_TDH".equals(this.tCoreDatasystem.getDbtype())) {
            rs.last();
            if (rs.getRow() <= 0) {
               isCan = false;
            }

            rs.beforeFirst();
            System.out.println("isCanKeepRead方法:" + isCan);
            return isCan;
         } else {
            return true;
         }
      } catch (Exception e) {
         System.out.println("isCanKeepRead方法" + e.getMessage());
         throw new SQLException(e);
      }
   }

   private void rollbackColumns(Connection conn, List<ColumnInfoVO> allColumns, String suffix, List<String> colSizes, List<String> pkFlags, List<String> pkCols, TCoreDatasystem tCoreDatasystem) {
      if (allColumns != null && allColumns.size() != 0) {
         ColumnInfoVO proto = (ColumnInfoVO)allColumns.get(0);
         Set<String> colSet = JdbcTool.getColumnMap(conn, this.schema, this.tableName);

         for(int i = 0; i < allColumns.size(); ++i) {
            try {
               ColumnInfoVO column = (ColumnInfoVO)allColumns.get(i);
               JdbcTool.rollbackReplaceColumn(conn, colSet, this.schema, this.tableName, column.getColumnName(), column.getColumnName() + suffix, column.getColumnType(), colSizes == null ? null : (String)colSizes.get(i), pkFlags == null ? null : (String)pkFlags.get(i), pkCols == null ? null : (String)pkCols.get(i), column.getColumnName(), tCoreDatasystem);
            } catch (Exception ex) {
               ex.printStackTrace();
            }
         }

      }
   }
}
