⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 configuration.java

📁 软件设计课做的一个类似Hibernate的O/R Mapping的框架
💻 JAVA
字号:
package cn.edu.nju.software.sd.torm.cfg;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import cn.edu.nju.software.sd.torm.PersistenceException;
import cn.edu.nju.software.sd.torm.PersistenceManager;
import cn.edu.nju.software.sd.torm.exception.MappingException;
import cn.edu.nju.software.sd.torm.impl.DefaultPersistenceManager;
import cn.edu.nju.software.sd.torm.impl.MySQLPersistenceManager;
import cn.edu.nju.software.sd.torm.impl.SQLServerPersistenceManager;

/**
 * An instance of Configuration allows the application to specify properties and
 * mapping documents to be used when creating a PersistenceManager. There is a
 * static instance of Configuration in the PersistenceManager. It reads the
 * configure file specified by the user(or use the default file "torm.cfg.xml"
 * at the root directory if the user dosen't specify a configure file) and do
 * the basic class mapping work. And then return a instance of
 * PersistenceManager.
 * 
 * @author Yinfei XU
 * @version 1.0.0
 */
public class Configuration {

	/**
	 * the map used to store the persistentable classes and the corresponding
	 * class information.
	 */
	private Map<Class, PersistenceClass> classMap;

	/**
	 * configuration properties
	 */
	private Map<String, String> configuration;

	/**
	 * Create a new instance of Configuration class. After initializing it, you
	 * should called its configure() method first and then call the
	 * createPersistenceManager() to get the instance of PersistenceManager.
	 */
	public Configuration() {
		classMap = new HashMap<Class, PersistenceClass>();
		configuration = new HashMap<String, String>();
	}

	/**
	 * Do the basic configurations using the default configure file
	 * "/torm.cfg.xml". This will determine the database to be used and all the
	 * persistentable classes to be added.
	 * 
	 * @return The Configuration object itself.
	 */
	public Configuration configure() {
		return configure("/torm.cfg.xml");
	}

	/**
	 * Do the basic configurations using the configure file specified by
	 * cfgfile. This will determine the database to be used and all the
	 * persistentable classes to be added.
	 * 
	 * @return The Configuration object itself.
	 */
	public Configuration configure(String cfgfile) {
		InputStream stream = getResourceAsStream(cfgfile);
		try {
			Document doc = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder().parse(stream);
			doConfigure(doc);
		} catch (SAXException e) {
			throw new MappingException(
					"Failed to Convert the Torm class configuration file");
		} catch (IOException e) {
			throw new MappingException(
					"Failed to read the Torm class configuration file ");
		} catch (ParserConfigurationException e) {
			throw new MappingException(
					"Failed to Convert the Torm class configuration file");
		}
		return this;
	}

	/**
	 * Get the instance of PersistenceManager. This method must be called after
	 * the call to configure().
	 * 
	 * @return An instance of PersistenceManager.
	 */
	public PersistenceManager createPersistenceManager() {
		String name = configuration.get("torm.dialect");
		if(name.toLowerCase().trim().equals("mysql"))
			return new MySQLPersistenceManager();
		else if(name.toLowerCase().trim().equals("sqlserver"))
			return new SQLServerPersistenceManager();
		return new DefaultPersistenceManager();
	}

	/**
	 * Get the Map which contains the information of all the persistentable
	 * classes.
	 * 
	 * @return The Map which contains the information of all the persistentable
	 *         classes.
	 */
	public Map<Class, PersistenceClass> getClassMap() {
		return classMap;
	}

	public Map<String, String> getConfiguration(){
		return this.configuration;
	}
	/**
	 * Add all the class information to the classMap. All this classes are
	 * presented in the xml file specified by xmlfile.
	 * 
	 * @param xmlfile
	 *            The xml file which contains the configure information of the
	 *            classes.
	 * @return The Configuration object itself.
	 * @throws MappingException
	 *             It is throwed if there are some unexpected information in the
	 *             file.
	 */
	public Configuration addClass(String xmlfile) throws MappingException {
		InputStream stream = getResourceAsStream(xmlfile);

		try {
			Document doc = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder().parse(stream);
			addClass(doc);
		} catch (SAXException e) {
			throw new MappingException(
					"Failed to Convert the Torm class configuration file");
		} catch (IOException e) {
			throw new MappingException(
					"Failed to read the Torm class configuration file ");
		} catch (ParserConfigurationException e) {
			throw new MappingException(
					"Failed to Convert the Torm class configuration file");
		}
		return this;
	}

