数据库建模pdm文件的解析、简单删除表和保存

工具的开发背景:
crm系统以ework为基础改造而来,以前简单起见和ework混合了代码和表的,现在需要分析,就需要重新分析,哪些是共用的,哪些是私有的。
通过日志中打印的表名,可以分析出哪些表是crm独有的。
通过pdm文件表的创建记录确定哪些表是新表,新的表少,再除去crm独有的,所以方便人工检查哪些是crm专有的。

另外分析了us系统那边用到的表(那边用到的就肯定不能公用),
cas、权限、用户、组织单位、数据字典的肯定是公用的。
另外考虑以前开发中折中,偷懒,有些方法混合了ework、crm一方使用无需用到的表,目前一时没法剥离,需要确定备忘。

总体思路:
日志(或初始化sql脚本)或pdm中分析出来的表名列表结果分别存到集合包里面,通过里面的CollectionTool.java做集合的运算、打印(打印表名、编码、pdm中所属包方便人工判断)、保存。

工具编写匆忙,可能有少量bug和注释不统一的地方,不懂的请研究代码,恕不做技术支持。

pdm解析的
package chenxiaowen.tool.pdm;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.dom4j.Attribute;
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;

import chenxiaowen.tool.collections.CollectionTool;
import chenxiaowen.tool.pdm.pojo.Column;
import chenxiaowen.tool.pdm.pojo.PhysicalDiagram;
import chenxiaowen.tool.pdm.pojo.Table;

/**
 * pdm文件解析出 PhysicalDiagram、Table、Column<br>
 * 演示了pdm元素的查找、删除、保存。 <br>
 * 如果文件很大导致内存溢出,请配置运行的vm参数,如:-Xms400m -Xmx1024m<br>
 * <br>
 * dom4j的xpath查找xml的指定节点 <br>
 * http://blog.csdn.net/sidihuo/article/details/41310727<br>
 * xpath表达式如: <br>
 * "//div[@style][@id='BlogArticleDetail']/[1]"<br>
 * "//div[@class='PageSkip_1']//a[@title]/[1]/text()"<br>
 * "//div[@class='PageSkip_1']//a/text()"<br>
 * "//div[@class='ArticleTitle']/text()[1]"<br>
 * "//div[@class='PageSkip_1']//a[@title]/[1]/text()" <br>
 * 
 * @author 陈小稳 [email protected]
 */
public class PdmParser {
	private File pdmFile;
	private Document doc;
	private ArrayList<Table> tableList = null;
	// <表id,表>
	private HashMap<String, Table> idTableMap = null;
	// <表code,表>
	private HashMap<String, Table> codeTableMap = null;
	// <表id,表所属PhysicalDiagram>
	private HashMap<String, PhysicalDiagram> idPhysicalDiagramMap = null;
	private ArrayList<PhysicalDiagram> PhysicalDiagramsList = null;
	private boolean hasParseColumns;
	private boolean hasParsePhysicalDiagrams;
	private boolean hasParseTables;

