package com.chenyang.nse.bussiness.tools.logger.dblog;

import com.alibaba.fastjson.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.graylog2.syslog4j.Syslog;
import org.graylog2.syslog4j.SyslogIF;
import org.graylog2.syslog4j.impl.net.udp.UDPNetSyslogConfig;

public class DblogClient {
   private static final String HOST = "192.168.2.218";
   private static final int PORT = 40000;
   private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

   public static void inputAuditLog(String username, String sql) {
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("datetime", sdf.format(new Date()));
      jsonObject.put("username", username);
      jsonObject.put("sql", sql);
      jsonObject.put("type", "2");
      generate(jsonObject.toString());
   }

   public static void inputMaksingLog(String username, String sql, String columnLabel, String oldValue, String newValue, String expression) {
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("datetime", sdf.format(new Date()));
      jsonObject.put("username", username);
      jsonObject.put("sql", sql);
      jsonObject.put("columnLabel", columnLabel);
      jsonObject.put("oldValue", oldValue);
      jsonObject.put("newValue", newValue);
      jsonObject.put("expression", expression);
      jsonObject.put("type", "1");
      generate(jsonObject.toString());
   }

   public static void inputMaksingLog(String jsonstr) {
      generate(jsonstr);
   }

   private static void generate(String message) {
      SyslogIF syslog = Syslog.getInstance("udp");
      UDPNetSyslogConfig udpConfig = (UDPNetSyslogConfig)syslog.getConfig();
      udpConfig.setMaxMessageLength(10240);
      syslog.getConfig().setHost("192.168.2.218");
      syslog.getConfig().setPort(40000);

      try {
         message = message.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
         message = message.replaceAll("\\+", "%2B");
         syslog.log(0, URLDecoder.decode(message, "utf-8"));
      } catch (UnsupportedEncodingException e) {
         System.out.println("generate log get exception " + e);
      }

   }

   public static void main(String[] args) {
      inputMaksingLog("{\"query\":\"SELECT * from dual\",\"responseinfo\":\"阻断\",\"exequery\":\"SELECT * from dual\",\"datetime\":\"2021-04-26 11:12:34\",\"accesstool\":\"dberror\",\"accessorip\":\"10.10.10.10\",\"accessormac\":\"jkjk:jijj-iokjfodsfd\",\"accessoruser\":\"zhangsan\",\"action\":\"1\",\"sqltype\":\"select\",\"matchrule\":\"rule1\",\"policyname\":\"策略1\",\"matchstatus\":\"1\",\"exestatus\":\"1\",\"datasourceid\":\"1\",\"type\":\"1\",\"alarmtype\":\"0\",\"alarmid\":\"32d31b0224a745d2a961c53f0491fc95\",\"auditswitch\":\"0\"}");
   }
}