	private InputStream getResourceAsStream(String resource)
			throws MappingException {
		String stripped = resource.startsWith("/") ? resource.substring(1)
				: resource;

		InputStream stream = null;
		ClassLoader classLoader = Thread.currentThread()
				.getContextClassLoader();
		if (classLoader != null) {
			stream = classLoader.getResourceAsStream(stripped);
		}
		if (stream == null) {
			throw new PersistenceException(resource + " not found");
		}
		return stream;
	}

	private void addClass(Document doc) {
		String packageName = "";
		NodeList list = doc.getElementsByTagName("torm-mapping");
		if (list.getLength() != 0) {
			Node n = list.item(0);
			if (n.getNodeType() == Node.ELEMENT_NODE) {
				Element root = (Element) n;
				packageName = root.getAttribute("package").trim();
				if (packageName.length() != 0)
					packageName += ".";
				NodeList classList = root.getElementsByTagName("class");
				for (int i = 0; i < classList.getLength(); i++) {
					Node nn = classList.item(i);
					if (nn.getNodeType() == Node.ELEMENT_NODE) {
						Element classElement = (Element) nn;
						String className = packageName
								+ classElement.getAttribute("name").trim();
						String tableName = classElement.getAttribute("table")
								.trim();
						Element idElement = ((Element) classElement
								.getElementsByTagName("id").item(0));
						int typeValue;
						try {
							typeValue = java.sql.Types.class.getField(
									idElement.getAttribute("type")
											.toUpperCase().trim()).getInt(null);
						} catch (Exception e) {
							e.printStackTrace();
							throw new MappingException(
									"Failed to Convert the Torm class configuration file");
						}
						NodeList genList = idElement
								.getElementsByTagName("generator");
						String generatorName = "increment";
						if (genList.getLength() != 0) {
							generatorName = ((Element) genList.item(0))
									.getAttribute("generator");
						}
						PersistenceProperty idProperty = new PersistenceProperty(
								idElement.getAttribute("name").trim(),
								idElement.getAttribute("column").trim(),
								typeValue);
						NodeList propertyList = classElement
								.getElementsByTagName("property");
						LinkedList<PersistenceProperty> pList = new LinkedList<PersistenceProperty>();
						for (int m = 0; m < propertyList.getLength(); m++) {
							Element propertyElement = ((Element) propertyList
									.item(m));
							try {
								typeValue = java.sql.Types.class.getField(
										propertyElement.getAttribute("type")
												.toUpperCase().trim()).getInt(
										null);
								PersistenceProperty p = new PersistenceProperty(
										propertyElement.getAttribute("name")
												.trim(), propertyElement
												.getAttribute("column").trim(),
										typeValue);
								String notnull = propertyElement
										.getAttribute("not_null");
								if (notnull != null
										&& notnull.trim().equals("true"))
									p.setNotNull(true);
								pList.addLast(p);
							} catch (Exception e) {
								throw new MappingException(
										"Failed to Convert the Torm class configuration file");
							}
						}
						PersistenceClass pClass = new PersistenceClass();
						pClass.setClassName(className);
						pClass.setID(idProperty);
						pClass.setTableName(tableName);
						pClass.setProperties(pList);
						pClass.setGeneratorName(generatorName);
						try {
							this.classMap.put(Class.forName(className), pClass);
						} catch (ClassNotFoundException e) {
							throw new MappingException("Class Not Found : "
									+ className);
						}
						return;
					}
				}
			}
		}
		throw new MappingException(
				"Failed to Convert the Torm class configuration file");
	}

	private void doConfigure(Document doc) {
		NodeList list = doc.getElementsByTagName("torm-configuration");
		if (list.getLength() != 0) {
			Node n = list.item(0);
			if (n.getNodeType() == Node.ELEMENT_NODE) {
				Element root = (Element) n;
				NodeList propertyList = root.getElementsByTagName("property");
				for (int i = 0; i < propertyList.getLength(); i++) {
					Node nn = propertyList.item(i);
					if (nn.getNodeType() == Node.ELEMENT_NODE) {
						Element propertyElement = (Element) nn;
						configuration.put(propertyElement.getAttribute("name")
								.trim(), propertyElement.getFirstChild()
								.getNodeValue().trim());
					}
				}
				NodeList srcList = root.getElementsByTagName("mapping");
				for (int i = 0; i < srcList.getLength(); i++) {
					Node nn = srcList.item(i);
					if (nn.getNodeType() == Node.ELEMENT_NODE) {
						Element srcElement = (Element) nn;
						addClass(srcElement.getAttribute("resource").trim());
					}
				}
				
				return;
			}
		}
		throw new MappingException(
				"Failed to Convert the Torm class configuration file");
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -