1 package org.codehaus.xfire.java.mapping;
2
3 import java.util.Collection;
4
5 import javax.xml.namespace.QName;
6
7 import org.codehaus.xfire.java.ServiceHelper;
8 import org.codehaus.xfire.java.type.ArrayType;
9 import org.codehaus.xfire.java.type.BeanType;
10 import org.codehaus.xfire.java.type.Type;
11
12 /***
13 * A type mapping which automatically generates types
14 * for java classes which are not registered, allowing
15 * easy deployment of java services.
16 *
17 * @author <a href="mailto:dan@envoisolutions.com">Dan Diephouse</a>
18 * @since Feb 21, 2004
19 */
20 public class AutoTypeMapping
21 extends CustomTypeMapping
22 {
23 public AutoTypeMapping( TypeMapping defaultTM )
24 {
25 super( defaultTM );
26 }
27
28 public AutoTypeMapping()
29 {
30 super();
31 }
32
33 /***
34 * @see org.codehaus.xfire.java.mapping.TypeMapping#getSerializer(java.lang.Class, javax.xml.namespace.QName)
35 */
36 public Type getType( Class javaType, QName xmlType )
37 {
38 Type type = super.getType(javaType, xmlType);
39
40 if ( type == null )
41 {
42 register( javaType, xmlType, findTypeClass( javaType ) );
43
44 type = super.getType(javaType, xmlType);
45 }
46
47 return type;
48 }
49
50 /***
51 * Tries to determine a type class automatically from the type.
52 *
53 * @param javaType
54 * @return
55 */
56 private Class findTypeClass(Class javaType)
57 {
58 if ( javaType.isArray() ||
59 javaType.isAssignableFrom( Collection.class ) )
60 {
61 return ArrayType.class;
62 }
63 else
64 {
65 return BeanType.class;
66 }
67 }
68
69 /***
70 * @see org.codehaus.xfire.java.mapping.TypeMapping#getType(java.lang.Class)
71 */
72 public Type getType(Class javaType)
73 {
74 Type type = super.getType(javaType);
75
76 if ( type == null )
77 {
78 QName qname = createQName( javaType );
79 register( javaType, qname, findTypeClass( javaType ) );
80
81 type = super.getType(javaType, qname);
82 }
83
84 return type;
85 }
86
87 /***
88 * @param javaType
89 * @return
90 * @throws ClassNotFoundException
91 */
92 private QName createQName(Class javaType)
93 {
94 String clsName = javaType.getName();
95
96 if (clsName.startsWith("[L"))
97 {
98 clsName = clsName.substring(2, clsName.length() - 1);
99 }
100
101 String ns = ServiceHelper.makeNamespaceFromClassName(clsName, "http");
102
103 String localName = null;
104
105 if (javaType.isArray() ||
106 javaType.isAssignableFrom( Collection.class ))
107 {
108 localName = "ArrayOf" + clsName.substring( clsName.lastIndexOf(".")+1 );
109
110
111
112 if ( javaType.isArray() )
113 {
114 Type type = getType( javaType.getComponentType() );
115
116 if ( type.isComplex() )
117 {
118 ns = type.getSchemaType().getNamespaceURI();
119 }
120 else
121 {
122 ns = getEncodingStyleURI();
123 }
124 }
125 }
126 else
127 {
128 localName = clsName.substring( clsName.lastIndexOf(".")+1 );
129 }
130
131 return new QName( ns, localName );
132 }
133 }