krysalis-update/src/java/org/krysalis/depot/update/util/xml IXMLAttribute.java,NONE,1.1 XMLGrouperElement.java,NONE,1.1 XMLEntryTable.java,NONE,1.1 XMLContext.java,NONE,1.1 XMLHandler.java,NONE,1.1 XMLException.java,NONE,1.1 XMLTagConstants.java,NONE,1.1 XMLParser.java,NONE,1.1

Nick Chalko <[email protected]> Wed, 08 Dec 2004 09:06:31 +0000
Newsgroups gmane.comp.krysalis.cvs
Message-ID <[email protected]>
Update of /cvsroot/krysalis/krysalis-update/src/java/org/krysalis/depot/update/util/xml
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24726/src/java/org/krysalis/depot/update/util/xml

Added Files:
	IXMLAttribute.java XMLGrouperElement.java XMLEntryTable.java 
	XMLContext.java XMLHandler.java XMLException.java 
	XMLTagConstants.java XMLParser.java 
Log Message:
Copied from the apache incubator.

--- NEW FILE: XMLGrouperElement.java ---
/*
 * Copyright  2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.krysalis.depot.update.util.xml;

/**
 * @author anou_mana
 */
public class XMLGrouperElement {
	public static final String XML_GROUPER_ELEMENT_CLASSNAME =
		XMLGrouperElement.class.getName();

	/**
	 * 
	 */
	public XMLGrouperElement() {
		super();
	}
}

--- NEW FILE: XMLTagConstants.java ---
/*
 * Copyright  2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.krysalis.depot.update.util.xml;

/**
 * @author anou_mana
 */
public class XMLTagConstants {
	public final static String XML_TAG_ID = "id";
	public final static String XML_TAG_REF_ID = "refId";

	// XML tags
	public final static String CONFIG_TAG = "config";
	public final static String PROPERTY_XML_TAG = "property";
	public final static String REPOSITORY_TAG = "repository";
	public final static String REPOSITORY_URL_TAG = "repository.url";
	public final static String REPOSITORY_ACTIVE_TAG = "repository.active";
	public final static String REPOSITORY_REMOTE_TAG = "repository.remote";
	public final static String REPOSITORYSET_TAG = "repositoryset";

	// Attributes
	public final static String XML_CLASS_ATTRIBUTE = "class";

	/**
	 * 
	 */
	public XMLTagConstants() {
		super();
		// TODO Auto-generated constructor stub
	}
}

--- NEW FILE: XMLEntryTable.java ---
/*
 * Copyright  2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.krysalis.depot.update.util.xml;

import java.util.HashMap;

/**
 * Implementation to store xml configuration tags and values in the provided classes. These classes
 * can be provided through the xml-tag "class". Some standard-Classes are normally provided by the
 * sub-classes 
 * 
 * @author <a href="http://incubator.apache.org/depot">The Apache Incubator Depot Project</a>
 */
public class XMLEntryTable 
{
	protected HashMap m_entryToClassMap = new HashMap();

	/**
	 * Constructor
	 */
	public XMLEntryTable()
	{
		super();
	}

	public void put(String entry, Class clazz)
	{
		this.m_entryToClassMap.put(entry, clazz);
	}
	
	public void put(String entry, String className) throws Exception
	{
		this.m_entryToClassMap.put(entry, className);
	}
	
	public Object get(String entry)
	{
		return this.m_entryToClassMap.get(entry);
	}
	
	/**
	 * This returns the Class to the given entry
	 * 
	 * @param entry
	 * @return
	 */
	public Object getClass(String entry)
	{
		return this.m_entryToClassMap.get(entry);
	}
}
--- NEW FILE: XMLHandler.java ---
/*
 * Copyright  2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.krysalis.depot.update.util.xml;

import java.lang.reflect.Method;
import java.util.Stack;

import org.krysalis.depot.update.impl.ReferenceManager;
import org.krysalis.depot.update.util.text.MessageConstants;
import org.krysalis.depot.update.util.text.Messages;
import org.krysalis.depot.common.log.Logger;
import org.krysalis.depot.common.util.envsafe.ClassLoaderContext;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * @author anou_mana
 */
