summaryrefslogtreecommitdiffstats
path: root/sca-java-2.x/tags/2.0.1-RC1/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/BeanXMLStreamReaderImpl.java
blob: ed59911a0be69c7c2b1b1e42aea7215a0552e9ed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.apache.tuscany.sca.databinding.xml;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.namespace.QName;

import org.apache.tuscany.sca.common.xml.stax.reader.SimpleXmlNodeImpl;
import org.apache.tuscany.sca.common.xml.stax.reader.XmlNode;
import org.apache.tuscany.sca.common.xml.stax.reader.XmlTreeStreamReaderImpl;
import org.apache.tuscany.sca.databinding.SimpleTypeMapper;
import org.apache.tuscany.sca.databinding.impl.SimpleTypeMapperImpl;
import org.apache.tuscany.sca.interfacedef.util.TypeInfo;

/**
 * @version $Rev$ $Date$
 */
public class BeanXMLStreamReaderImpl extends XmlTreeStreamReaderImpl {
    private static final Comparator<Accessor> COMPARATOR = new Comparator<Accessor>() {
        public int compare(Accessor o1, Accessor o2) {
            return o1.getName().compareTo(o2.getName());
        }
    };

    public static class BeanXmlNodeImpl extends SimpleXmlNodeImpl implements XmlNode {
        private static final Object[] NULL = null;
        private static final SimpleTypeMapper MAPPER = new SimpleTypeMapperImpl();

        public BeanXmlNodeImpl(Object bean) {
            super(getName(bean == null ? null : bean.getClass()), bean);
        }

        public BeanXmlNodeImpl(QName name, Object bean) {
            super(name, bean);
        }

        private static boolean isSimpleType(Class<?> javaType) {
            return MAPPER.getXMLType(javaType) != null;
        }

        private static String getStringValue(Object o) {
            if (o == null) {
                return null;
            }
            TypeInfo info = MAPPER.getXMLType(o.getClass());
            if (info != null) {
                return MAPPER.toXMLLiteral(info.getQName(), o, null);
            } else {
                return String.valueOf(o);
            }
        }

        @Override
        public Iterator<XmlNode> children() {
            if (name == null) {
                return null;
            }
            if (value == null) {
                return super.children();
            }
            if (isSimpleType(value.getClass())) {
                XmlNode textNode = new BeanXmlNodeImpl(null, value);
                return Arrays.asList(textNode).iterator();
            }
            if (Map.class.isAssignableFrom(value.getClass())) {
                List<XmlNode> entries = new ArrayList<XmlNode>();
                QName entryName = new QName(name.getNamespaceURI(), "entry");
                Map map = (Map)value;
                if (map != null) {
                    for (Object e : map.entrySet()) {
                        Map.Entry entry = (Map.Entry)e;
                        entries.add(new BeanXmlNodeImpl(entryName, entry));
                    }
                }
                return entries.iterator();
            }
            try {
                Map<String, Accessor> accessorMap = getAccessors(value);
                List<Accessor> accessorList = new ArrayList<Accessor>(accessorMap.values());
                Collections.sort(accessorList, COMPARATOR);

                List<XmlNode> props = new ArrayList<XmlNode>();
                for (Accessor accessor : accessorList) {
                    Class<?> pType = accessor.getType();

                    QName pName = new QName(name.getNamespaceURI(), accessor.getName());
                    Object pValue = accessor.getValue();
                    if (pType.isArray()) {
                        if (pValue != null) {
                            int i1 = Array.getLength(pValue);
                            for (int j = 0; j < i1; j++) {
                                Object o = Array.get(pValue, j);
                                props.add(new BeanXmlNodeImpl(pName, o));
                            }
                        } else {
                            // TODO: How to handle null?
                        }
                    } else if (Collection.class.isAssignableFrom(pType)) {
                        Collection objList = (Collection)pValue;
                        if (objList != null && objList.size() > 0) {
                            for (Iterator j = objList.iterator(); j.hasNext();) {
                                Object o = j.next();
                                props.add(new BeanXmlNodeImpl(pName, o));
                            }

                        } else {
                            // How to handle null
                        }
                    } else {
                        props.add(new BeanXmlNodeImpl(pName, pValue));
                    }
                }
                return props.iterator();
            } catch (Exception e) {
                throw new IllegalArgumentException(e);
            }
        }

