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

import com.chenyang.nse.bussiness.config.PropertiesLoaderUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.SocketAddress;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import org.graylog2.syslog4j.server.SyslogServer;
import org.graylog2.syslog4j.server.SyslogServerConfigIF;
import org.graylog2.syslog4j.server.SyslogServerEventIF;
import org.graylog2.syslog4j.server.SyslogServerIF;
import org.graylog2.syslog4j.server.SyslogServerSessionEventHandlerIF;
import org.graylog2.syslog4j.server.impl.net.udp.UDPNetSyslogServerConfig;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplogService implements ApplicationContextAware {
   protected static ApplicationContext applicationContext;
   private static Properties props = new Properties();
   private static String filepath = "";
   private static String appAlertInterface = "";
   private static String HOST = "192.168.2.212";
   private static Integer PORT = 32376;
   private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   private static FileOutputStream outputStream = null;

   private void receiveSyslogMessage() throws InterruptedException {
      SyslogServerIF server = SyslogServer.getInstance("udp");
      UDPNetSyslogServerConfig udpConfig = (UDPNetSyslogServerConfig)server.getConfig();
      udpConfig.setMaxMessageSize(10240);
      SyslogServerConfigIF config = server.getConfig();
      config.setHost(HOST);
      config.setPort(PORT);
      config.addEventHandler(new SyslogServerSessionEventHandlerIF() {
         public Object sessionOpened(SyslogServerIF syslogServerIF, SocketAddress socketAddress) {
            return null;
         }

         public void event(Object o, SyslogServerIF syslogServerIF, SocketAddress socketAddress, SyslogServerEventIF syslogServerEventIF) {
            String sendvalue = "{\"from\": \"" + socketAddress.toString().replace("/", "").split("\\:")[0] + "\",\"hostname\":\"" + syslogServerEventIF.getHost() + "\"," + syslogServerEventIF.getMessage().replace(syslogServerEventIF.getHost(), "\"message\":") + "}\n";
            File file = null;
            if (sendvalue.contains("\"type\":\"2\"")) {
               file = new File(ApplogService.filepath + File.separator + "audit" + File.separator + ApplogService.sdf.format(new Date()) + ".txt");
            } else if (sendvalue.contains("\"type\":\"1\"")) {
               if (sendvalue.contains("\"auditswitch\":\"0\"")) {
                  file = new File(ApplogService.filepath + File.separator + "masking" + File.separator + ApplogService.sdf.format(new Date()) + ".txt");
                  ApplogService.interfaceUtil(ApplogService.appAlertInterface, "");
               } else if (sendvalue.contains("\"auditswitch\":\"1\"")) {
                  file = new File(ApplogService.filepath + File.separator + "masking" + File.separator + ApplogService.sdf.format(new Date()) + ".txt");
               }
            }

            if (!file.exists()) {
               try {
                  file.getParentFile().mkdirs();
                  file.createNewFile();
               } catch (Exception e) {
                  e.printStackTrace();
               }
            }

            try {
               ApplogService.outputStream = new FileOutputStream(file, true);
               ApplogService.outputStream.write(sendvalue.getBytes());
            } catch (Exception e) {
               e.printStackTrace();
            } finally {
               try {
                  ApplogService.outputStream.close();
               } catch (IOException e) {
                  e.printStackTrace();
               }

            }

         }

         public void exception(Object o, SyslogServerIF syslogServerIF, SocketAddress socketAddress, Exception e) {
         }

         public void sessionClosed(Object o, SyslogServerIF syslogServerIF, SocketAddress socketAddress, boolean b) {
         }

         public void initialize(SyslogServerIF syslogServerIF) {
         }

         public void destroy(SyslogServerIF syslogServerIF) {
         }
      });
      SyslogServer.getThreadedInstance("udp");
   }

   public static void interfaceUtil(String path, String data) {
      try {
         URL url = new URL(path);
         HttpURLConnection conn = (HttpURLConnection)url.openConnection();
         PrintWriter out = null;
         conn.setRequestProperty("accept", "*/*");
         conn.setRequestProperty("connection", "Keep-Alive");
         conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
         conn.setDoOutput(true);
         conn.setDoInput(true);
         out = new PrintWriter(conn.getOutputStream());
         out.print(data);
         out.flush();
         InputStream is = conn.getInputStream();
         BufferedReader br = new BufferedReader(new InputStreamReader(is));
         String str = "";

         while((str = br.readLine()) != null) {
            System.out.println(str);
         }

         is.close();
         conn.disconnect();
         System.out.println("告警结束");
      } catch (Exception e) {
         e.printStackTrace();
      }

   }

   public void setApplicationContext(ApplicationContext arg0) throws BeansException {
      if (applicationContext == null) {
         applicationContext = arg0;
      }

   }

   public static void main(String[] args) throws InterruptedException {
      (new ApplogService()).receiveSyslogMessage();
   }

   public static void execute() throws InterruptedException {
      (new ApplogService()).receiveSyslogMessage();
   }

   static {
      try {
         props = PropertiesLoaderUtils.loadAllProperties("config.properties");
         filepath = props.getProperty("appserverlogpath");
         appAlertInterface = props.getProperty("app_alert_interface");
         HOST = props.getProperty("applogServerHost");
         PORT = Integer.parseInt(props.getProperty("applogServerPort"));
      } catch (IOException e) {
         e.printStackTrace();
      }

   }
}