public class XMLHandler extends DefaultHandler {

	private Stack m_tagObjectStack = new Stack();
	private Object m_currentTagObject;
	private ClassLoaderContext m_classLoaderHelper = null;

	private XMLContext m_context;
	private XMLEntryTable m_xmlEntryTable;

	public XMLHandler(XMLContext context) {
		m_context = context;
		m_xmlEntryTable = new XMLEntryTable();
	}

	public XMLHandler(XMLContext context, XMLEntryTable xmlEntryTable, ClassLoaderContext loaderHelper) {
		m_context = context;
		m_xmlEntryTable = xmlEntryTable;
		m_classLoaderHelper = loaderHelper;
	}

	public Object getCurrentTagObject() {
		return m_currentTagObject;
	}

	public void startElement(
		String uri,
		String tag,
		String qname,
		Attributes attributes)
		throws SAXParseException {
		try {
			
			Logger.getLogger().debug("startElement : " + qname);

			if (tag.equals(XMLTagConstants.PROPERTY_XML_TAG)) {
				// add the property to the xmlEntryTable
				setAttributesToEntryTable(attributes);
			}
			else {
				// handle the case where the class is different from the one in xmltable
				String classAttributeName =
					attributes.getValue(XMLTagConstants.XML_CLASS_ATTRIBUTE);
				
				String clazzName = null;
				
				// find out if the tag - class is defined in the depot-update.xml / XMLEntryTable
				if (classAttributeName != null
					&& !classAttributeName.equals("")){
						clazzName = classAttributeName;
				}
				else{
					clazzName = (String) m_xmlEntryTable.get(tag);
				}

				if (null != clazzName)

					Logger.getLogger().debug("Class : " + clazzName);
				
					// if it is the XMLGrouperElement
					if (!clazzName
						.equals(
							XMLGrouperElement.XML_GROUPER_ELEMENT_CLASSNAME)) {
						Object currentTagObject = null;
						Class clazz =
							m_classLoaderHelper.getClassForName(clazzName);

						String tagId =
							attributes.getValue(XMLTagConstants.XML_TAG_ID);
						String refId =
							attributes.getValue(XMLTagConstants.XML_TAG_REF_ID);

						Logger.getLogger().debug("TagId : " + tagId);
						Logger.getLogger().debug("RefId : " + refId);
						
						if (tagId == null) {
							throw new Exception(
								"No Id for the xml entry " + tag);
						}

						//if there is an object already in the stack, add this as child to it
						if (!m_tagObjectStack.empty()) {
							Object parent = this.m_tagObjectStack.peek();
							if (parent != null) {
								
								/// TODO *** 
								currentTagObject =
									setChild(parent, clazz, tagId, refId);
								if (currentTagObject == null) {
									throw new Exception(
										"Unexpected child \""
											+ qname
											+ "\" "
											+ tag
											+ " for the parent element "
											+ parent.getClass().getName());
								}
							}
							else {
								// parent is null so call the ref Mgr and create a ref
								currentTagObject =
									ReferenceManager.createReferenceObject(
										clazz,
										tagId,
										refId);
							}
						}
						else {
							// create the object
							currentTagObject =
								ReferenceManager.createReferenceObject(
									clazz,
									tagId,
									refId);

						}
						if (currentTagObject == null) {
							//TODO
							String message = "No tagObject " + tag;
							throw new Exception(message);
						}

						//set the attributes
						setObjectAttributes(tag, currentTagObject, attributes);

						// add this to stack and the created objects
						this.m_tagObjectStack.push(currentTagObject);
						this.m_context.putCreatedTagObject(
							tag,
							currentTagObject);
					}
			}
		}
		catch (Exception exception) {
			Logger.getLogger().error("XML_BEAN_ERROR", exception);
			
			throw new SAXParseException(
				exception.getLocalizedMessage(),
				m_context.getLocator(),
				exception);
		}

	}

