package com.nexirius.framework.datamodel.xml;
import com.nexirius.framework.datamodel.DataModel;
import com.nexirius.framework.datamodel.SimpleModel;
import com.nexirius.framework.datamodel.StructModel;
import com.nexirius.framework.datamodel.ArrayModel;
import com.nexirius.framework.application.ErrorMessageException;
import java.io.OutputStream;
import java.io.IOException;
import java.util.Hashtable;
public class DataModelXmlGenerator {
Hashtable generatorTable = new Hashtable();
int indentLevel = 0;
String charset = "UTF-8";
public static final String ID = "ID";
public DataModelXmlGenerator() {
register(SimpleModel.class, new SimpleModelXmlGenerator());
register(StructModel.class, new StructModelXmlGenerator());
register(ArrayModel.class, new ArrayModelXmlGenerator());
}
public void generateXml(OutputStream out, DataModel model) {
Class clazz = model.getClass();
IXmlGenerator generator = getGenerator(clazz);
if (generator == null) {
throw new ErrorMessageException("No generator for {0}", null, new Object[]{clazz});
} else {
try {
generator.generateXml(this, out, model);
} catch (Exception e) {
throw new ErrorMessageException("Error generating {0}", e, new Object[]{model.toString()});
}
}
}
public void register(Class clazz, IXmlGenerator generator) {
generatorTable.put(clazz, generator);
}
public IXmlGenerator getGenerator(Class clazz) {
while (clazz != null) {
IXmlGenerator gen = (IXmlGenerator) generatorTable.get(clazz);
if (gen != null) {
return gen;
}
clazz = clazz.getSuperclass();
}
return null;
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
public void incrementIndent() {
++indentLevel;
}
public void decrementIndent() {
--indentLevel;
}
public void startTag(OutputStream out, String elementName, String fieldName) throws IOException {
out.write('<');
out.write(elementName.getBytes(getCharset()));
out.write(' ');
out.write(ID.getBytes(getCharset()));
out.write('=');
out.write('"');
out.write(fieldName.getBytes(getCharset()));
out.write('"');
out.write('>');
}
public void endTag(OutputStream out, String elementName) throws IOException {
out.write('<');
out.write('/');
out.write(elementName.getBytes(getCharset()));
out.write('>');
}
public void addText(OutputStream out, String text) throws IOException {
if (text != null) {
out.write(text.getBytes(getCharset()));
}
}
public void indent(OutputStream out) throws IOException {
for (int i = 0; i < indentLevel; ++i) {
out.write('\t');
}
}
public void newLine(OutputStream out) throws IOException {
out.write('\n');
}
}