01: /*
02: * This file is part of PFIXCORE.
03: *
04: * PFIXCORE is free software; you can redistribute it and/or modify
05: * it under the terms of the GNU Lesser General Public License as published by
06: * the Free Software Foundation; either version 2 of the License, or
07: * (at your option) any later version.
08: *
09: * PFIXCORE is distributed in the hope that it will be useful,
10: * but WITHOUT ANY WARRANTY; without even the implied warranty of
11: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12: * GNU Lesser General Public License for more details.
13: *
14: * You should have received a copy of the GNU Lesser General Public License
15: * along with PFIXCORE; if not, write to the Free Software
16: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17: *
18: */
19: package de.schlund.pfixcore.oxm.impl.serializers;
20:
21: import java.lang.reflect.Field;
22: import java.lang.reflect.Method;
23: import java.util.Iterator;
24: import java.util.Set;
25:
26: import de.schlund.pfixcore.beans.BeanDescriptor;
27: import de.schlund.pfixcore.beans.BeanDescriptorFactory;
28: import de.schlund.pfixcore.oxm.impl.ComplexTypeSerializer;
29: import de.schlund.pfixcore.oxm.impl.SerializationContext;
30: import de.schlund.pfixcore.oxm.impl.XMLWriter;
31:
32: /**
33: * @author mleidig@schlund.de
34: */
35: public class ComplexEnumSerializer implements ComplexTypeSerializer {
36:
37: private BeanDescriptorFactory beanDescFactory;
38:
39: public ComplexEnumSerializer(BeanDescriptorFactory beanDescFactory) {
40: this .beanDescFactory = beanDescFactory;
41: }
42:
43: public void serialize(Object obj, SerializationContext ctx,
44: XMLWriter writer) {
45: Enum<?> e = (Enum<?>) obj;
46: writer.writeAttribute("name", e.name());
47: BeanDescriptor bd = beanDescFactory.getBeanDescriptor(obj
48: .getClass());
49: Set<String> props = bd.getReadableProperties();
50: Iterator<String> it = props.iterator();
51: while (it.hasNext()) {
52: String prop = it.next();
53: try {
54: Object val = null;
55: Method meth = bd.getGetMethod(prop);
56: if (meth != null) {
57: val = meth.invoke(obj, new Object[0]);
58: } else {
59: Field field = bd.getDirectAccessField(prop);
60: if (field != null) {
61: val = field.get(obj);
62: } else {
63: throw new RuntimeException(
64: "Enum of type '"
65: + obj.getClass().getName()
66: + "' doesn't "
67: + " have getter method or direct access to property '"
68: + prop + "'.");
69: }
70: }
71: if (val != null) {
72: if (ctx.hasSimpleTypeSerializer(val.getClass())) {
73: writer.writeAttribute(prop, ctx.serialize(val));
74: } else {
75: writer.writeStartElement(prop);
76: ctx.serialize(val, writer);
77: writer.writeEndElement();
78: }
79: }
80: } catch (Exception x) {
81: throw new RuntimeException(
82: "Error during serialization.", x);
83: }
84: }
85: }
86: }
|