	private void setAttributesToEntryTable(Attributes attributes)
		throws Exception {
		for (int j = 0; j < attributes.getLength(); j++) {
			String attributeName = attributes.getLocalName(j);
			String attributeValue = attributes.getValue(j);

			// add it to the entrytable
			this.m_xmlEntryTable.put(attributeName, attributeValue);
		}
	}

	private Object setChild(
		Object parent,
		Class childClass,
		String tagId,
		String refId)
		throws Exception {
		Object childObject = null;
		/*String childName = childClass.getName();
		int index = childName.lastIndexOf(".");
		if (index != -1) {
			childName = childName.substring(index + 1, childName.length());
		}*/

		// introspect to see if there is a method with this childName
		Class clazz = parent.getClass();
		Method[] methods = clazz.getMethods();

		for (int i = 0; i < methods.length; i++) {
			final Method method = methods[i];
			final String methodName = method.getName();
			Class returnType = method.getReturnType();
			Class[] parameters = method.getParameterTypes();

			if (parameters.length == 3
				&& methodName.startsWith("createChild")) {
					
					//TODO **** going wrong in the child class
				childObject =
					method.invoke(
						parent,
						new Object[] { childClass, tagId, refId });

				// log it 
				Logger.getLogger().debug(
					"Child :"
						+ childClass.getName()
						+ " is set, for the Parent "
						+ clazz.getName());

				// jump out of the loop
				i = methods.length;
			}
		}
		return childObject;
	}

	private boolean setMethods(
		Object tagObject,
		Object attribute,
		Object attributeValue)
		throws Exception {
		// introspect to see if there is a method with this attribute Name
		Class clazz = tagObject.getClass();
		Method[] methods = clazz.getMethods();
		boolean attributeSet = false;
		String attributeName = null;

		if (attribute instanceof String) {
			attributeName = (String) attribute;
		}
		else {
			attributeName = getClassNameWithoutPackage(attribute);
		}

		for (int i = 0; i < methods.length; i++) {
			final Method method = methods[i];
			final String methodName = method.getName();
			Class returnType = method.getReturnType();
			Class[] parameters = method.getParameterTypes();

			// check of setXyz(Class) pattern
			if (java.lang.Void.TYPE.equals(returnType)
				&& methodName.startsWith("set")) {
				// remove the set from the method name 
				String tmp = methodName.substring(3, methodName.length());
				// compare it with attribute name
				if (tmp.equalsIgnoreCase(attributeName)) {

					if (parameters.length == 1
						&& parameters[0] == attributeValue.getClass()) {
						method.invoke(
							tagObject,
							new Object[] { attributeValue });
					}
					else if (parameters.length == 2) {
						method.invoke(
							tagObject,
							new Object[] { attribute, attributeValue });
					}
					// log it 
					Logger.getLogger().debug(
						"Attribute :" + attributeName + " is set");
					attributeSet = true;

					// jump out of the loop
					i = methods.length;
				}
			}
		}
		return attributeSet;
	}