        @Override
        public QName getName() {
            return name;
        }

        @Override
        public String getValue() {
            return getStringValue(value);
        }
        
        private static String getPackageName(Class<?> cls) {
            String name = cls.getName();
            int index = name.lastIndexOf('.');
            return index == -1 ? "" : name.substring(0, index);
        }

        public static QName getName(Class<?> cls) {
            if (cls == null) {
                return null;
            }

            String packageName = getPackageName(cls);

            if ("".equals(packageName)) {
                return new QName("", cls.getSimpleName());
            }
            StringBuffer ns = new StringBuffer("http://");
            String[] names = packageName.split("\\.");
            for (int i = names.length - 1; i >= 0; i--) {
                ns.append(names[i]);
                if (i != 0) {
                    ns.append('.');
                }
            }
            ns.append('/');
            return new QName(ns.toString(), cls.getSimpleName());
        }

    }

    public BeanXMLStreamReaderImpl(QName name, Object bean) {
        super(getXmlNode(name, bean));
    }

    private static BeanXmlNodeImpl getXmlNode(QName name, Object bean) {
        BeanXmlNodeImpl root = null;
        if (name != null) {
            root = new BeanXmlNodeImpl(name, bean);
        } else {
            root = new BeanXmlNodeImpl(bean);
        }
        return root;
    }

    public static interface Accessor {
        String getName();

        Class<?> getType();

        Object getValue() throws Exception;

        void setValue(Object value) throws Exception;
    }

    private static class FieldAccessor implements Accessor {
        private Object target;
        private Field field;

        public FieldAccessor(Object target, Field field) {
            super();
            this.target = target;
            this.field = field;
            this.field.setAccessible(true);
        }

        public String getName() {
            return field.getName();
        }

        public Object getValue() throws Exception {
            return field.get(target);
        }

        public void setValue(Object value) throws Exception {
            field.set(target, value);
        }

        public Class<?> getType() {
            return field.getType();
        }

    }

    private static class PropertyAccessor implements Accessor {
        private Object target;
        private PropertyDescriptor prop;

        public PropertyAccessor(Object target, PropertyDescriptor prop) {
            super();
            this.target = target;
            this.prop = prop;
        }

        public String getName() {
            return prop.getName();
        }

        public Class<?> getType() {
            return prop.getPropertyType();
        }

        public Object getValue() throws Exception {
            Method getter = prop.getReadMethod();
            if (getter != null) {
                getter.setAccessible(true);
                return getter.invoke(target);
            }
            throw new IllegalAccessException("The property cannot be read: " + getName());
        }

        public void setValue(Object value) throws Exception {
            Method setter = prop.getWriteMethod();
            if (setter != null) {
                setter.setAccessible(true);
                setter.invoke(target);
            }
            throw new IllegalAccessException("The property cannot be written: " + getName());
        }

    }

    private static Map<String, Accessor> getAccessors(Object target) throws Exception {
        if (target == null) {
            return Collections.emptyMap();
        }
        Map<String, Accessor> map = new HashMap<String, Accessor>();
        Class<?> type = target.getClass();
        for (Field f : type.getFields()) {
            map.put(f.getName(), new FieldAccessor(target, f));
        }
        BeanInfo info = Introspector.getBeanInfo(type, Object.class);
        for (PropertyDescriptor p : info.getPropertyDescriptors()) {
            // if (p.getReadMethod() != null && p.getWriteMethod() != null) {
                map.put(p.getName(), new PropertyAccessor(target, p));
            // }
        }
        return map;
    }

}