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

import com.chenyang.nse.bussiness.entity.vo.ResultVO;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.KafkaAdminClient;

public class KafkaTool {
   public static ResultVO conntest(String host, int port) {
      boolean result = false;
      ResultVO resultvo = new ResultVO();
      Socket sClient = null;

      try {
         SocketAddress saAdd = new InetSocketAddress(host.trim(), port);
         sClient = new Socket();
         sClient.connect(saAdd, 3000);
         result = true;
         System.out.println("KAFKA系统IP及端口号连接正常！");
      } catch (Exception e) {
         e.printStackTrace();
         resultvo.setMessage(JdbcTool.getExceptionSrintStackTrace(e));
      } finally {
         resultvo.setResult(result);

         try {
            if (sClient != null) {
               sClient.close();
            }
         } catch (Exception e) {
            e.printStackTrace();
            resultvo.setMessage(JdbcTool.getExceptionSrintStackTrace(e));
            resultvo.setResult(false);
         }

         return resultvo;
      }
   }

   public static Set<String> kafkaListTopics(String host, String port) {
      Properties props = new Properties();
      props.put("bootstrap.servers", host + ":" + port);
      Set<String> topicsSet = new HashSet();

      try {
         AdminClient client = KafkaAdminClient.create(props);
         topicsSet = (Set)client.listTopics().names().get();
      } catch (Exception e) {
         e.printStackTrace();
      }

      return topicsSet;
   }

   public static void main(String[] args) {
      conntest("192.168.2.211", 9092);
      kafkaListTopics("192.168.2.211", "9092");
   }
}