	private void setObjectAttributes(
		String tag,
		Object tagObject,
		Attributes attributes)
		throws Exception {
		// introspect to see if there is a method with this attribute Name
		Class clazz = tagObject.getClass();
		Method[] methods = clazz.getMethods();

		for (int j = 0; j < attributes.getLength(); j++) {
			String attributeName = attributes.getLocalName(j);
			Object attributeValue = attributes.getValue(j);
			Object attribute = attributeName;
			// tag, ref id and class attributes are already handled
			if (attributeName != XMLTagConstants.XML_TAG_ID
				&& attributeName != XMLTagConstants.XML_TAG_REF_ID
				&& attributeName != XMLTagConstants.XML_CLASS_ATTRIBUTE) {
				//check the xmlEntryTable to see if there are any class names
				// for the attributes
				String attributeClassName =
					(String) this.m_xmlEntryTable.get(
						tag + "." + attributeName);

				Object objectAttributeValue = null;
				if (attributeClassName != null
					&& !attributeClassName.equals("")) {

					// if there is a class name, load a class
					Class attributeClass =
					m_classLoaderHelper.getClassForName(attributeClassName);

					objectAttributeValue =
						ReferenceManager.createObject(
							attributeClass,
							attributeName,
							null);

					if (objectAttributeValue != null) {
						if (!(objectAttributeValue instanceof IXMLAttribute)) {
							objectAttributeValue =
								ReferenceManager.createObject(
									attributeClass,
									(String) attributeValue,
									null);

							attributeValue = objectAttributeValue;
							attribute =
								getClassNameWithoutPackage(attributeClassName);
						}
						else {
							attribute = objectAttributeValue;
						}
					}
				}
				// invoke the setMethod if Found 
				boolean attributeSet =
					setMethods(tagObject, attribute, attributeValue);

				if (!attributeSet) {
					Logger.getLogger().error(
						"Attribute :"
							+ attributeName
							+ " is not available in the class :"
							+ clazz.getName());
				}
			}
		}
	}

	private String getClassNameWithoutPackage(Object object) {
		return getClassNameWithoutPackage(object.getClass().getName());
	}

	private String getClassNameWithoutPackage(String pkgClassName) {
		int index = pkgClassName.lastIndexOf(".");
		if (index != -1) {
			pkgClassName =
				pkgClassName.substring(index + 1, pkgClassName.length());
		}
		return pkgClassName;

	}
	/**
	 * Sets the locator in the project helper for future reference.
	 *
	 * @param locator The locator used by the parser.
	 *                Will not be <code>null</code>.
	 */
	public void setDocumentLocator(Locator locator) {
		m_context.setLocator(locator);
	}

	/**
	 * @param uri  The namespace URI for this element.
	 * @param name The name of the element which is ending.
	 *             Will not be <code>null</code>.
	 * @param qName The qualified name for this element.
	 *
	 * @exception SAXException in case of error (not thrown in
	 *                         this implementation)
	 *
	 */
	public void endElement(String uri, String name, String qName)
		throws SAXException {
		try {

			// find out if the tag - class is defined in the XMLEntryTable
			String clazzName = (String) m_xmlEntryTable.get(name);
			if (null != clazzName)
				// if it is the XMLGrouperElement
				if (!clazzName
					.equals(XMLGrouperElement.XML_GROUPER_ELEMENT_CLASSNAME)) {
					// pop the element out of the stack
					m_tagObjectStack.pop();
				}
		}
		catch (Exception exception) {
			Logger.getLogger().error(Messages.getString(MessageConstants.XML_BEAN_ERROR), exception);
			throw new SAXParseException(
				exception.getLocalizedMessage(),
				m_context.getLocator(),
				exception);
		}
	}

	/**
	 * @param buf  A character array of the test.
	 * @param start The start offset in the array.
	 * @param count The number of characters to read.
	 * @exception SAXParseException if an error occurs
	 */
	public void characters(char[] buf, int start, int count)
		throws SAXParseException {

	}

	/**
	 * Start a namespace prefix to uri mapping
	 *
	 * @param prefix the namespace prefix
	 * @param uri the namespace uri
	 */
	public void startPrefixMapping(String prefix, String uri) {
		m_context.startPrefixMapping(prefix, uri);
	}

	/**
	 * End a namepace prefix to uri mapping
	 *
	 * @param prefix the prefix that is not mapped anymore
	 */
	public void endPrefixMapping(String prefix) {
		m_context.endPrefixMapping(prefix);
	}
	/**
	 * @return
	 */
	public XMLContext getContext() {
		return m_context;
	}

	/**
	 * @return
	 */
	public Stack getTagObjectStack() {
		return m_tagObjectStack;
	}

	/**
	 * @return
	 */
	public XMLEntryTable getXmlEntryTable() {
		return m_xmlEntryTable;
	}

