package com.chenyang.nse.bussiness.jar.util;

import java.util.Iterator;
import java.util.Set;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import javax.management.Query;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class PortConfig implements ApplicationListener<WebServerInitializedEvent> {
   private Integer port = 0;

   public Integer getProPort() {
      if (this.port == 0) {
         this.port = this.getPort();
      }

      return this.port;
   }

   public void onApplicationEvent(WebServerInitializedEvent event) {
      this.port = event.getWebServer().getPort();
   }

   private int getPort() {
      try {
         if (MBeanServerFactory.findMBeanServer((String)null).size() <= 0) {
            return -1;
         }

         MBeanServer server = (MBeanServer)MBeanServerFactory.findMBeanServer((String)null).get(0);
         Set<ObjectName> names = server.queryNames(new ObjectName("Catalina:type=Connector,*"), Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
         Iterator<ObjectName> iterator = names.iterator();
         if (iterator.hasNext()) {
            ObjectName name = (ObjectName)iterator.next();
            return Integer.parseInt(server.getAttribute(name, "port").toString());
         }
      } catch (Exception e) {
         e.printStackTrace();
      }

      return -1;
   }
}
