package org.jerrymouse.database.hadoop.jpa;

import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class PersistenceXMLReader {
	private static Log log = LogFactory.getLog(PersistenceXMLReader.class);

	public static Map<String, String> read(String persistenceUnitName, URL url) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(url);
			Element root = document.getRootElement();
			List<Element> persistenceUnits = root.elements();
			for (Element persistenceUnit : persistenceUnits) {
				if (persistenceUnitName.equals(persistenceUnit
						.attributeValue("name"))) {
					List<Element> properties = persistenceUnit.element(
							"properties").elements();
					for (Element property : properties) {
						map.put(property.attributeValue("name"), property
								.attributeValue("value"));
					}
				}
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return map;
	}

}