	/**
	 * @param context
	 */
	public void setContext(XMLContext context) {
		m_context = context;
	}

	/**
	 * @param object
	 */
	public void setCurrentTagObject(Object object) {
		m_currentTagObject = object;
	}

	/**
	 * @param stack
	 */
	public void setTagObjectStack(Stack stack) {
		m_tagObjectStack = stack;
	}

	/**
	 * @param table
	 */
	public void setXmlEntryTable(XMLEntryTable table) {
		m_xmlEntryTable = table;
	}

}

--- NEW FILE: XMLContext.java ---
/*
 * Copyright  2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.krysalis.depot.update.util.xml;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.xml.sax.Locator;

/**
 * @author anou_mana
 */
public class XMLContext
{
	/**
	 * Locator for the configuration file parser.
	 * Used for giving locations of errors etc.
	 */
	private Locator locator;

	/** Keeps track of prefix -> uri mapping during parsing */
	private Map prefixMapping = new HashMap();

	File m_buildFile = null;
	
	private HashMap m_createdTagObjects = new HashMap();
	
	/**
	 * 
	 */
	public XMLContext()
	{
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * access the locator
	 * @return locator
	 */
	public Locator getLocator() {
		return locator;
	}

	/**
	 * sets the locator
	 * @param locator locator
	 */
	public void setLocator(Locator locator) {
		this.locator = locator;
	}

	/**
	 * Called during parsing, stores the prefix to uri mapping.
	 *
	 * @param prefix a namespace prefix
	 * @param uri    a namespace uri
	 */
	public void startPrefixMapping(String prefix, String uri) {
		List list = (List) prefixMapping.get(prefix);
		if (list == null) {
			list = new ArrayList();
			prefixMapping.put(prefix, list);
		}
		list.add(uri);
	}

	/**
	 * End of prefix to uri mapping.
	 *
	 * @param prefix the namespace prefix
	 */
	public void endPrefixMapping(String prefix) {
		List list = (List) prefixMapping.get(prefix);
		if (list == null || list.size() == 0) {
			return; // Should not happen
		}
		list.remove(list.size() - 1);
	}

	/**
	 * prefix to namespace uri mapping
	 *
	 * @param prefix the prefix to map
	 * @return the uri for this prefix, null if not present
	 */
	public String getPrefixMapping(String prefix) {
		List list = (List) prefixMapping.get(prefix);
		if (list == null || list.size() == 0) {
			return null;
		}
		return (String) list.get(list.size() - 1);
	}

	/**
	 * @return
	 */
	public File getBuildFile()
	{
		return m_buildFile;
	}

	/**
	 * @param file
	 */
	public void setBuildFile(File file)
	{
		m_buildFile = file;
	}

	/**
	 * @return
	 */
	public HashMap getCreatedTagObjects()
	{
		return m_createdTagObjects;
	}

	/**
	 * @param map
	 */
	public void setCreatedTagObjects(HashMap map)
	{
		m_createdTagObjects = map;
	}

	public Object getCreatedTagObject(String tagName)
	{
		return this.m_createdTagObjects.get(tagName);
	}
	
	public void putCreatedTagObject(String tagName, Object tagObject)
	{
		this.m_createdTagObjects.put(tagName, tagObject);
	}
}

--- NEW FILE: IXMLAttribute.java ---
/*
 * Copyright  2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.krysalis.depot.update.util.xml;

/**
 * @author anou_mana
 */
public interface IXMLAttribute {

}

--- NEW FILE: XMLParser.java ---
/*
 * Copyright  2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.krysalis.depot.update.util.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.xml.parsers.SAXParserFactory;

import org.krysalis.depot.update.util.io.FileUtils;
import org.krysalis.depot.common.util.envsafe.ClassLoaderContext;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

/**
 * Parser for xml-configuration files
 * 
 * @author <a href="http://incubator.apache.org/depot">The Apache Incubator Depot Project</a>
 */
public class XMLParser {
	private XMLEntryTable m_xmlEntryTable;
	private ClassLoaderContext m_classLoaderHelper;

