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

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class TicketTool {
   public static String getkrb5cc(String command) throws IOException, InterruptedException {
      Process process = null;
      new StringBuffer();
      String krb_tikct = "";
      File file = new File("/tmp");
      File[] tempList = file.listFiles();
      if (tempList == null) {
         return null;
      } else {
         for(int i = 0; i < tempList.length; ++i) {
            if (tempList[i].isFile()) {
               String krb = tempList[i].getName();
               if (krb.contains("krb5cc")) {
                  process = Runtime.getRuntime().exec("rm /tmp/" + krb);
               }
            }
         }

         if (process == null) {
            process = Runtime.getRuntime().exec("date");
         }

         process.waitFor();
         System.out.println("command:" + command);
         process = Runtime.getRuntime().exec(command);
         process.waitFor();
         BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
         new StringBuffer();

         String line;
         while((line = bufferedReader.readLine()) != null) {
            krb_tikct = line;
         }

         System.out.println("krb_tikct:" + krb_tikct);
         String tikct = krb_tikct.substring(krb_tikct.indexOf("/"), krb_tikct.length());
         System.out.println("生成tikct:" + tikct);
         return tikct;
      }
   }

   public static String updateHiveXml(String xmlpath, String value) throws DocumentException, IOException {
      File file = new File(xmlpath);
      SAXReader reader = new SAXReader();
      if (!file.exists()) {
         return null;
      } else {
         Document doc = reader.read(file);
         Element root = doc.getRootElement();

         for(Element child : root.elements()) {
            if ("hadoop.security.kerberos.ticket.cache.path".equals(child.elementText("name"))) {
               child.element("value").setText(value);
               System.out.println("ticket.cache.path:" + child.element("value").getText());
            }
         }

         FileOutputStream out = new FileOutputStream(file.getPath());
         OutputFormat format = OutputFormat.createPrettyPrint();
         format.setEncoding("UTF-8");
         XMLWriter writer = new XMLWriter(out);
         writer.write(doc);
         writer.close();
         return "ok";
      }
   }
}
