summaryrefslogtreecommitdiffstats
path: root/sca-java-2.x/tags/2.0.1-RC1/modules/databinding-jaxb/src/main/java/org/apache/tuscany/sca/databinding/jaxb/DataConverter.java
blob: 35adffe23be9015eb7c5fbdc97a08644ba386d0a (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
372
373
374
375
376
377
378
/*
 * 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.jaxb;

import java.awt.Image;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.activation.DataHandler;
import javax.imageio.ImageIO;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.oasisopen.sca.ServiceRuntimeException;

/**
 * Provides utilities to convert an object into a different kind of Object. For example, convert a
 * String[] into a List<String>
 */
public class DataConverter {

    /**
     * This method should return true if the convert method will succeed.
     * <p/>
     * Note that any changes to isConvertable() must also be accompanied by similar changes to
     * convert()
     *
     * @param obj  source object or class
     * @param dest destination class
     * @return boolean true if convert(..) can convert obj to the destination class
     */
    public static boolean isConvertable(Object obj, Class dest) {
        Class src = null;

        if (obj != null) {
            if (obj instanceof Class) {
                src = (Class)obj;
            } else {
                src = obj.getClass();
            }
        }

        if (dest == null) {
            return false;
        }

        if (src == null) {
            return true;
        }

        // If we're directly assignable, we're good.
        if (dest.isAssignableFrom(src)) {
            return true;
        }

        // If it's a wrapping conversion, we're good.
        if (getWrapperClass(src) == dest) {
            return true;
        }
        if (getWrapperClass(dest) == src) {
            return true;
        }

        // If it's List -> Array or vice versa, we're good.
        if ((Collection.class.isAssignableFrom(src) || src.isArray()) && (Collection.class.isAssignableFrom(dest) || dest
            .isArray())) {

            // TODO this should consider the component types instead of returning true.
            return true;
        }

        // Allow mapping of HashMaps to Hashtables
        if (src == HashMap.class && dest == Hashtable.class)
            return true;

        // Allow mapping of Calendar to Date
        if (Calendar.class.isAssignableFrom(src) && dest == Date.class) {
            return true;
        }

        if (src.isPrimitive()) {
            return isConvertable(getWrapperClass(src), dest);
        }

        if (InputStream.class.isAssignableFrom(src) && dest == byte[].class) {
            return true;
        }

        if (Source.class.isAssignableFrom(src) && dest == byte[].class) {
            return true;
        }

        if (DataHandler.class.isAssignableFrom(src) && isConvertable(byte[].class, dest)) {
            return true;
        }

        if (DataHandler.class.isAssignableFrom(src) && dest == Image.class) {
            return true;
        }

        if (DataHandler.class.isAssignableFrom(src) && dest == Source.class) {
            return true;
        }

        if (byte[].class.isAssignableFrom(src) && dest == String.class) {
            return true;
        }

        // If it's a MIME type mapping and we want a DataHandler,
        // then we're good.
        // REVIEW Do we want to support this
        /*
        if (dest.getName().equals("javax.activation.DataHandler")) {
            String name = src.getName();
            if (src == String.class
                    || src == java.awt.Image.class
                    || name.equals("javax.mail.internet.MimeMultipart")
                    || name.equals("javax.xml.transform.Source"))
                return true;
        }
        */

        return false;
    }

    /**
     * Utility function to convert an Object to some desired Class.
     * <p/>
     * Normally this is used for T[] to List<T> processing. Other conversions are also done (i.e.
     * HashMap <->Hashtable, etc.)
     * <p/>
     * Use the isConvertable() method to determine if conversion is possible. Note that any changes
     * to convert() must also be accompanied by similar changes to isConvertable()
     *
     * @param arg       the array to convert
     * @param destClass the actual class we want
     * @return object of destClass if conversion possible, otherwise returns arg
     */
    public static Object convert(Object arg, Class<?> destClass) {
        if (destClass == null) {
            return arg;
        }

        if (arg != null && destClass.isAssignableFrom(arg.getClass())) {
            return arg;
        }

        // Convert between Calendar and Date
        if (arg instanceof Calendar && destClass == Date.class) {
            return ((Calendar)arg).getTime();
        }

        // Convert between HashMap and Hashtable
        if (arg instanceof HashMap && destClass == Hashtable.class) {
            return new Hashtable((HashMap)arg);
        }

        if (arg instanceof InputStream && destClass == byte[].class) {

            try {
                InputStream is = (InputStream)arg;
                return getBytesFromStream(is);
            } catch (IOException e) {
                throw new ServiceRuntimeException(e);
            }
        }

        if (arg instanceof Source && destClass == byte[].class) {
            try {
                if (arg instanceof StreamSource) {
                    InputStream is = ((StreamSource)arg).getInputStream();
                    if (is != null) {
                        return getBytesFromStream(is);
                    }
                }
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                Result result = new StreamResult(out);
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                transformer.transform((Source)arg, result);
                byte[] bytes = out.toByteArray();
                return bytes;

            } catch (Exception e) {
                throw new ServiceRuntimeException(e);
            }
        }

        if (arg instanceof DataHandler) {
            try {
                InputStream is = ((DataHandler)arg).getInputStream();
                if (destClass == Image.class) {
                    return ImageIO.read(is);
                } else if (destClass == Source.class) {
                    return new StreamSource(is);
                }
                byte[] bytes = getBytesFromStream(is);
                return convert(bytes, destClass);
            } catch (Exception e) {
                throw new ServiceRuntimeException(e);
            }
        }

        if (arg instanceof byte[] && destClass == String.class) {
            return new String((byte[])arg);
        }

        // If the destination is an array and the source
        // is a suitable component, return an array with 
        // the single item.
        /* REVIEW do we need to support atomic to array conversion ?
        if (arg != null &&
            destClass.isArray() &&
            !destClass.getComponentType().equals(Object.class) &&
            destClass.getComponentType().isAssignableFrom(arg.getClass())) {
            Object array = 
                Array.newInstance(destClass.getComponentType(), 1);
            Array.set(array, 0, arg);
            return array;
        }
        */

        // Return if no conversion is available
        if (!(arg instanceof Collection || (arg != null && arg.getClass().isArray()))) {
            return arg;
        }

        if (arg == null) {
            return null;
        }

        // The arg may be an array or List 
        Object destValue = null;
        int length = 0;
        if (arg.getClass().isArray()) {
            length = Array.getLength(arg);
        } else {
            length = ((Collection)arg).size();
        }

        try {
            if (destClass.isArray()) {
                if (destClass.getComponentType().isPrimitive()) {

                    Object array = Array.newInstance(destClass.getComponentType(), length);
                    // Assign array elements
                    if (arg.getClass().isArray()) {
                        for (int i = 0; i < length; i++) {
                            Array.set(array, i, Array.get(arg, i));
                        }
                    } else {
                        int idx = 0;
                        for (Iterator i = ((Collection)arg).iterator(); i.hasNext();) {
                            Array.set(array, idx++, i.next());
                        }
                    }
                    destValue = array;

                } else {
                    Object[] array;
                    try {
                        array = (Object[])Array.newInstance(destClass.getComponentType(), length);
                    } catch (Exception e) {
                        return arg;
                    }

                    // Use convert to assign array elements.
                    if (arg.getClass().isArray()) {
                        for (int i = 0; i < length; i++) {
                            array[i] = convert(Array.get(arg, i), destClass.getComponentType());
                        }
                    } else {
                        int idx = 0;
                        for (Iterator i = ((Collection)arg).iterator(); i.hasNext();) {
                            array[idx++] = convert(i.next(), destClass.getComponentType());
                        }
                    }
                    destValue = array;
                }
            } else if (Collection.class.isAssignableFrom(destClass)) {
                Collection newList = null;
                try {
                    // if we are trying to create an interface, build something
                    // that implements the interface
                    if (destClass == Collection.class || destClass == List.class) {
                        newList = new ArrayList();
                    } else if (destClass == Set.class) {
                        newList = new HashSet();
                    } else {
                        newList = (Collection)destClass.newInstance();
                    }
                } catch (Exception e) {
                    // No FFDC code needed
                    // Couldn't build one for some reason... so forget it.
                    return arg;
                }

                if (arg.getClass().isArray()) {
                    for (int j = 0; j < length; j++) {
                        newList.add(Array.get(arg, j));
                    }
                } else {
                    for (Iterator j = ((Collection)arg).iterator(); j.hasNext();) {
                        newList.add(j.next());
                    }
                }
                destValue = newList;
            } else {
                destValue = arg;
            }
        } catch (Throwable t) {
            throw new ServiceRuntimeException(t);
        }

        return destValue;
    }

    private static byte[] getBytesFromStream(InputStream is) throws IOException {
        // TODO This code assumes that available is the length of the stream.
        byte[] bytes = new byte[is.available()];
        is.read(bytes);
        return bytes;
    }

    public static Class getWrapperClass(Class primitive) {
        if (primitive == int.class) {
            return java.lang.Integer.class;
        } else if (primitive == short.class) {
            return java.lang.Short.class;
        } else if (primitive == boolean.class) {
            return java.lang.Boolean.class;
        } else if (primitive == byte.class) {
            return java.lang.Byte.class;
        } else if (primitive == long.class) {
            return java.lang.Long.class;
        } else if (primitive == double.class) {
            return java.lang.Double.class;
        } else if (primitive == float.class) {
            return java.lang.Float.class;
        } else if (primitive == char.class) {
            return java.lang.Character.class;
        }

        return null;
    }
}