	/**
	 * Constructor for the XMLParser
	 * 
	 * @param xmlEntryTable a XMLEntryTable
	 * @param loaderHelper a ClassLoaderContext
	 */
	public XMLParser(
		XMLEntryTable xmlEntryTable,
		ClassLoaderContext loaderHelper) {

		m_xmlEntryTable = xmlEntryTable;
		m_classLoaderHelper = loaderHelper;
	}

	public XMLContext parse(URL source) throws XMLException {
		XMLContext xmlContext = new XMLContext();

		return parse(
			source,
			new XMLHandler(xmlContext, m_xmlEntryTable, m_classLoaderHelper));
	}
	/**
	 * Parse a source xml input.
	 *
	 * @param source  the xml source
	 * @exception XMLException if an error occurs
	 */
	public XMLContext parse(Object source) throws XMLException {
		XMLContext xmlContext = new XMLContext();
		return parse(
			source,
			new XMLHandler(xmlContext, m_xmlEntryTable, m_classLoaderHelper));
	}

	/**
	 * @param source  the xml source
	 * @param handler the root handler to use (contains the current context)
	 * @exception XMLException if the configuration is invalid or cannot
	 *                           be read
	 */
	public XMLContext parse(Object source, XMLHandler handler)
		throws XMLException {

		XMLContext xmlContext = handler.getContext();

		File buildFile = null;
		URL url = null;
		String buildFileName = null;

		if (source instanceof File) {
			buildFile = (File) source;
			xmlContext.setBuildFile(buildFile);
			buildFileName = buildFile.toString();
		}
		else if (source instanceof URL) {
			url = (URL) source;
			buildFileName = url.toString();
		}
		else if (!(source instanceof InputStream)) {
			throw new XMLException(
				"Source " + source.getClass().getName() + " not supported");
		}

		InputStream inputStream = null;
		InputSource inputSource = null;

		try {
			/**
			 * SAX 2 style parser used to parse the given file.
			 */
			SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
			saxParserFactory.setNamespaceAware(true);

			XMLReader parser = saxParserFactory.newSAXParser().getXMLReader();

			if (null == parser)
				throw new XMLException("Failed to load XMLReader");

			String uri = null;
			if (buildFile != null) {
				uri = FileUtils.toURI(buildFile.getPath());
				inputStream = new FileInputStream(buildFile);
			}
			else if (url != null) {
				inputStream = url.openStream();
				uri = url.toString();
			}
			else {
				inputStream = (InputStream) source;
			}

			inputSource = new InputSource(inputStream);
			if (uri != null) {
				inputSource.setSystemId(uri);
			}

			parser.setContentHandler(handler);
			parser.setContentHandler(handler);
			parser.setEntityResolver(handler);
			parser.setErrorHandler(handler);
			parser.setDTDHandler(handler);
			parser.parse(inputSource);
		}
		catch (Exception exc) {
			throw new XMLException(exc.getLocalizedMessage(), exc);
		}
		finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				}
				catch (IOException ioe) {
					// ignore this
				}
			}
		}
		return xmlContext;

	}

}

--- NEW FILE: XMLException.java ---
/*
 * Copyright  2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.krysalis.depot.update.util.xml;

import org.krysalis.depot.update.UpdateException;

/**
 * @author anou_mana
 */
public class XMLException extends UpdateException {

	/**
	 * @param message
	 */
	public XMLException(String message) {
		super(message);
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param message
	 * @param throwable
	 */
	public XMLException(String message, Throwable throwable) {
		super(message, throwable);
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param throwable
	 */
	public XMLException(Throwable throwable) {
		super(throwable);
		// TODO Auto-generated constructor stub
	}
}



-------------------------------------------------------
SF email is sponsored by - The IT Product Guide
Read honest & candid reviews on hundreds of IT Products from real users.
Discover which products truly live up to the hype. Start reading now. 
http://productguide.itmanagersjournal.com/