Update of /cvsroot/metamorphosis/ruper2/src/java/core/org/krysalis/ruper2/util/xml
In directory sc8-pr-cvs1:/tmp/cvs-serv30481/src/java/core/org/krysalis/ruper2/util/xml
Added Files:
XMLTagConstants.java XMLAttribute.java XMLException.java
XMLHandler.java XMLContext.java XMLEntryTable.java
XMLGrouperElement.java XMLParser.java
Log Message:
Avoid clash with existing Ruper...
--- NEW FILE: XMLTagConstants.java ---
/*
* Created on Sep 10, 2003
*/
package org.krysalis.ruper2.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
}
public static void main(String[] args)
{
}
}
--- NEW FILE: XMLAttribute.java ---
/*
* Created on Sep 12, 2003
*/
package org.krysalis.ruper2.util.xml;
/**
* @author anou_mana
*/
public interface XMLAttribute {
}
--- NEW FILE: XMLException.java ---
/*
* Created on Sep 4, 2003
*/
package org.krysalis.ruper2.util.xml;
import org.krysalis.ruper2.RuperException;
/**
* @author anou_mana
*/
public class XMLException extends RuperException {
/**
* @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
}
}
--- NEW FILE: XMLHandler.java ---
/*
* Created on Sep 3, 2003
*/
package org.krysalis.ruper2.util.xml;
import java.lang.reflect.Method;
import java.util.Stack;
import org.krysalis.ruper2.impl.ReferenceManager;
import org.krysalis.ruper2.log.Logger;
import org.krysalis.ruper2.util.ClassLoaderHelper;
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 XMLContext m_context;
private XMLEntryTable m_xmlEntryTable;
public XMLHandler(XMLContext context) {
m_context = context;
m_xmlEntryTable = new XMLEntryTable();
}
public XMLHandler(XMLContext context, XMLEntryTable xmlEntryTable) {
m_context = context;
m_xmlEntryTable = xmlEntryTable;
}
public Object getCurrentTagObject() {
return m_currentTagObject;
}
public void startElement(
String uri,
String tag,
String qname,
Attributes attributes)
throws SAXParseException {
try {
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);
if (classAttributeName != null
&& !classAttributeName.equals(""))
m_xmlEntryTable.put(tag, classAttributeName);
// find out if the tag - class is defined in the XMLEntryTable
String clazzName = (String) m_xmlEntryTable.get(tag);
//:TODO: log this?
if (null != clazzName)
// if it is the XMLGrouperElement
if (!clazzName
.equals(
XMLGrouperElement.XML_GROUPER_ELEMENT_CLASSNAME)) {
Object currentTagObject = null;
Class clazz =
ClassLoaderHelper.getClassForName(clazzName);
String tagId =
attributes.getValue(XMLTagConstants.XML_TAG_ID);
String refId =
attributes.getValue(XMLTagConstants.XML_TAG_REF_ID);
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) {
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.getLog().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")) {
childObject =
method.invoke(
parent,
new Object[] { childClass, tagId, refId });
// log it
Logger.getLog().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.getLog().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 =
ClassLoaderHelper.getClassForName(attributeClassName);
objectAttributeValue =
ReferenceManager.createObject(
attributeClass,
attributeName,
null);
if (objectAttributeValue != null) {
if (!(objectAttributeValue instanceof XMLAttribute)) {
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.getLog().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 {
// find out if the tag - class is defined in the XMLEntryTable
String clazzName = (String) m_xmlEntryTable.get(name);
// if it is the XMLGrouperElement
if (!clazzName
.equals(XMLGrouperElement.XML_GROUPER_ELEMENT_CLASSNAME)) {
// pop the element out of the stack
this.m_tagObjectStack.pop();
}
}
/**
* @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 ---
/*
* Created on Sep 3, 2003
*/
package org.krysalis.ruper2.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: XMLEntryTable.java ---
/*
* Created on Sep 2, 2003
*
*/
package org.krysalis.ruper2.util.xml;
import java.util.HashMap;
/**
* @author anou_mana
*/
public class XMLEntryTable
{
protected HashMap m_entryToClassMap = new HashMap();
/**
*
*/
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);
}
public Object getClass(String entry)
{
return this.m_entryToClassMap.get(entry);
}
}
--- NEW FILE: XMLGrouperElement.java ---
/*
* Created on Sep 9, 2003
*/
package org.krysalis.ruper2.util.xml;
/**
* @author anou_mana
*/
public class XMLGrouperElement
{
public static final String XML_GROUPER_ELEMENT_CLASSNAME = XMLGrouperElement.class.getName();
/**
*
*/
public XMLGrouperElement()
{
super();
// TODO Auto-generated constructor stub
}
public static void main(String[] args)
{
}
}
--- NEW FILE: XMLParser.java ---
/*
* Created on Sep 2, 2003
*
*/
package org.krysalis.ruper2.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.xml.sax.InputSource;
import org.xml.sax.XMLReader;
/**
* @author anou_mana
*/
public class XMLParser {
private XMLEntryTable m_xmlEntryTable;
/**
*
*/
public XMLParser(XMLEntryTable xmlEntryTable) {
super();
m_xmlEntryTable = xmlEntryTable;
}
public XMLContext parse(URL source) throws XMLException {
XMLContext xmlContext = new XMLContext();
return parse(source, new XMLHandler(xmlContext, this.m_xmlEntryTable));
}
/**
* 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, this.m_xmlEntryTable));
}
/**
* @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 = buildFile.toURI().toString();
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;
}
}
-------------------------------------------------------
This sf.net email is sponsored by:ThinkGeek
Welcome to geek heaven.
http://thinkgeek.com/sf
lmpx.com only provides a reader for public news (NNTP) servers. It is not
affiliated with the servers or forums shown here and is not responsible for
the content of articles, which is written by their respective authors.