package org.positrium.waket;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.digester.Digester;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.SAXException;

/**
 * It loads XML file, and converts to object.
 * 
 * @author token , 2009 CC BY-SA
 * @version $Rev: 121 $
 */
public class XMLConfigLoader {
	public static Log logger = LogFactory.getLog(XMLConfigLoader.class);
	
	private MapContainer bean = MapContainer.Null;

	public MapContainer getMap() {
		return bean;
	}

	/**
	 * @param xmlconfig
	 * @throws IOException
	 * @throws SAXException
	 */
	public XMLConfigLoader(File xmlconfig){
		Digester dgt = new Digester();
		dgt.setValidating(true);
		// dgt.push(this);

		// If the element is server, this create MapContainer object.
		dgt.addObjectCreate("dataserver", MapContainer.class);

		// If the element is server/mapping, this create URLMap object.
		dgt.addObjectCreate("dataserver/mapping", URLMap.class);
		dgt.addSetNext("dataserver/mapping", "addURLMap");

		// If these elements appeared, each values into URLMap#setXXX.
		dgt.addBeanPropertySetter("dataserver/mapping/url");
		dgt.addBeanPropertySetter("dataserver/mapping/classname");

		try{
			bean = (MapContainer) dgt.parse(xmlconfig);
		} catch(FileNotFoundException e) {
			logger.warn("Error Occurs: "+xmlconfig.getAbsolutePath()+" is not found.");
		} catch(IOException e){
			logger.error("Error Occurs: ",e);
		} catch(SAXException e){
			logger.error("Error Occurs: ",e);
		}
	}
}
