最近写一个基于xml的解析器,模拟数据库的增删改查操作。但是由于时间原因,还没有完成。
版本一不支持xml的属性、dtd,schema等,不支持复杂查询。
package com.xml;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import com.xml.XmlDao;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
public class XmlDaoImpl
protected static Document doc;
protected Element root;
protected Method[] methods;
protected Field[] fields;
protected String path;
protected File file;
protected Class claz;
protected Object entity = null;
public XmlDaoImpl() {
doc = DocumentHelper.createDocument();
}
public XmlDaoImpl(String path) {
this.path = path;
SAXReader xmlReader = new SAXReader();
try {
this.doc = xmlReader.read(new File(path));
} catch (DocumentException e) {
e.printStackTrace();
}
}
public XmlDaoImpl(URL url) {
}
public XmlDaoImpl(File file) {
this.file = file;
SAXReader xmlReader = new SAXReader();
try {
this.doc = xmlReader.read(file);
} catch (DocumentException e) {
e.printStackTrace();
}
}
public boolean addObject(Object o) {
return false;
}
public boolean addObjects(List list) {
return false;
}
public Object[] concat(Object[] O1, Object[] O2) {
return null;
}
public Document getDocument() {
return this.doc;
}
public Field[] getFields() {
// TODO Auto-generated method stub
return null;
}
public Method[] getMethods() {
return null;
}
public Object getObject(Element e) {
return null;
}
public List getObjects(Element e) {
return null;
}
public Element getRoot() {
// TODO Auto-generated method stub
return null;
}
public String getRootName() {
// TODO Auto-generated method stub
return null;
}
public boolean modifyObject(Object o) {
// TODO Auto-generated method stub
return false;
}
public boolean modifyObjects(List list) {
// TODO Auto-generated method stub
return false;
}
public Document readDocument() {
// TODO Auto-generated method stub
return null;
}
public Document readDocument(String path) {
// TODO Auto-generated method stub
return null;
}
public Document readDocument(File file) {
// TODO Auto-generated method stub
return null;
}
public Document readDocument(InputStream is) {
// TODO Auto-generated method stub
return null;
}
public Document readDocument(URL url) {
// TODO Auto-generated method stub
return null;
}
public boolean removeObject(Object o) {
// TODO Auto-generated method stub
return false;
}
public boolean removeObjectBy(String name, Object value) {
// TODO Auto-generated method stub
return false;
}
public boolean removeObjects(List list) {
// TODO Auto-generated method stub
return false;
}
public void setRootName(String rootName) {
// TODO Auto-generated method stub
}
public void writeDocument(String path) {
XMLWriter writer;
try {
OutputFormat format = OutputFormat.createPrettyPrint();
writer = new XMLWriter(new FileOutputStream(new File(path)), format);
writer.write(doc);
writer.close();
} catch (UnsupportedEncodingException e) {
print(e.getMessage());
} catch (FileNotFoundException e) {
print(e.getMessage());
} catch (IOException e) {
print(e.getMessage());
}
}
public boolean writeDocument(File file) {
// TODO Auto-generated method stub
return false;
}
public boolean writeDocument(OutputStream os) {
// TODO Auto-generated method stub
return false;
}
public boolean writeDocument() {
// TODO Auto-generated method stub
return false;
}
public Element find(Object o) {
return null;
}
public static Class loadClass(String className, Class callingClass)
throws ClassNotFoundException {
try {
return Thread.currentThread().getContextClassLoader().loadClass(
className);
} catch (ClassNotFoundException e) {
try {
return Class.forName(className);
} catch (ClassNotFoundException ex) {
try {
return XmlDaoImpl.class.getClassLoader().loadClass(
className);
} catch (ClassNotFoundException exc) {
return callingClass.getClassLoader().loadClass(className);
}
}
}
}
public boolean delete(Object o) {
if (o != null)
this.claz = o.getClass();
else {
// throw new Exception("");//defined your own Exceptions
}
Iterator
boolean flag = false;
if (this.doc != null)
it = this.doc.getRootElement().elements().iterator();
else
return false;
while (it.hasNext()) {
Element el = it.next();
if (el.getName().equalsIgnoreCase(o.getClass().getSimpleName())) {
entity = new Object();
entity = parseToObject(el);
if (!entity.getClass().isInstance(o))
continue;
else if (isFind(entity, o)) {
if (this.doc.getRootElement().remove(el))
this.print("delete success!/n");
flag = true;
this.writeDocument("c:/backup.xml");
// change after finished
}
}
}
return flag;
}
public boolean insert(Object o) {
if (o != null)
this.claz = o.getClass();
else {
// throw new Exception("");//defined your own Exceptions
}
if (this.doc != null)
this.root = this.doc.getRootElement();
else
return false;
if (root != null)
parseToXml(root, o);
this.writeDocument("c:/backup.xml");
return false;
}
public void parseToXml(Element e, Object o) {
if (o != null) {
Element root_e = e.addElement(
o.getClass().getSimpleName().toLowerCase()).addAttribute(
"class", o.getClass().getName());
Field fields[] = this.getAllFields(o.getClass());
for (Field field : fields) {
Method m = this.findMethod(o.getClass(), field, "get");
try {
// this.print("method:" + m.getName() + "/n");
Object value = m.invoke(o, null);
if (value != null && value.getClass().isArray()) {
if (this.isSystemObject(value.getClass())) {
Element root_e_e = root_e.addElement(field
.getName());
for (int i = 0; i < Array.getLength(value); i++) {
root_e_e.addElement("value").addText(
Array.get(value, i).toString());
}
} else {
Element root_e_e = root_e.addElement(field
.getName());
for (int i = 0; i < Array.getLength(value); i++) {
parseToXml(root_e_e, Array.get(value, i));
}
}
} else if (value != null && this.isHash(value)) {
Element root_e_e = root_e.addElement(field.getName());
if (value instanceof Collection) {
List ls = (List) value;
for (Iterator it = ls.iterator(); it.hasNext();) {
Object lo = it.next();
if (lo != null)
this.parseToXml(root_e_e, lo);
}
} else if (value instanceof Map) {
Collection ls = (Collection) ((Map) value).values();
for (Iterator it = ls.iterator(); it.hasNext();) {
Object lo = it.next();
if (lo != null)
this.parseToXml(root_e_e, lo);
}
}
} else if (value != null) {
if (this.isSystemObject(value.getClass())) {
root_e.addElement(field.getName()).addText(
value.toString());
} else {
parseToXml(root_e, value);
}
}
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (InvocationTargetException e1) {
e1.printStackTrace();
}
}
} else
return;// throw Exception(""); here
}
public boolean isHash(Object obj) {
if (obj == null)
return false;
boolean isHash = obj instanceof Collection || obj instanceof Map;
return isHash;
}
public boolean insert(Object o, int index) {
return false;
}
public Object query(Object o) {
Iterator
if (o != null)
this.claz = o.getClass();
else {
// throw new Exception("");//defined your own Exceptions
}
if (this.doc != null)
it = this.doc.getRootElement().elements().iterator();
ArrayList list = new ArrayList();
while (it.hasNext()) {
Element el = it.next();
if (el.getName().equalsIgnoreCase(o.getClass().getSimpleName())) {
entity = new Object();
entity = parseToObject(el);
if (!entity.getClass().isInstance(o))
continue;
else if (isFind(entity, o)) {
return entity;
}
}
}
return null;
}
public List queryForAll(Object o) {
if (o != null)
this.claz = o.getClass();
else {
// throw new Exception("");//defined your own Exceptions
}
Iterator
if (this.doc != null)
it = this.doc.getRootElement().elements().iterator();
ArrayList list = new ArrayList();
while (it.hasNext()) {
Element el = it.next();
if (el.getName().equalsIgnoreCase(o.getClass().getSimpleName())) {
entity = new Object();
entity = parseToObject(el);
if (entity != null)
list.add(entity);
}
}
return list;
}
public List queryForList(Object o) {
if (o != null)
this.claz = o.getClass();
else {
// throw new Exception("");//defined your own Exceptions
}
Iterator
ArrayList list = new ArrayList();
if (this.doc != null)
it = this.doc.getRootElement().elements().iterator();
while (it.hasNext()) {
Element el = it.next();
if (el.getName().equalsIgnoreCase(o.getClass().getSimpleName())) {
entity = new Object();
entity = parseToObject(el);
if (isFind(entity, o)) {
list.add(entity);
} else
continue;
}
}
if (list.size() > 0)
return list;
return null;
}
public boolean update(Object o) {
if (o != null)
this.claz = o.getClass();
else {
// throw new Exception("");//defined your own Exceptions
}
return false;
}
public void print(String s) {
System.out.print(s);
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public boolean deleteByField(String name, Object value) {
return false;
}
public List queryByField(String name, Object value) {
return null;
}
public boolean deleteAll() {
Iterator
boolean flag = false;
if (this.doc != null)
it = this.doc.getRootElement().elements().iterator();
else
return false;
if (this.doc.remove(this.doc.getRootElement()))
this.print("delete success!/n");
flag = true;
this.writeDocument("c:/backup.xml");// change after finished
return flag;
}
public boolean isEqual(Object o1, Object o2) {
if(o2!=null)return false;
if(o1==o2||(o1!=null&&o1.equals(o2)))return true;
else{
if(o1 == null && o2 != null)return false;
else if(o2==null&&o1!=null)return false;
else{
//o1 o2 is not null
}
}
return false;
}
// this function is not fully
public boolean isFind(Object target, Object base) {
if (target == base || (target != null && target.equals(base)))
return true;
else if (target == null && base != null)return false;
else if (target != null && base == null)return false;
else if (target.getClass().isAssignableFrom(base.getClass())) {
try {
Field[] fs = this.getAllFields(target.getClass());
for (Field f : fs) {
Method m = this.findMethod(base.getClass(), f, "get");
Object v1 = m.invoke(base, null), v2 = m.invoke(target,
null);
// base JDK class or Object should be true but Object
// Container
// eg:List Vector etc.
if (v1 == null || (v1 == v2)
|| (v1 != null && v1.equals(v2))) {
continue;
} else {
if (v2!=null&&this.isEqual(v1, v2))
continue;
else return false;
}
}
return true;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
return false;
}
public String getClassName(String name) {
String className = null;
if (this.claz.getSimpleName().equalsIgnoreCase(name)) {
className = this.claz.getName();
} else {
Field fields[] = this.getAllFields(this.claz);
for (Field f : fields) {
if (f != null) {
if (this.isSystemObject(f.getType()))
continue;
else if (f.getType().getName().equalsIgnoreCase(name))
className = f.getType().getName();
}
}
}
return className;
}
public boolean isSystemObject(Class c) {
boolean flag = false;
if (c != null) {
String cname = c.getName();
flag = cname == "int" || cname == "long" || cname == "float";
flag = flag || cname == "double" || cname == "short"
|| cname == "ulong";
if (cname.indexOf(".") != -1) {
flag = flag
|| cname.substring(0, cname.indexOf(".")).indexOf(
"java") != -1;
}
} else
flag = false;
return flag;
}
public Object parseToObject(Element element) {
Object obj = null;
List
Class
try {
String className = this.getClassName(element.getName());
if (className == null)
className = element.attributeValue("class");
if (element != null) {
if (className != null)
cls = this.loadClass(className, this.getClass());
if (cls != null)
obj = cls.newInstance();
if (obj == null)
return null;
} else {
// throw your own Exception here
return null;
}
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
for (Node node : list) {
try {
String mName = "set"
+ node.getName().substring(0, 1).toUpperCase()
+ node.getName().substring(1);
Field f = this.getField(obj.getClass(), node.getName());
Object fo = null;
try {
if (!f.getType().isInterface())
fo = f.getType().newInstance();
else {
if (f.getType().getName().equals("java.util.List")) {
fo = new ArrayList();
} else if (f.getType().getName()
.equals("java.util.Map")) {
fo = new HashMap();
}
}
} catch (Exception e) {
fo = null;
}
if (f.getType().isArray()) {
Method method = this.findMethod(obj.getClass(), f, "set");
method.invoke(obj, this.getParamsValue(f, (Element) node));
} else if (fo != null && this.isHash(fo)) {
Method method = this.findMethod(obj.getClass(), f, "set");
if (fo instanceof Collection) {
method.invoke(obj, this.getParamsValue(f,
(Element) node));
}
} else {
Method method = this.findMethod(obj.getClass(), f, "set");
Object pars[] = getParamsValue(f, (Element) node);
if (pars != null)
method.invoke(obj, pars);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return obj;
}
public Object[] getParamsValue(Field fields, Element pe) {
Object params[] = new Object[1];
if (fields.getType() != null && !fields.getType().isInterface()) {
String value = pe.getStringValue();
String pname = fields.getType().getName();
if (pname == "int") {
pname = "java.lang.Integer";
} else if (pname == "long") {
pname = "java.lang.Long";
} else if (pname == "float") {
pname = "java.lang.Float";
} else if (pname == "double") {
pname = "java.lang.Double";
} else if (pname == "short") {
pname = "java.lang.Short";
} else if (pname == "boolean") {
pname = "java.lang.Boolean";
}
if (pname != null) {
if (this.isSystemObject(fields.getType())) {
if (fields.getType().isArray()) {
// Parse System Array
List
try {
Class pcls = this.loadClass(pname.substring(2,
pname.length() - 1), this.getClass());
Constructor c = pcls
.getConstructor(new Class[] { String.class });
Object o_arr = null;
o_arr = (Object) Array
.newInstance(pcls, e_l.size());
int i = 0;
for (Element e_o : e_l) {
Object[] parms = new Object[] { e_o
.getStringValue() };
Array.set(o_arr, i, c.newInstance(parms));
i++;
}
params[0] = o_arr;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
Object[] parms = new Object[] { value };
Class pcls = this.loadClass(pname, this.getClass());
if (fields.getType().getName() == "java.util.Vector") {
List
Method add = fields.getType().getMethod("add",
new Class[] { Object.class });
Vector v = new Vector();
for (Element e_o : e_l) {
Object o_r = this.parseToObject(e_o);
v.add(o_r);
}
params[0] = v;
} else if (fields.getType().getName() != "java.util.Date") {
Constructor c = pcls
.getConstructor(new Class[] { String.class });
if (parms != null)
params[0] = c.newInstance(parms);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
if (fields.getType().isArray()) {
List
Object o_arr = null;
int i = 0;
Element o_Temp = (Element) pe.elementIterator().next();
Object o_t = this.parseToObject(o_Temp);
o_arr = (Object) Array.newInstance(o_t.getClass(), e_l
.size());
for (Element e_o : e_l) {
Object o_p = this.parseToObject(e_o);
Array.set(o_arr, i, o_p);
i++;
}
params[0] = o_arr;
} else {
Object o = this.parseToObject(pe);
params[0] = o;
}
// parse user define object
}
} else
params = null;
} else if (fields.getType() != null && fields.getType().isInterface()) {
try {
List cl = new ArrayList();
List
for (Element e_o : e_l) {
Object o_r = this.parseToObject(e_o);
if (o_r != null)
cl.add(o_r);
}
Object[] parms = new Object[] { cl };
} catch (Exception e) {
e.printStackTrace();
}
}
return params;
}
public Field getField(Class cls, String fieldName) throws SecurityException {
Field field = null;
if (cls.getSuperclass() != null) {
try {
if (cls.getDeclaredField(fieldName) != null)
field = cls.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
field = getField(cls.getSuperclass(), fieldName);
}
} else {
try {
if (cls.getDeclaredField(fieldName) != null)
field = cls.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
field = null;
}
}
return field;
}
public Method findMethod(Class cls, Field field, String mType) {
Method m = null;
String mName = field.getName();
mName = mType + mName.substring(0, 1).toUpperCase()
+ mName.substring(1);
if (cls.getSuperclass() != null) {
try {
if (mType.equals("set"))
m = cls.getMethod(mName, new Class[] { field.getType() });
else if (mType.equals("get"))
m = cls.getMethod(mName, new Class[] {});
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
m = this.findMethod(cls.getSuperclass(), field, mName);
}
} else {
try {
if (mType.equals("set"))
m = cls.getMethod(mName, new Class[] { field.getType() });
else if (mType.equals("get"))
m = cls.getMethod(mName, new Class[] {});
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
}
}
return m;
}
public Method[] getPublicMethods(Class cls) {
Method methods[] = null;
if (cls.getSuperclass() != null) {
Class base = cls.getSuperclass();
methods = concat(getPublicMethods(base), cls.getMethods());
} else {
methods = cls.getMethods();
}
return methods;
}
public Method[] concat(Method[] m1, Method[] m2) {
Method m[] = new Method[m1.length + m2.length];
if (m1 != null && m2 != null) {
for (int i = 0; i < m.length; i++) {
if (i < m1.length) {
m[i] = m1[i];
} else {
m[i] = m2[i - m1.length];
}
}
}
return m;
}
public Field[] getAllFields(Class cls) {
Field[] fields = null;
if (cls.getSuperclass() != null) {
Class base = cls.getSuperclass();
fields = concat(getAllFields(base), cls.getDeclaredFields());
} else {
fields = cls.getDeclaredFields();
}
return fields;
}
public Field[] concat(Field[] f1, Field[] f2) {
Field f[] = new Field[f1.length + f2.length];
if (f1 != null && f2 != null) {
for (int i = 0; i < f.length; i++) {
if (i < f1.length) {
f[i] = f1[i];
} else {
f[i] = f2[i - f1.length];
}
}
}
return f;
}
}