	public static void main(String[] args) throws Exception {
		File pdmFile = new File("D:\\Desktop\\PhysicalData_1.pdm");
		PdmParser parseTool = new PdmParser(pdmFile);

		// //按 PhysicalDiagram>表>字段 打印
		// parseTool.printAllInfo();

		// //按 PhysicalDiagram>表>字段 打印指定日期后新增的表和字段信息
		// parseTool.printAddedInfoAfterDate("2016-12-10 00:01");

		// //打印指定日期后新增的表的信息
		// parseTool.printAddedTablesAfterDate("2016-12-10 00:01");

		// // 指定日期后新增的表的信息输出到集合文件
		// parseTool.writeAddedTablesAfterDateToCollectionFile("2016-06-01",
		// "z.new_crm.txt");

		// // 将所有表名输入到表名集合文件
		// parseTool.printAllTablesToCollectionFile("4.txt");

		// //将所有pdm文件中有表定义没所属包的表的表名输入到表名集合文件
		// parseTool.printTablesWithOutSymbolToCollectionFile("4.txt");

		// // 编辑保存
		// parseTool.deleteTableByCode("t_3,Table_1");
		// File file = new File("D:\\Desktop\\new.pdm");
		// parseTool.saveToFile(file);

		// String datastr="2016-12-9 23:24";//查询的日期转换成pdm格式的时间
		// Date date1 = DateUtils.parseDate(datastr, new String[]{"yyyy-MM-dd
		// HH:mm","yyyy-MM-dd"});
		// String compareDate = date1.getTime()/1000+"";
		// System.out.println(compareDate);//1481297040
		// System.out.println(System.currentTimeMillis());//1481297096391

		// String creationDate="1481286082";//pdm格式的时间转换为一般可视化日期
		// Long timeMillis = Long.parseLong(creationDate)*1000;
		// Date date2 = new Date(timeMillis);
		// String datastr2 = DateFormatUtils.format(date2, "yyyy-MM-dd
		// HH:mm:ss");
		// System.out.println(datastr2);//2016-12-09 20:21:22

	}

	/**
	 * 根据表名删除指定节点
	 * 
	 * @param parseTool
	 * @param string
	 * @throws DocumentException
	 */
	public void deleteTableByCode(String tableCodes) throws DocumentException {
		String[] codes = tableCodes.split(",");
		if (!this.hasParseTables) {
			parseTables();
		}
		if (!this.hasParsePhysicalDiagrams) {
			parsePhysicalDiagrams();
		}
		for (int i = 0; i < codes.length; i++) {
			String code = codes[i];
			if (StringUtils.isEmpty(code)) {
				continue;
			}
			Table table = codeTableMap.get(code);
			if (table == null) {
				System.err.println("要删除的表 " + code + " 不在pdm中");
				continue;
			}
			String tableid = table.getId();

			// 根据table 的Id属性过滤
			String xpath = "//c:Tables/o:Table[@Id='" + tableid + "']";

			// 根据表格的code节点的文本内容查找到code节点,再获得上级(也就是表格)
			// String xpath = "//c:Tables/o:Table/a:Code[text()='" + code +
			// "']/..";

			List<Element> composites = this.getDoc().selectNodes(xpath);
			if (CollectionUtils.isEmpty(composites)) {
				System.err.println("没找到编号为 " + code + " 的表");
			} else if (composites.size() > 1) {
				System.err.println("找到编号为 " + code + " 的表,但不唯一");
			} else {
				Element tableElement = composites.get(0);
				// String tableid = tableElement.attributeValue("Id");

				System.out.println("删除表,编号为 " + code + ",id=" + tableid
						+ " 位置:" + idPhysicalDiagramMap.get(tableid).getName());
				// 删表
				tableElement.getParent().remove(tableElement);

				// 删除表所属包的关系
				String xpath2 = "//c:PhysicalDiagrams//c:Symbols//o:Table[@Ref='"
						+ tableid + "']";// 简写部分关键路径
				// String xpath2 =
				// "//c:PhysicalDiagrams//o:PhysicalDiagram//c:Symbols//o:TableSymbol//c:Object//o:Table[@Ref='"
				// + tableid + "']";//完整路径
				List<Element> composites2 = this.getDoc().selectNodes(xpath2);
				if (CollectionUtils.isNotEmpty(composites2)) {
					System.out.println("删表(编号为 " + code + ")的包、表关系 "
							+ composites2.size() + " 处");
					for (Iterator iterator = composites2.iterator(); iterator
							.hasNext();) {
						Element element = (Element) iterator.next();
						// 删表的引用
						Element oTableSymbolElement = element.getParent()
								.getParent();
						oTableSymbolElement.getParent().remove(
								oTableSymbolElement);
					}
				} else {
					System.err.println("删表编号为 " + code + "的表,找不到所属包");
				}

				// 删除表所属外键的关系
				String xpath3 = "//c:References//o:Table[@Ref='" + tableid
						+ "']";// 简写部分关键路径
				List<Element> composites3 = this.getDoc().selectNodes(xpath3);
				if (CollectionUtils.isNotEmpty(composites3)) {
					System.out.println("删表(编号为 " + code + ")的外键 "
							+ composites3.size() + " 处");
					for (Iterator iterator = composites3.iterator(); iterator
							.hasNext();) {
						Element element = (Element) iterator.next();
						Element oReferenceElement = element.getParent()
								.getParent();
						oReferenceElement.getParent().remove(oReferenceElement);
					}
				} else {
					System.out.println("删表编号为 " + code + "的表,找不到相关外键");
				}

			}
		}
	}

