Package cputils

Source Code of cputils.XmlUtils

package cputils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import common.Config;

public class XmlUtils {
  private static String fileName = "data.xml";
//  private static String CONFIG_FILE_PATH = "config/";
//
//  public static String DATA_FILE_PATH = "data/";

  public static void main(String[] args) {
    XmlUtils dao = new XmlUtils();
    List<DataItem> list;
    try {
      Map<String, Object> last = CPHMTBService.lastIssuoInfo("SSQ");
      String ssqonsaleNo = (String) last.get("onsaleIssueNo");
      last = CPHMTBService.lastIssuoInfo("DLT");
      String dltonsaleNo = (String) last.get("onsaleIssueNo");
      // //list = dao.list("ssq");
      // // for (DataItem dataItem : list) {
      // //
      // //System.out.println(dataItem.getId()+":"+dataItem.getOpencode());
      // // }
      // //dao.tjSSQ();
      // //dao.importDLTData(8001, 8002);
      // /*for (int i = 0; i < 1000; i++) {
      // dao.deleteItem(i+"");
      // }*/
      dao.importDLTData(Integer.parseInt(dltonsaleNo));
      dao.importSSQData(Integer.parseInt(ssqonsaleNo));
      // dao.importDLTData(14041, Integer.parseInt("14070"));
      // System.out.println(dao.stat("dlt"));
    } catch (DocumentException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public Map<String, Map<Integer, Integer>> stat(String type)
      throws DocumentException, IOException {
    int bMax = 33, aMax = 16;
    if ("dlt".equals(type)) {
      bMax = 35;
      aMax = 12;
    }
    Map<String, Map<Integer, Integer>> res = new HashMap<String, Map<Integer, Integer>>();
    List<DataItem> list = list(type);
    Map<Integer, Integer> bMap = new HashMap<Integer, Integer>();
    Map<Integer, Integer> aMap = new HashMap<Integer, Integer>();
    for (int i = 1; i <= bMax; i++) {
      bMap.put(i, 0);
    }
    for (int i = 1; i <= aMax; i++) {
      aMap.put(i, 0);
    }
    for (DataItem dataItem : list) {
      String[] codeArr = dataItem.getOpencode().split(" ");
      for (int i = 0, size = codeArr.length; i < size; i++) {
        int num = Integer.parseInt(codeArr[i]);
        if (i < ("dlt".equals(type) ? 5 : 6)) {
          bMap.put(num, bMap.get(num) + 1);
        } else {
          aMap.put(num, aMap.get(num) + 1);
        }
      }
    }
    res.put("b", bMap);
    res.put("a", aMap);
    // System.out.println(res);
    return makeSortedMap(res, true);
  }

  public static Map<String, Map<Integer, Integer>> makeSortedMap(
      Map<String, Map<Integer, Integer>> res, boolean isSorted) {
    if (isSorted) {
      Map<Integer, Integer> bMap = res.get("b");
      Map<Integer, Integer> aMap = res.get("a");
      // List<KeyValueItem> bItems = new ArrayList<KeyValueItem>();
      // List<KeyValueItem> aItems = new ArrayList<KeyValueItem>();
      // for (Entry<Integer, Integer> entry : bMap.entrySet()) {
      // KeyValueItem item = new
      // KeyValueItem(entry.getKey(),entry.getValue());
      // bItems.add(item);
      // }
      // for (Entry<Integer, Integer> entry : aMap.entrySet()) {
      // KeyValueItem item = new
      // KeyValueItem(entry.getKey(),entry.getValue());
      // aItems.add(item);
      // }
      // aItems = sortList(aItems);
      // bItems = sortList(bItems);
      // bMap = new LinkedHashMap<Integer, Integer>();
      // aMap = new LinkedHashMap<Integer, Integer>();
      // for (KeyValueItem item : aItems) {
      // aMap.put(item.key, item.value);
      // }
      // for (KeyValueItem item : bItems) {
      // bMap.put(item.key, item.value);
      // }
      res.put("b", makeSortedMap(bMap));
      res.put("a", makeSortedMap(aMap));
    }
    return res;
  }

  public static Map<Integer, Integer> makeSortedMap(Map<Integer, Integer> res) {
    List<KeyValueItem> aItems = new ArrayList<KeyValueItem>();
    for (Entry<Integer, Integer> entry : res.entrySet()) {
      KeyValueItem item = new KeyValueItem(entry.getKey(),
          entry.getValue());
      aItems.add(item);
    }
    aItems = sortList(aItems);
    Map<Integer, Integer> aMap = new LinkedHashMap<Integer, Integer>();
    for (KeyValueItem item : aItems) {
      aMap.put(item.key, item.value);
    }
    return aMap;
  }

  private static List<KeyValueItem> sortList(List<KeyValueItem> list) {
    Collections.sort(list, new Comparator<KeyValueItem>() {
      public int compare(KeyValueItem o1, KeyValueItem o2) {
        return o2.value - o1.value;
      }
    });
    return list;
  }

  public void importSSQData(Integer currengNo) throws DocumentException,
      IOException {
    Map<String, String> ssqMap = null;
    int begin = 2014001;
    for (int i = currengNo - 1; i > 0; i--) {
      if (isExisted(i + "", "ssq")) {
        begin = i + 1;
        break;
      }
    }
    for (int i = begin; i < currengNo; i++) {
      /*
       * if (Integer.parseInt((i+"").substring((i+"").length()-3))>160) {
       * continue; }
       */
      ssqMap = CPDataService.getKJData(i + "");
      if (ssqMap != null) {
        DataItem item = new DataItem();
        item = new DataItem(i + "", ssqMap.get(i + ""), "ssq");
        try {
          if (!addItem(item)) {
            break;
          } else {
            System.out.println(i + " insert...");
          }
        } catch (DocumentException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

  public void importDLTData(Integer currengNo) throws DocumentException,
      IOException {
    int begin = 14001;
    for (int i = currengNo - 1; i > 0; i--) {
      if (isExisted(i + "", "dlt")) {
        begin = i + 1;
        break;
      }
    }
    Map<String, String> dltMap = null;
    for (int i = begin; i < currengNo; i++) {
      if (Integer.parseInt((i + "").substring((i + "").length() - 3)) > 180) {
        continue;
      }
      dltMap = CPDataService.getKJData((i + "").length() == 5 ? (i + "")
          : "0" + i + "");
      if (dltMap != null) {
        DataItem item = new DataItem();
        item = new DataItem(i + "", dltMap.get(i + ""), "dlt");
        try {
          if (!addItem(item)) {
            break;
          } else {
            System.out.println(i + " insert...");
          }
        } catch (DocumentException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

  public Document getDocument(String type) throws DocumentException,
      IOException {
//    SAXReader reader = new SAXReader();
//    reader.setEncoding("UTF-8");
//    File file = new File(CONFIG_FILE_PATH + type + fileName);
//    if (!file.exists()) {
//      throw new FileNotFoundException("FileNotFound:" + type + fileName);
//    }
//    Document document = reader.read(file);
    return getDocumentComm(Config.CONFIG_FILE_PATH + type + fileName);
  }
 
  public Document getDocumentComm(String filePathAndName) throws DocumentException,
    IOException {
    SAXReader reader = new SAXReader();
    reader.setEncoding("UTF-8");
    File file = new File(filePathAndName);
    if (!file.exists()) {
      throw new FileNotFoundException("FileNotFound:" + filePathAndName);
    }
    Document document = reader.read(file);
    return document;
  }

  public List<DataItem> list(String type) throws DocumentException,
      IOException {
    List<DataItem> list = new ArrayList<DataItem>();
    Document root = getDocument(type);
    Element rootEl = root.getRootElement();
    Iterator<Element> it = rootEl.elementIterator();
    Element el;
    DataItem item;
    while (it.hasNext()) {
      el = it.next();
      item = new DataItem(el.attributeValue("ID"),
          el.attributeValue("opencode"), el.attributeValue("type"));
      list.add(item);
    }
    return list;
  }

  public DataItem getDataItem(String issueNo) throws DocumentException,
      IOException {
    String type = issueNo.length() == 5 ? "dlt" : "ssq";
    DataItem item = null;
    Document root = getDocument(type);
    Element element = root.getRootElement().elementByID(issueNo);
    if (element != null) {

      item = new DataItem(element.attributeValue("ID"),
          element.attributeValue("opencode"),
          element.attributeValue("type"));
    }
    return item;
  }

  private boolean isExisted(String issueNo, String type)
      throws DocumentException, IOException {
    Document root = getDocument(type);
    Element rootEl = root.getRootElement();
    if (rootEl.elementByID(issueNo) != null) {
      return true;
    }
    return false;
  }

  public boolean addItem(DataItem item) throws DocumentException, IOException {
    Document root = getDocument(item.getType());
    Element rootEl = root.getRootElement();
    if (rootEl.elementByID(item.getId()) != null) {
      System.err.println(item.getType() + " number:" + item.getId()
          + " is existed.");
      writeLogs(item.getType() + " number:" + item.getId()
          + " is existed.", this.getClass(), null);
      return false;
    }
    List<Element> list = rootEl.elements();
    Element el = DocumentHelper.createElement("item");
    el.addAttribute("ID", item.getId());
    el.addAttribute("opencode", item.getOpencode());
    el.addAttribute("type", item.getType());
    list.add(el);
    writeDoc(root, item.getType());
    return true;
  }
 
  public boolean addSSCItem(DataItem item) throws DocumentException, IOException {
    Document root = getDocumentComm(Config.DATA_FILE_PATH+item.getType()+".xml");
    Element rootEl = root.getRootElement();
    if (rootEl.elementByID(item.getId()) != null) {
//      System.err.println(item.getType() + " number:" + item.getId()
//          + " is existed.");
      writeLogs(item.getType() + " number:" + item.getId()
          + " is existed.", this.getClass(), null);
      return false;
    }
    List<Element> list = rootEl.elements();
    Element el = DocumentHelper.createElement("item");
    el.addAttribute("ID", item.getId());
    el.addAttribute("opencode", item.getOpencode());
    el.addAttribute("type", item.getType());
    list.add(el);
    writeDocComm(root, Config.DATA_FILE_PATH+item.getType()+".xml");
    return true;
  }
 
  public boolean deleteAll(String filePathAndName) throws DocumentException, IOException {
    Document root = getDocumentComm(filePathAndName);
    Element rootEl = root.getRootElement();
    root.remove(rootEl);
    writeDocComm(root, filePathAndName);
    return true;
  }
 
  public int delete(String id, String filePathAndName) throws DocumentException, IOException {
    Document root = getDocumentComm(filePathAndName);
    Element rootEl = root.getRootElement();
    Element deleteEl = rootEl.elementByID(id);
    boolean flag = rootEl.remove(deleteEl);
    if (flag) {
//      System.out.println("delete id ok:" + id);
    } else {
      System.out.println("delete id fail:" + id);
    }
    writeDocComm(root, filePathAndName);
    return 1;
    }
 
  public int deleteItem(String id, String type) throws DocumentException,
      IOException {
    Document root = getDocument(type);
    Element rootEl = root.getRootElement();
    // rootEl.elementByID("10001");
    Element deleteEl = rootEl.elementByID(id);
    // Node deleteEl = rootEl.selectSingleNode("//item/");
    boolean flag = rootEl.remove(deleteEl);
    if (flag) {
      writeLogs(type + " delete number:" + id, this.getClass(), null);
    } else {
      writeLogs(type + " delete number:" + id + " error.",
          this.getClass(), null);
    }
    writeDoc(root, type);
    return 1;
  }

  public int writeDoc(Document document, String type) throws IOException {
    return writeDocComm(document, Config.CONFIG_FILE_PATH + type + fileName);
  }
 
  public int writeDocComm(Document document, String filePathAndName) throws IOException {
    OutputFormat former = OutputFormat.createPrettyPrint();// ���ø�ʽ�������
    former.setEncoding("UTF-8");
    XMLWriter writer = new XMLWriter(new OutputStreamWriter(
        new FileOutputStream(filePathAndName),
        "UTF-8"), former);
    writer.write(document);
    writer.close();
    return 1;
  }

  public static void writeLogs(String message, Class<?> clazz, Exception e1) {
    try {
      File logFile = new File(Config.CONFIG_FILE_PATH + "log.log");
      if (!logFile.exists()) {
        logFile.createNewFile();
      }
      SimpleDateFormat format = new SimpleDateFormat(
          "yyyy-MM-dd hh:mm:ss");
      FileOutputStream fileOutputStream = new FileOutputStream(logFile,
          true);
      OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream);
      StringBuffer buffer = new StringBuffer();
      buffer.append(format.format(new Date())).append("] [")
          .append(clazz.getName()).append("] [").append(message)
          .append("]\r\n");
      writer.write(buffer.toString());
      if (e1 != null) {
        PrintWriter log = new PrintWriter(writer, true);
        e1.printStackTrace(log);
      }
      writer.close();
      fileOutputStream.close();
    } catch (IOException e) {
      System.err.println("file write fail:" + e.getMessage());
    }
  }

  public static List<String> getHMData(String issueNo) throws IOException {
    List<String> list = new ArrayList<String>();
    File file = new File(Config.CONFIG_FILE_PATH + issueNo + ".txt");
    if (!file.exists()) {
      throw new FileNotFoundException("file not found...");
    }
    FileReader fileReader = new FileReader(file);
    BufferedReader reader = new BufferedReader(fileReader);
    String con;
    while ((con = reader.readLine()) != null) {
      list.add(con);
    }
    reader.close();
    fileReader.close();
    return list;
  }

  public static void writeConfigFile(String message, String fileName, boolean append) {
    writeFile(message, Config.CONFIG_FILE_PATH, fileName, append);
  }
 
  public static void writeDataFile(String message, String fileName, boolean append) {
    writeFile(message, Config.DATA_FILE_PATH, fileName, append);
  }
 
  public static void writeFile(String message, String filePath,String fileName, boolean append) {
    try {
      File file = new File(filePath + fileName);
      if (!file.exists()) {
        file.createNewFile();
      }
      FileOutputStream fileOutputStream = new FileOutputStream(file,
          append);
      OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream);
      writer.write(message);
      writer.close();
      fileOutputStream.close();
    } catch (IOException e) {
      System.err.println("file write fail:" + e.getMessage());
    }
  }
 
}

class KeyValueItem {
  public Integer key;
  public Integer value;

  public KeyValueItem(Integer key, Integer value) {
    this.key = key;
    this.value = value;
  }
}
TOP

Related Classes of cputils.XmlUtils

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.