summaryrefslogtreecommitdiffstats
path: root/sca-java-2.x/tags/2.0.1-RC1/modules/implementation-java-runtime/src/main/java/org/apache/tuscany/sca/implementation/java/injection/JavaPropertyValueObjectFactory.java
blob: acacd23d8ffca7f6b5ed709fdedb8a13e9640731 (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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
/*
 * 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.implementation.java.injection;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.tuscany.sca.assembly.ComponentProperty;
import org.apache.tuscany.sca.assembly.Property;
import org.apache.tuscany.sca.common.xml.dom.DOMHelper;
import org.apache.tuscany.sca.context.PropertyValueFactory;
import org.apache.tuscany.sca.core.ExtensionPointRegistry;
import org.apache.tuscany.sca.core.UtilityExtensionPoint;
import org.apache.tuscany.sca.core.factory.ObjectCreationException;
import org.apache.tuscany.sca.core.factory.ObjectFactory;
import org.apache.tuscany.sca.databinding.Mediator;
import org.apache.tuscany.sca.databinding.SimpleTypeMapper;
import org.apache.tuscany.sca.databinding.impl.SimpleTypeMapperImpl;
import org.apache.tuscany.sca.databinding.xml.DOMDataBinding;
import org.apache.tuscany.sca.implementation.java.JavaElementImpl;
import org.apache.tuscany.sca.implementation.java.introspect.JavaIntrospectionHelper;
import org.apache.tuscany.sca.interfacedef.DataType;
import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl;
import org.apache.tuscany.sca.interfacedef.util.TypeInfo;
import org.apache.tuscany.sca.interfacedef.util.XMLType;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @version $Rev$ $Date$
 */
public class JavaPropertyValueObjectFactory implements PropertyValueFactory {
    private Mediator mediator = null;
    private SimpleTypeMapper simpleTypeMapper;
    private boolean isSimpleType;

    public JavaPropertyValueObjectFactory(ExtensionPointRegistry registry) {
        UtilityExtensionPoint utilityExtensionPoint = registry.getExtensionPoint(UtilityExtensionPoint.class);
        this.mediator = utilityExtensionPoint.getUtility(Mediator.class);
        this.simpleTypeMapper = utilityExtensionPoint.getUtility(SimpleTypeMapper.class);
    }

    public JavaPropertyValueObjectFactory(Mediator mediator) {
        this.mediator = mediator;
    }

    public ObjectFactory createValueFactory(Property property, Object propertyValue, JavaElementImpl javaElement) {
        Document doc = (Document)propertyValue;
        List<Node> nodes = getValues(doc);
        Class<?> javaType = JavaIntrospectionHelper.getBaseType(javaElement.getType(), javaElement.getGenericType());
        if (property.isMany()) {
            if (javaElement.getType().isArray()) {
                return new ArrayObjectFactoryImpl(property, nodes, javaType);
            } else {
                return new ListObjectFactoryImpl(property, nodes, javaType);
            }
        } else {
            Object value = null;
            if (!nodes.isEmpty()) {
                value = nodes.get(0);
            }
            return new ObjectFactoryImpl(property, value, javaType);

        }
    }

    public ObjectFactory createValueFactory(Property property, Object propertyValue, Class<?> javaType) {
        Document doc = (Document)propertyValue;
        List<Node> nodes = getValues(doc);
        if (property.isMany()) {
            return new ListObjectFactoryImpl(property, nodes, javaType);
        } else {
            Object value = null;
            if (!nodes.isEmpty()) {
                value = nodes.get(0);
            }
            return new ObjectFactoryImpl(property, value, javaType);
        }
    }

    public <B> B createPropertyValue(ComponentProperty property, Class<B> type) {
    	
    	validateTypes(property, type);
    	
        ObjectFactory<B> factory = this.createValueFactory(property, property.getValue(), type);
        return factory.getInstance();
    }

	private <B> void validateTypes(ComponentProperty property, Class<B> type) {
		// JAXB seems to do some strange things with conversions, so
    	// we can't rely on the databinding conversion from Node->Java to catch
		// incompatible types. 
		
		DataType prop1 = property.getProperty().getDataType();
    	
		if ( (prop1 != null) && (type.isAssignableFrom(prop1.getPhysical())) )  {
			return;    			
		} else if ( simpleTypeMapper.getXMLType(type) != null ) { 
    		if ( simpleTypeMapper.getXMLType(type).getQName().equals(property.getXSDType())) 
    			return;    			    		
    	} else if ( isSimpleType(property) ) {
    		if ( type.isAssignableFrom(simpleTypeMapper.getJavaType(property.getXSDType()))) 
    			return;    		
    	} 
    	
		throw new IllegalArgumentException("Property type " + prop1.getPhysical().getName() + " is not compatible with " + type.getName());
 
	}

    abstract class ObjectFactoryImplBase implements ObjectFactory {
        protected SimpleTypeMapper simpleTypeMapper = new SimpleTypeMapperImpl();
        protected Property property;
        protected Object propertyValue;
        protected Class<?> javaType;
        protected DataType<XMLType> sourceDataType;
        protected DataType<?> targetDataType;

        public ObjectFactoryImplBase(Property property, Object propertyValue, Class<?> javaType) {
            this.property = property;
            this.propertyValue = propertyValue;
            this.javaType = javaType;
            sourceDataType =
                new DataTypeImpl<XMLType>(DOMDataBinding.NAME, Node.class,
                                          new XMLType(null, this.property.getXSDType()));
            
            targetDataType = property.getDataType();
            if (targetDataType == null) {
                TypeInfo typeInfo = null;
                if (this.property.getXSDType() != null) {
                    if (simpleTypeMapper.isSimpleXSDType(this.property.getXSDType())) {
                        typeInfo = new TypeInfo(property.getXSDType(), true, null);
                    } else {
                        typeInfo = new TypeInfo(property.getXSDType(), false, null);
                    }
                } else {
                    typeInfo = new TypeInfo(property.getXSDType(), false, null);
                }

                XMLType xmlType = new XMLType(typeInfo);
                String dataBinding = null; // (String)property.getExtensions().get(DataBinding.class.getName());
                if (dataBinding != null) {
                    targetDataType = new DataTypeImpl<XMLType>(dataBinding, javaType, xmlType);
                } else {
                    targetDataType = new DataTypeImpl<XMLType>(dataBinding, javaType, xmlType);
                    mediator.getDataBindings().introspectType(targetDataType, null);
                }
            }
        }
    }

    class ObjectFactoryImpl extends ObjectFactoryImplBase {
        private Object result = null;
        
        public ObjectFactoryImpl(Property property, Object propertyValue, Class<?> javaType) {
            super(property, propertyValue, javaType);
        }

        public Object getInstance() throws ObjectCreationException {
            // TUSCANY-3791
            if (result != null){
                return result;
            }
            
            if (isSimpleType) {
                try {
                    result = simpleTypeMapper.toJavaObject(property.getXSDType(), (String)propertyValue, null);
                } catch (NumberFormatException ex) {
                    throw new ObjectCreationException("Failed to create instance for property " + property.getName()
                        + " with value "
                        + propertyValue, ex);
                } catch (IllegalArgumentException ex) {
                    throw new ObjectCreationException("Failed to create instance for property " + property.getName()
                        + " with value "
                        + propertyValue, ex);
                }
            } else {
                result = mediator.mediate(propertyValue, sourceDataType, targetDataType, null);
            }
            return result;
        }
    }

    class ListObjectFactoryImpl extends ObjectFactoryImplBase {
        private List result = null;
        
        public ListObjectFactoryImpl(Property property, List<?> propertyValues, Class<?> javaType) {
            super(property, propertyValues, javaType);
        }

        @SuppressWarnings("unchecked")
        public List<?> getInstance() throws ObjectCreationException {
            // TUSCANY-3791
            if (result != null){
                return result;
            }
            
            if (isSimpleType) {
                List<Object> values = new ArrayList<Object>();
                for (String aValue : (List<String>)propertyValue) {
                    try {
                        values.add(simpleTypeMapper.toJavaObject(property.getXSDType(), aValue, null));
                    } catch (NumberFormatException ex) {
                        throw new ObjectCreationException("Failed to create instance for property " + property
                            .getName()
                            + " with value "
                            + aValue
                            + " from value list of "
                            + propertyValue, ex);
                    } catch (IllegalArgumentException ex) {
                        throw new ObjectCreationException("Failed to create instance for property " + property
                            .getName()
                            + " with value "
                            + aValue
                            + " from value list of "
                            + propertyValue, ex);
                    }
                }
                result = values;
            } else {
                List instances = new ArrayList();
                for (Node aValue : (List<Node>)propertyValue) {
                    instances.add(mediator.mediate(aValue, sourceDataType, targetDataType, null));
                }
                result = instances;
            }
            
            return result;
        }
    }

    class ArrayObjectFactoryImpl extends ObjectFactoryImplBase {
        private Object result = null;
        
        public ArrayObjectFactoryImpl(Property property, List<?> propertyValues, Class<?> javaType) {
            super(property, propertyValues, javaType);
        }

        @SuppressWarnings("unchecked")
        public Object getInstance() throws ObjectCreationException {
            // TUSCANY-3791
            if (result != null){
                return result;
            }
            
            if (isSimpleType) {
                int count = 0;
                Object values = Array.newInstance(javaType, ((List<Object>)propertyValue).size());
                for (String aValue : (List<String>)propertyValue) {
                    try {
                        Array.set(values, count++, simpleTypeMapper.toJavaObject(property.getXSDType(), aValue, null));
                    } catch (NumberFormatException ex) {
                        throw new ObjectCreationException("Failed to create instance for property " + property
                            .getName()
                            + " with value "
                            + aValue
                            + " from value list of "
                            + propertyValue, ex);
                    } catch (IllegalArgumentException ex) {
                        throw new ObjectCreationException("Failed to create instance for property " + property
                            .getName()
                            + " with value "
                            + aValue
                            + " from value list of "
                            + propertyValue, ex);
                    }
                }
                result = values;
            } else {
                Object instances = Array.newInstance(javaType, ((List<Object>)propertyValue).size());
                int count = 0;
                for (Node aValue : (List<Node>)propertyValue) {
                    Array.set(instances, count++, mediator.mediate(aValue, sourceDataType, targetDataType, null));
                }
                result = instances;
            }
            
            return result;
        }
    }

    /**
     * Utility methods
     */

    /**
     *
     * @param property
     * @return
     */
    private boolean isSimpleType(Property property) {
        if (property.getXSDType() != null) {
            return simpleTypeMapper.isSimpleXSDType(property.getXSDType());
        } else {
            if (property instanceof Document) {
                Document doc = (Document)property;
                Element element = doc.getDocumentElement();
                if (element.getChildNodes().getLength() == 1 && element.getChildNodes().item(0).getNodeType() == Element.TEXT_NODE) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Retrieve list of simple property values
     * @param concatenatedValue
     * @param javaType
     * @return
     */
    private static List<String> getSimplePropertyValues(String concatenatedValue, Class<?> javaType) {
        List<String> propValues = new ArrayList<String>();
        StringTokenizer st = null;
        if (javaType.getName().equals("java.lang.String")) {
            st = new StringTokenizer(concatenatedValue, "\"");
        } else {
            st = new StringTokenizer(concatenatedValue);
        }
        String aToken = null;
        while (st.hasMoreTokens()) {
            aToken = st.nextToken();
            if (aToken.trim().length() > 0) {
                propValues.add(aToken);
            }
        }
        return propValues;
    }

    /**
     * Retrieve the list of complex property values
     * @param document
     * @return
     */
    private static List<Node> getValues(Document document) {
    	 List<Node> propValues = new ArrayList<Node>();
    	 if ( document == null )
    		 return propValues;
        // The root is the property element
        Element rootElement = document.getDocumentElement();
       
        NodeList nodes = rootElement.getChildNodes();
        for (int count = 0; count < nodes.getLength(); ++count) {
            Node node = nodes.item(count);
            if (node.getNodeType() == Document.ELEMENT_NODE) {
                propValues.add(DOMHelper.promote(node));
            }
        }
        return propValues;
    }
}