	public HashMap<String, PhysicalDiagram> getIdPhysicalDiagramMap() {
		return idPhysicalDiagramMap;
	}

	public void setIdPhysicalDiagramMap(
			HashMap<String, PhysicalDiagram> idPhysicalDiagramMap) {
		this.idPhysicalDiagramMap = idPhysicalDiagramMap;
	}

	public void saveToFile(File file) {
		try {
			if (file.exists()) {
				System.out.println("del " + file.getAbsolutePath());
				file.delete();
			}
			/*
			 * OutputFormat format = new OutputFormat();// 指定XML的输出样式
			 * OutputFormat.createPrettyPrint() format.setEncoding("UTF-8"); //
			 * 指定XML编码 XMLWriter writer = new XMLWriter(new FileWriter(file),
			 * format); Document doc = this.getDoc();
			 * doc.setXMLEncoding("UTF-8"); writer.write(doc); writer.close();
			 */

			// 解决输出乱码问题
			OutputFormat format = new OutputFormat();
			format.setEncoding("UTF-8");
			OutputStream out = new FileOutputStream(file);
			XMLWriter writer = new XMLWriter(out, format);
			writer.write(this.getDoc());
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 解析 PhysicalDiagram、表、字段 信息
	 * 
	 * @param parseTool
	 * @throws DocumentException
	 */
	public void parseAllInfo() throws DocumentException {
		if (!this.hasParseTables) {
			parseTables();
		}
		if (!this.hasParseColumns) {
			parseColumns();
		}
		if (!this.hasParsePhysicalDiagrams) {
			parsePhysicalDiagrams();
		}
	}

	/**
	 * 解析多个pdm文件的表和模块
	 * 
	 * @param pdmFiles
	 * @return
	 * @throws DocumentException
	 */
	public static PdmParser parseTablesAndPhysicalDiagrams(String[] pdmFiles)
			throws DocumentException {
		// <表code,表>
		HashMap<String, Table> codeTableMap = new HashMap<String, Table>();
		// <表id,表所属PhysicalDiagram>
		HashMap<String, PhysicalDiagram> idPhysicalDiagramMap = new HashMap<String, PhysicalDiagram>();
		for (int i = 0; i < pdmFiles.length; i++) {
			File pdmFile1 = new File(pdmFiles[i]);
			PdmParser parseTool1 = new PdmParser(pdmFile1);
			parseTool1.parseTables();
			parseTool1.parsePhysicalDiagrams();
			HashMap<String, Table> codeTableMap1 = parseTool1.getCodeTableMap();
			HashMap<String, PhysicalDiagram> idPhysicalDiagramMap1 = parseTool1
					.getIdPhysicalDiagramMap();
			codeTableMap.putAll(codeTableMap1);
			idPhysicalDiagramMap.putAll(idPhysicalDiagramMap1);
		}
		PdmParser r = new PdmParser(null);
		r.setIdPhysicalDiagramMap(idPhysicalDiagramMap);
		r.setCodeTableMap(codeTableMap);
		return r;
	}

	/**
	 * 按 PhysicalDiagram>表>字段 打印指定日期后新增的表和字段信息
	 * 
	 * @param parseTool
	 * @param datastr
	 *            查询的时间,如:"2016-12-9 20:21:22"
	 * @throws ParseException
	 * @throws DocumentException
	 */
	public void printAddedInfoAfterDate(String datastr) throws ParseException,
			DocumentException {
		if (!this.hasParseTables) {
			parseTables();
		}
		if (!this.hasParseColumns) {
			parseColumns();
		}
		if (!this.hasParsePhysicalDiagrams) {
			parsePhysicalDiagrams();
		}
		// 如果表是新增的,则在 表上标记新增。
		// 如果表是旧的,字段是新增的,则在 字段 上标记新增。
		Date date1 = DateUtils.parseDate(datastr, new String[] {
				"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd" });
		String compareDateTicksStr = date1.getTime() / 1000 + "";
		System.out.println("==打印指定日期 " + datastr + "(" + compareDateTicksStr
				+ ") 之后新增的表格和字段============================");
		for (Iterator iterator = this.getPhysicalDiagramsList().iterator(); iterator
				.hasNext();) {
			PhysicalDiagram pd = (PhysicalDiagram) iterator.next();
			Boolean packHasPrint = false;
			ArrayList<String> tableIds = pd.getTableIds();
			for (Iterator iterator2 = tableIds.iterator(); iterator2.hasNext();) {
				String tableid = (String) iterator2.next();
				Table table = this.getIdTableMap().get(tableid);
				Boolean tableHasPrint = false;
				// 发现指定日期后的表格
				if (table.getCreationDate().compareTo(compareDateTicksStr) >= 0) {
					if (!packHasPrint) {
						packHasPrint = true;
						System.out.println("" + pd);
					}
					tableHasPrint = true;
					System.out.println("\t【new】" + table);
				}
				ArrayList<Column> columns = table.getColumns();
				Boolean tableIsNew = tableHasPrint;
				for (Iterator iterator3 = columns.iterator(); iterator3
						.hasNext();) {
					Column column = (Column) iterator3.next();
					// 发现指定日期后的字段
					if (column.getCreationDate().compareTo(compareDateTicksStr) >= 0) {
						if (!packHasPrint) {
							packHasPrint = true;
							System.out.println("" + pd);
						}
						if (!tableHasPrint) {
							tableHasPrint = true;
							System.out.println("\t" + table);
						}

						System.out.println("\t\t" + (tableIsNew ? "" : "【new】")
								+ column);
					}
				}
			}
		}
	}

	/**
	 * 打印指定日期后新增的表的信息
	 * 
	 * @param datastr
	 * @throws ParseException
	 * @throws DocumentException
	 */
	public void printAddedTablesAfterDate(String datastr)
			throws ParseException, DocumentException {
		if (!this.hasParseTables) {
			parseTables();
		}
		Date date1 = DateUtils.parseDate(datastr, new String[] {
				"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd" });
		String compareDateTicksStr = date1.getTime() / 1000 + "";
		TreeSet<String> adds = new TreeSet<String>();
		for (Iterator iterator2 = tableList.iterator(); iterator2.hasNext();) {
			Table table = (Table) iterator2.next();
			// 发现指定日期后的表格
			if (table.getCreationDate().compareTo(compareDateTicksStr) >= 0) {
				adds.add(table.getCode());
			}
		}
		for (Iterator iterator = adds.iterator(); iterator.hasNext();) {
			String tablecode = (String) iterator.next();
			System.out.println(tablecode + ",");
		}
	}

	/**
	 * 指定日期后新增的表的信息输出到集合文件
	 * 
	 * @param datastr
	 * @throws ParseException
	 * @throws DocumentException
	 */
	public void writeAddedTablesAfterDateToCollectionFile(String datastr,
			String filename) throws Exception {
		if (!this.hasParseTables) {
			parseTables();
		}
		Date date1 = DateUtils.parseDate(datastr, new String[] {
				"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd" });
		String compareDateTicksStr = date1.getTime() / 1000 + "";
		TreeSet<String> adds = new TreeSet<String>();
		for (Iterator iterator2 = tableList.iterator(); iterator2.hasNext();) {
			Table table = (Table) iterator2.next();
			// 发现指定日期后的表格
			if (table.getCreationDate().compareTo(compareDateTicksStr) >= 0) {
				adds.add(table.getCode());
			}
		}
		CollectionTool.writeCollectionFile(filename, adds);
	}

	/**
	 * 将所有表名输入到表名集合文件
	 * 
	 * @param filename
	 * @throws DocumentException
	 */
	public void printAllTablesToCollectionFile(String filename)
			throws Exception {
		if (!this.hasParseTables) {
			parseTables();
		}
		TreeSet<String> a = new TreeSet<String>();
		for (Iterator iterator = tableList.iterator(); iterator.hasNext();) {
			Table t = (Table) iterator.next();
			a.add(t.getCode());
		}
		CollectionTool.writeCollectionFile(filename, a);
	}

	/**
	 * 将所有pdm文件中有表定义没所属包的表的表名输入到表名集合文件
	 * 
	 * @param filename
	 * @throws DocumentException
	 */
	public void printTablesWithOutSymbolToCollectionFile(String filename)
			throws Exception {
		if (!this.hasParseTables) {
			parseTables();
		}
		if (!this.hasParsePhysicalDiagrams) {
			parsePhysicalDiagrams();
		}
		TreeSet<String> a = new TreeSet<String>();
		for (Iterator iterator = tableList.iterator(); iterator.hasNext();) {
			Table t = (Table) iterator.next();
			String tbid = t.getId();
			PhysicalDiagram symbol = idPhysicalDiagramMap.get(tbid);
			if (symbol == null) {
				a.add(t.getCode());
			}
		}
		CollectionTool.writeCollectionFile(filename, a);
	}

	/**
	 * 按 PhysicalDiagram>表>字段 打印
	 * 
	 * @param parseTool
	 * @throws DocumentException
	 */
	public void printAllInfo() throws DocumentException {
		if (!this.hasParseTables) {
			parseTables();
		}
		if (!this.hasParseColumns) {
			parseColumns();
		}
		if (!this.hasParsePhysicalDiagrams) {
			parsePhysicalDiagrams();
		}

		System.out
				.println("==按 PhysicalDiagram>表>字段 打印======================================================================");
		for (Iterator iterator = getPhysicalDiagramsList().iterator(); iterator
				.hasNext();) {
			PhysicalDiagram pd = (PhysicalDiagram) iterator.next();
			System.out.println(pd.toString());
			ArrayList<String> tableIds = pd.getTableIds();
			for (Iterator iterator2 = tableIds.iterator(); iterator2.hasNext();) {
				String tableid = (String) iterator2.next();
				Table table = getIdTableMap().get(tableid);
				System.out.println("\t" + table);
				ArrayList<Column> columns = table.getColumns();
				for (Iterator iterator3 = columns.iterator(); iterator3
						.hasNext();) {
					Column column = (Column) iterator3.next();
					System.out.println("\t\t" + column);
				}
			}
		}
	}

	/**
	 * 1.解析所有表格
	 * 
	 * @throws DocumentException
	 */
	public void parseTables() throws DocumentException {
		tableList = new ArrayList<Table>();
		idTableMap = new HashMap<String, Table>();
		codeTableMap = new HashMap<String, Table>();
		Iterator itr = doc.selectNodes("//c:Tables//o:Table").iterator();
		Table table = null;
		while (itr.hasNext()) {
			table = new Table();
			Element tableElement = (Element) itr.next();
			String id = tableElement.attribute("Id").getValue();
			table.setId(id);
			String code = tableElement.elementTextTrim("Code");
			code = code.toLowerCase();
			table.setCode(code);
			table.setName(tableElement.elementTextTrim("Name"));
			table.setCreationDate(tableElement.elementTextTrim("CreationDate"));
			table.setModificationDate(tableElement
					.elementTextTrim("ModificationDate"));
			tableList.add(table);
			idTableMap.put(id, table);
			codeTableMap.put(code, table);
		}
		this.hasParseTables = true;
	}

	/**
	 * 2.解析所有PhysicalDiagram和PhysicalDiagram包含的表
	 * 
	 * @throws DocumentException
	 */
	public void parsePhysicalDiagrams() throws DocumentException {
		PhysicalDiagramsList = new ArrayList<PhysicalDiagram>();
		idPhysicalDiagramMap = new HashMap<String, PhysicalDiagram>();
		Iterator itr = doc.selectNodes(
				"//c:PhysicalDiagrams//o:PhysicalDiagram").iterator();
		PhysicalDiagram physicalDiagram = null;
		while (itr.hasNext()) {
			physicalDiagram = new PhysicalDiagram();
			Element element = (Element) itr.next();
			String id = element.attribute("Id").getValue();
			physicalDiagram.setId(id);
			String code = element.elementTextTrim("Code");
			code = code.toLowerCase();
			physicalDiagram.setName(element.elementTextTrim("Name"));
			physicalDiagram.setCode(code);
			// physicalDiagram.setCreationDate(element.elementTextTrim("CreationDate"));
			// physicalDiagram.setModificationDate(element.elementTextTrim("ModificationDate"));
			PhysicalDiagramsList.add(physicalDiagram);

			// System.out.println("name:"+physicalDiagram.getName()+"
			// id:"+physicalDiagram.getId());
			// 不以“//”开头,表示从下级里面查找
			Iterator ittable = element.selectNodes(
					"c:Symbols//o:TableSymbol//c:Object//o:Table").iterator();
			ArrayList<String> tableIds = new ArrayList<String>();
			while (ittable.hasNext()) {
				Element reftable = (Element) ittable.next();
				String tableid = reftable.attribute("Ref").getValue();
				// System.out.println("ref tableid:"+tableid);
				tableIds.add(tableid);
				idPhysicalDiagramMap.put(tableid, physicalDiagram);
			}
			physicalDiagram.setTableIds(tableIds);
		}
		this.hasParsePhysicalDiagrams = true;
	}

	/**
	 * 3.解析表的字段和pk
	 * 
	 * @param table
	 * @throws DocumentException
	 */

	public void parseColumns() throws DocumentException {
		for (Iterator iterator = getTableList().iterator(); iterator.hasNext();) {
			Table table = (Table) iterator.next();
			parseColumnsOfTable(table);
		}
		this.hasParseColumns = true;
	}

	/**
	 * 解析表的字段和pk
	 * 
	 * @param table
	 * @throws DocumentException
	 */
	public void parseColumnsOfTable(Table table) throws DocumentException {
		ArrayList<Column> columnlist = new ArrayList<Column>();
		Column column = null;
		Element tableElement = getTableElementById(table.getId());
		// Iterator itr1 =
		// tableElement.element("Columns").elements("Column").iterator();
		Iterator itr1 = tableElement.selectNodes("c:Columns//o:Column")
				.iterator();
		while (itr1.hasNext()) {
			column = new Column();
			Element columnElement = (Element) itr1.next();
			String id = columnElement.attributeValue("Id");
			// String id = columnElement.attribute("Id").getValue();
			column.setId(id);
			column.setName(columnElement.elementTextTrim("Name"));
			String code = columnElement.elementTextTrim("Code");
			code = code.toLowerCase();
			column.setCode(code);
			column.setCreationDate(columnElement
					.elementTextTrim("CreationDate"));
			column.setModificationDate(columnElement
					.elementTextTrim("ModificationDate"));
			String length = columnElement.elementTextTrim("Length");
			column.setLength(length == null ? null : Integer.parseInt(length));
			String dataType = columnElement.elementTextTrim("DataType");
			if (dataType.indexOf("(") > 0) {
				column.setType(dataType.substring(0, dataType.indexOf("(")));
			} else {
				column.setType(dataType);
			}
			columnlist.add(column);
		}
		table.setColumns(columnlist);

		// set pk
		if (tableElement.element("Keys") != null) {
			String keys_primarykey_ref_id = tableElement.element("PrimaryKey")
					.element("Key").attributeValue("Ref");
			String keys_key_id = tableElement.element("Keys").element("Key")
					.attributeValue("Id");
			if (keys_primarykey_ref_id.equals(keys_key_id)) {
				String keys_column_ref = tableElement.element("Keys").element(
						"Key").element("Key.Columns").element("Column")
						.attributeValue("Ref");
				for (Iterator iterator = columnlist.iterator(); iterator
						.hasNext();) {
					Column columni = (Column) iterator.next();
					if (keys_column_ref.equals(columni.getId())) {
						columni.setPkFlag(true);
						table.setPkFieldCode(columni.getCode());
					}
				}
			}
		}
	}

	/**
	 * 根据Id找到 PhysicalDiagram 元素
	 * 
	 * @param id
	 * @return
	 * @throws DocumentException
	 */
	public Element getPhysicalDiagramElementById(String id)
			throws DocumentException {
		Element tableElement = getElementByTypePathAndAttrVal(
				"//c:PhysicalDiagrams//o:PhysicalDiagram", "Id", id);
		return tableElement;
	}

	/**
	 * 根据Id找到表元素
	 * 
	 * @param id
	 * @return
	 * @throws DocumentException
	 */
	public Element getTableElementById(String id) throws DocumentException {
		Element tableElement = getElementByTypePathAndAttrVal(
				"//c:Tables//o:Table", "Id", id);
		return tableElement;
	}

	/**
	 * 根据typepath找到指定类型的元素,再根据元素上的属性定位具体的元素
	 * 
	 * @param typepath
	 * @param attrName
	 * @param attrVal
	 * @return
	 * @throws DocumentException
	 */
	public Element getElementByTypePathAndAttrVal(String typepath,
			String attrName, String attrVal) throws DocumentException {
		Iterator itr = doc.selectNodes(typepath).iterator();
		Table table = null;
		while (itr.hasNext()) {
			Element element = (Element) itr.next();
			Attribute attr = element.attribute(attrName);
			if (attr != null) {
				String txt = attr.getValue();
				if (StringUtils.equalsIgnoreCase(attrVal, txt)) {
					return element;
				}
			}
		}
		return null;
	}

	/**
	 * 枚举列出元素上的所有属性
	 * 
	 * @param tableElement
	 */
	private void showAttributes(Element tableElement) {
		List<Attribute> listAttr = tableElement.attributes();// 当前节点的所有属性的list
		for (Attribute attr : listAttr) {// 遍历当前节点的所有属性
			String name = attr.getName();// 属性名称
			String value = attr.getValue();// 属性的值
			System.out.println("属性名称:" + name + "属性值:" + value);
		}
	}

	/**
	 * @deprecated
	 * @throws DocumentException
	 */
	private void printTables() throws DocumentException {
		if (CollectionUtils.isNotEmpty(tableList)) {
			for (Iterator iterator = tableList.iterator(); iterator.hasNext();) {
				Table table = (Table) iterator.next();
				System.out.println(table.getCode() + "\t" + table.getId());
			}
		}
	}

	public PdmParser(File pdmFile) throws DocumentException {
		this.pdmFile = pdmFile;
		if (pdmFile != null && pdmFile.exists()) {
			SAXReader sr = new SAXReader();
			this.doc = sr.read(this.pdmFile);
		}
	}

	public ArrayList<Table> getTableList() {
		return tableList;
	}

	public void setTableList(ArrayList<Table> tableList) {
		this.tableList = tableList;
	}

	public ArrayList<PhysicalDiagram> getPhysicalDiagramsList() {
		return PhysicalDiagramsList;
	}

	public void setPhysicalDiagramsList(
			ArrayList<PhysicalDiagram> physicalDiagramsList) {
		PhysicalDiagramsList = physicalDiagramsList;
	}

	public HashMap<String, Table> getIdTableMap() {
		return idTableMap;
	}

	public void setIdTableMap(HashMap<String, Table> idTableMap) {
		this.idTableMap = idTableMap;
	}

	public Document getDoc() {
		return doc;
	}

	public void setDoc(Document doc) {
		this.doc = doc;
	}

	public HashMap<String, Table> getCodeTableMap() {
		return codeTableMap;
	}

	public void setCodeTableMap(HashMap<String, Table> codeTableMap) {
		this.codeTableMap = codeTableMap;
	}

}

package chenxiaowen.tool.pdm.pojo;

import java.util.ArrayList;

import org.apache.commons.collections.CollectionUtils;

public class Table {
	private String id;
	private String name;
	private String code;
	private String creationDate;
	private String modificationDate;
	private ArrayList<Column> columns;
	private String pkFieldCode;
	

	@Override
	public String toString() {
		return "Table " +
				"{id: " + id 
				+ ", name: " + name 
				+ ", code: " + code
				+ ", creationDate: " + creationDate
				+ ", modificationDate: " + modificationDate
				+ ", columns size: " + (CollectionUtils.isEmpty(columns)?0:columns.size())
				+ "}";
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getCreationDate() {
		return creationDate;
	}

	public void setCreationDate(String creationDate) {
		this.creationDate = creationDate;
	}

	public String getModificationDate() {
		return modificationDate;
	}

	public void setModificationDate(String modificationDate) {
		this.modificationDate = modificationDate;
	}

	public String getPkFieldCode() {
		return pkFieldCode;
	}

	public void setPkFieldCode(String pkFieldCode) {
		this.pkFieldCode = pkFieldCode;
	}

	public ArrayList<Column> getColumns() {
		return columns;
	}

	public void setColumns(ArrayList<Column> columns) {
		this.columns = columns;
	}

}

package chenxiaowen.tool.pdm.pojo;

import java.util.ArrayList;

import org.apache.commons.collections.CollectionUtils;

/**
 * pdm文件的模块
 * @author 陈小稳 [email protected]
 *
 */
public class PhysicalDiagram {
	private String name;
	private String code;
	private String id;
	private ArrayList<String> tableIds;
	@Override
	public String toString() {
		return "PhysicalDiagram {id: " + id 
				+ ", name: " + name 
				+ ", code: " + code
				+ ", tables in package: " + (CollectionUtils.isEmpty(tableIds)?0:tableIds.size())
				+ "}";
	}

	public ArrayList<String> getTableIds() {
		return tableIds;
	}

	public void setTableIds(ArrayList<String> tableIds) {
		this.tableIds = tableIds;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

}


package chenxiaowen.tool.pdm.pojo;

public class Column {
	private String id;
	private String name;
	private String code;
	private String creationDate;
	private String modificationDate;
	private String type;
	private Integer length;
	private Boolean pkFlag;

	@Override
	public String toString() {
		return "Column {id: " + id + ", name: " + name + ", code: " + code
				+ ", creationDate: " + creationDate + ", modificationDate: "
				+ modificationDate + "}";
	}

	public String getCreationDate() {
		return creationDate;
	}

	public void setCreationDate(String creationDate) {
		this.creationDate = creationDate;
	}

	public String getModificationDate() {
		return modificationDate;
	}

	public void setModificationDate(String modificationDate) {
		this.modificationDate = modificationDate;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public Integer getLength() {
		return length;
	}

	public void setLength(Integer length) {
		this.length = length;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public Boolean getPkFlag() {
		return pkFlag;
	}

	public void setPkFlag(Boolean pkFlag) {
		this.pkFlag = pkFlag;
	}
}

猜你喜欢

转载自ccxw1983.iteye.com/blog/2344549