001: /*
002: * Copyright (c) 1998-2007 Caucho Technology -- all rights reserved
003: *
004: * This file is part of Resin(R) Open Source
005: *
006: * Each copy or derived work must preserve the copyright notice and this
007: * notice unmodified.
008: *
009: * Resin Open Source is free software; you can redistribute it and/or modify
010: * it under the terms of the GNU General Public License as published by
011: * the Free Software Foundation; either version 2 of the License, or
012: * (at your option) any later version.
013: *
014: * Resin Open Source is distributed in the hope that it will be useful,
015: * but WITHOUT ANY WARRANTY; without even the implied warranty of
016: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
017: * of NON-INFRINGEMENT. See the GNU General Public License for more
018: * details.
019: *
020: * You should have received a copy of the GNU General Public License
021: * along with Resin Open Source; if not, write to the
022: * Free SoftwareFoundation, Inc.
023: * 59 Temple Place, Suite 330
024: * Boston, MA 02111-1307 USA
025: *
026: * @author Emil Ong
027: */
028:
029: package com.caucho.jaxb;
030:
031: import org.w3c.dom.Document;
032: import org.w3c.dom.Element;
033: import org.w3c.dom.Node;
034:
035: import javax.xml.bind.JAXBException;
036: import javax.xml.bind.annotation.XmlAnyAttribute;
037: import javax.xml.bind.annotation.XmlAnyElement;
038: import javax.xml.bind.annotation.XmlAttribute;
039: import javax.xml.bind.annotation.XmlElement;
040: import javax.xml.bind.annotation.XmlElements;
041: import javax.xml.bind.annotation.XmlElementRef;
042: import javax.xml.bind.annotation.XmlID;
043: import javax.xml.bind.annotation.XmlSchema;
044: import javax.xml.bind.annotation.XmlType;
045: import javax.xml.bind.annotation.XmlValue;
046: import javax.xml.datatype.DatatypeFactory;
047: import javax.xml.datatype.DatatypeConfigurationException;
048: import javax.xml.datatype.XMLGregorianCalendar;
049: import javax.xml.namespace.QName;
050: import javax.xml.stream.XMLEventFactory;
051: import javax.xml.ws.Holder;
052:
053: import static java.lang.Character.*;
054: import java.lang.reflect.AnnotatedElement;
055: import java.lang.reflect.GenericArrayType;
056: import java.lang.reflect.Method;
057: import java.lang.reflect.ParameterizedType;
058: import java.lang.reflect.Type;
059: import java.math.BigDecimal;
060: import java.math.BigInteger;
061: import java.util.ArrayList;
062: import java.util.Calendar;
063: import java.util.Collection;
064: import java.util.HashMap;
065: import java.util.List;
066: import java.util.Map;
067: import java.util.logging.Logger;
068:
069: import com.caucho.util.L10N;
070:
071: /**
072: * JAXB utilities.
073: */
074: public class JAXBUtil {
075: private static final L10N L = new L10N(JAXBUtil.class);
076: private static final Logger log = Logger.getLogger(JAXBUtil.class
077: .getName());
078:
079: private static final Map<Class, QName> _datatypeMap = new HashMap<Class, QName>();
080: private static final Map<QName, Class> _classMap = new HashMap<QName, Class>();
081:
082: private static DatatypeFactory _datatypeFactory;
083:
084: public static final XMLEventFactory EVENT_FACTORY = XMLEventFactory
085: .newInstance();
086:
087: public static final String XML_SCHEMA_NS = "http://www.w3.org/2001/XMLSchema";
088: public static final String XML_SCHEMA_PREFIX = "xsd";
089:
090: public static DatatypeFactory getDatatypeFactory()
091: throws JAXBException {
092: if (_datatypeFactory == null) {
093: try {
094: _datatypeFactory = DatatypeFactory.newInstance();
095: } catch (DatatypeConfigurationException e) {
096: throw new JAXBException(e);
097: }
098: }
099:
100: return _datatypeFactory;
101: }
102:
103: public static QName qnameFromNode(Node node) {
104: if (node == null)
105: return null;
106:
107: int colon = node.getNodeName().indexOf(':');
108:
109: if (colon > 0) {
110: String prefix = node.getNodeName().substring(0, colon);
111: String localName = node.getNodeName().substring(colon + 1);
112:
113: return new QName(node.getNamespaceURI(), localName, prefix);
114: } else if (node.getNamespaceURI() != null)
115: return new QName(node.getNamespaceURI(), node.getNodeName());
116: else
117: return new QName(node.getNodeName());
118: }
119:
120: public static Element elementFromQName(QName name, Node node) {
121: Document doc = node.getOwnerDocument();
122:
123: if (name.getPrefix() != null)
124: return doc.createElementNS(name.getNamespaceURI(), name
125: .getPrefix()
126: + ':' + name.getLocalPart());
127: else if (name.getNamespaceURI() != null)
128: return doc.createElementNS(name.getNamespaceURI(), name
129: .getLocalPart());
130: else
131: return doc.createElement(name.getLocalPart());
132: }
133:
134: // skip all the whitespace and comments
135: public static Node skipIgnorableNodes(Node node) {
136: while (node != null) {
137: if (node.getNodeType() == Node.TEXT_NODE) {
138: String text = node.getTextContent();
139:
140: boolean whitespace = true;
141:
142: for (int i = 0; i < text.length(); i++) {
143: if (!Character.isWhitespace(text.charAt(i))) {
144: whitespace = false;
145: break;
146: }
147: }
148:
149: if (!whitespace)
150: break;
151: } else if (node.getNodeType() != Node.COMMENT_NODE)
152: break;
153:
154: node = node.getNextSibling();
155: }
156:
157: return node;
158: }
159:
160: /**
161: * Gets the type of a parameter. If the type is something like Holder<T>,
162: * it return T, otherwise, it returns the passed type.
163: *
164: **/
165: public static Type getActualParameterType(Type type)
166: throws JAXBException {
167: if (type instanceof ParameterizedType) {
168: ParameterizedType ptype = (ParameterizedType) type;
169:
170: if (ptype.getRawType().equals(Holder.class)) {
171: Type[] arguments = ptype.getActualTypeArguments();
172:
173: if (arguments.length != 1)
174: throw new JAXBException(
175: "Holder has incorrect number of arguments");
176:
177: return arguments[0];
178: }
179: }
180:
181: return type;
182: }
183:
184: public static void introspectClass(Class cl,
185: Collection<Class> jaxbClasses) throws JAXBException {
186: log.finest("Introspecting class " + cl.getName());
187:
188: Method[] methods = cl.getMethods();
189:
190: for (Method method : methods)
191: introspectMethod(method, jaxbClasses);
192: }
193:
194: /**
195: * Finds all the classes mentioned in a method signature (return type and
196: * parameters) and adds them to the passed in classList. Pass in a set if
197: * you expect multiple references.
198: */
199: public static void introspectMethod(Method method,
200: Collection<Class> jaxbClasses) throws JAXBException {
201: log.finest("Introspecting method " + method.getName());
202:
203: introspectType(method.getReturnType(), jaxbClasses);
204:
205: Type[] params = method.getGenericParameterTypes();
206:
207: for (Type param : params) {
208: if (param.equals(Holder.class))
209: continue;
210:
211: introspectType(getActualParameterType(param), jaxbClasses);
212: }
213:
214: // XXX: Check for @WebFault annotation
215:
216: /*
217: Type[] exceptions = method.getGenericExceptionTypes();
218:
219: for (Type exception : exceptions) {
220: if (! exception.toString().endsWith("_Exception"))
221: introspectType(exception, jaxbClasses);
222: }*/
223: }
224:
225: /**
226: * Add all classes referenced by type to jaxbClasses.
227: */
228: private static void introspectType(Type type,
229: Collection<Class> jaxbClasses) {
230: log.finest(" Introspecting type " + type);
231:
232: if (type instanceof Class) {
233: Class cl = (Class) type;
234:
235: if (!cl.isInterface())
236: jaxbClasses.add((Class) type);
237: } else if (type instanceof ParameterizedType) {
238: ParameterizedType pType = (ParameterizedType) type;
239:
240: introspectType(pType.getRawType(), jaxbClasses);
241: introspectType(pType.getOwnerType(), jaxbClasses);
242:
243: Type[] arguments = pType.getActualTypeArguments();
244:
245: for (Type argument : arguments)
246: introspectType(argument, jaxbClasses);
247: } else if (type instanceof GenericArrayType) {
248: Type component = ((GenericArrayType) type)
249: .getGenericComponentType();
250: introspectType(component, jaxbClasses);
251: } else if (type != null) {
252: // Type variables must be instantiated
253: throw new UnsupportedOperationException(
254: L
255: .l(
256: "Method arguments cannot have uninstantiated type variables or wildcards ({0} of type {1})",
257: type, type.getClass().getName()));
258: }
259: }
260:
261: public static String primitiveToWrapperName(Class cl) {
262: if (cl.getName().equals("int"))
263: return "Integer";
264: else if (cl.getName().equals("char"))
265: return "Character";
266: else
267: return toUpperCase(cl.getName().charAt(0))
268: + cl.getName().substring(1);
269: }
270:
271: /**
272: * Tests for punctuation according to JAXB page 334.
273: */
274: private static boolean isPunctuation(char ch) {
275: return "-.:\u00B7\u0387\u06DD\u06dd\u06de_".indexOf((int) ch) >= 0;
276: }
277:
278: /**
279: * Tests for "uncased" characters.
280: */
281: private static boolean isUncased(char ch) {
282: return (!isLowerCase(ch)) && (!isUpperCase(ch));
283: }
284:
285: /**
286: * Splits a string into XML "words" as defined by the JAXB standard.
287: * (see page 162 and appendix D)
288: *
289: */
290: private static List<StringBuilder> splitIdentifier(String identifier) {
291: List<StringBuilder> words = new ArrayList<StringBuilder>();
292: StringBuilder word = new StringBuilder();
293: char lastCh = 0;
294:
295: for (int i = 0; i < identifier.length(); i++) {
296: char ch = identifier.charAt(i);
297:
298: // punctuation shouldn't be common for the java -> xml direction
299: if (word.length() > 0 && isPunctuation(ch)) {
300: words.add(word);
301: word = new StringBuilder();
302: } else if (isDigit(ch)) {
303: if (word.length() > 0 && !isDigit(lastCh)) {
304: words.add(word);
305: word = new StringBuilder();
306: }
307:
308: word.append(ch);
309: } else if (i > 0) { // all of the following need lastCh
310: if (isLowerCase(lastCh) && isUpperCase(ch)) {
311: words.add(word);
312: word = new StringBuilder();
313: word.append(ch);
314: } else if (isUpperCase(lastCh) && isLowerCase(ch)) {
315: // need to steal the last character from the current word
316: // for the next word (e.g. FOOBar -> { "FOO", "Bar" })
317:
318: if (word.length() > 1) {
319: word.deleteCharAt(word.length() - 1);
320: words.add(word);
321: }
322:
323: word = new StringBuilder();
324: word.append(lastCh);
325: word.append(ch);
326: } else if (isLetter(lastCh) != isLetter(ch)) {
327: words.add(word);
328: word = new StringBuilder();
329: word.append(ch);
330: } else if (isUncased(lastCh) != isUncased(ch)) {
331: words.add(word);
332: word = new StringBuilder();
333: word.append(ch);
334: } else
335: word.append(ch);
336: } else
337: word.append(ch);
338:
339: lastCh = ch;
340: }
341:
342: if (word.length() > 0)
343: words.add(word);
344:
345: return words;
346: }
347:
348: public static String identifierToXmlName(Class cl) {
349: List<StringBuilder> words = splitIdentifier(cl.getSimpleName());
350: StringBuilder xmlName = new StringBuilder();
351:
352: xmlName.append(toLowerCase(words.get(0).charAt(0)));
353: xmlName.append(words.get(0).substring(1));
354:
355: for (int i = 1; i < words.size(); i++) {
356: if (words.get(i).length() > 0) {
357: xmlName.append(toUpperCase(words.get(i).charAt(0)));
358: xmlName.append(words.get(i).substring(1));
359: }
360: }
361:
362: return xmlName.toString();
363: }
364:
365: public static String xmlNameToClassName(String name) {
366: // XXX FIXME
367:
368: if (name.length() > 1)
369: return toUpperCase(name.charAt(0)) + name.substring(1);
370: else
371: return toUpperCase(name.charAt(0)) + "";
372: }
373:
374: /// XXX this is sooooooooo wrong. It belongs in JAXBContextImpl
375: public static QName getXmlSchemaDatatype(Class cl,
376: JAXBContextImpl context) {
377: if (_datatypeMap.containsKey(cl))
378: return _datatypeMap.get(cl);
379:
380: String name = null;
381: String namespace = context.getTargetNamespace();
382:
383: Package pkg = cl.getPackage();
384:
385: // look at package defaults first...
386: XmlSchema schema = (XmlSchema) pkg
387: .getAnnotation(XmlSchema.class);
388:
389: if (schema != null && !"".equals(schema.namespace()))
390: namespace = schema.namespace();
391:
392: if (cl.isAnnotationPresent(XmlType.class)) {
393: XmlType xmlType = (XmlType) cl.getAnnotation(XmlType.class);
394:
395: if (!"##default".equals(xmlType.name()))
396: name = xmlType.name();
397:
398: if (!"##default".equals(xmlType.namespace()))
399: namespace = xmlType.namespace();
400: }
401:
402: if (name == null)
403: name = identifierToXmlName(cl);
404:
405: QName qname = null;
406:
407: if (namespace == null)
408: qname = new QName(name);
409: else
410: qname = new QName(namespace, name);
411:
412: _datatypeMap.put(cl, qname);
413:
414: return qname;
415: }
416:
417: public static Class getClassForDatatype(QName qname) {
418: return _classMap.get(qname);
419: }
420:
421: public static String qNameToString(QName qName) {
422: if (qName.getPrefix() == null || "".equals(qName.getPrefix()))
423: return qName.getLocalPart();
424: else
425: return qName.getPrefix() + ':' + qName.getLocalPart();
426: }
427:
428: public static boolean isJAXBAnnotated(AnnotatedElement element) {
429: return element.isAnnotationPresent(XmlAnyAttribute.class)
430: || element.isAnnotationPresent(XmlAnyElement.class)
431: || element.isAnnotationPresent(XmlAttribute.class)
432: || element.isAnnotationPresent(XmlElement.class)
433: || element.isAnnotationPresent(XmlElements.class)
434: || element.isAnnotationPresent(XmlElementRef.class)
435: || element.isAnnotationPresent(XmlID.class)
436: || element.isAnnotationPresent(XmlValue.class);
437: }
438:
439: static {
440: QName stringQName = new QName(XML_SCHEMA_NS, "string",
441: XML_SCHEMA_PREFIX);
442: _datatypeMap.put(String.class, stringQName);
443: _classMap.put(stringQName, String.class);
444:
445: QName bigDecimalQName = new QName(XML_SCHEMA_NS, "decimal",
446: XML_SCHEMA_PREFIX);
447: _datatypeMap.put(BigDecimal.class, bigDecimalQName);
448: _classMap.put(bigDecimalQName, BigDecimal.class);
449:
450: QName bigIntegerQName = new QName(XML_SCHEMA_NS, "integer",
451: XML_SCHEMA_PREFIX);
452: _datatypeMap.put(BigInteger.class, bigIntegerQName);
453: _classMap.put(bigIntegerQName, BigInteger.class);
454:
455: QName booleanQName = new QName(XML_SCHEMA_NS, "boolean",
456: XML_SCHEMA_PREFIX);
457: _datatypeMap.put(Boolean.class, booleanQName);
458: _datatypeMap.put(boolean.class, booleanQName);
459: _classMap.put(booleanQName, boolean.class);
460:
461: // XXX hexBinary
462: QName base64BinaryQName = new QName(XML_SCHEMA_NS,
463: "base64Binary", XML_SCHEMA_PREFIX);
464: _datatypeMap.put(Byte[].class, base64BinaryQName);
465: _datatypeMap.put(byte[].class, base64BinaryQName);
466: _classMap.put(base64BinaryQName, byte[].class);
467:
468: QName byteQName = new QName(XML_SCHEMA_NS, "byte",
469: XML_SCHEMA_PREFIX);
470: _datatypeMap.put(Byte.class, byteQName);
471: _datatypeMap.put(byte.class, byteQName);
472: _classMap.put(byteQName, byte.class);
473:
474: QName charQName = new QName(XML_SCHEMA_NS, "unsignedShort",
475: XML_SCHEMA_PREFIX);
476: _datatypeMap.put(Character.class, charQName);
477: _datatypeMap.put(char.class, charQName);
478: _classMap.put(charQName, char.class);
479:
480: // XXX time
481: QName calendarQName = new QName(XML_SCHEMA_NS, "date",
482: XML_SCHEMA_PREFIX);
483: _datatypeMap.put(Calendar.class, calendarQName);
484: _classMap.put(calendarQName, Calendar.class);
485:
486: QName dateTimeQName = new QName(XML_SCHEMA_NS, "dateTime",
487: XML_SCHEMA_PREFIX);
488: _datatypeMap.put(XMLGregorianCalendar.class, dateTimeQName);
489: _classMap.put(dateTimeQName, XMLGregorianCalendar.class);
490:
491: QName doubleQName = new QName(XML_SCHEMA_NS, "double",
492: XML_SCHEMA_PREFIX);
493: _datatypeMap.put(Double.class, doubleQName);
494: _datatypeMap.put(double.class, doubleQName);
495: _classMap.put(doubleQName, double.class);
496:
497: QName floatQName = new QName(XML_SCHEMA_NS, "float",
498: XML_SCHEMA_PREFIX);
499: _datatypeMap.put(Float.class, floatQName);
500: _datatypeMap.put(float.class, floatQName);
501: _classMap.put(floatQName, float.class);
502:
503: QName intQName = new QName(XML_SCHEMA_NS, "int",
504: XML_SCHEMA_PREFIX);
505: _datatypeMap.put(Integer.class, intQName);
506: _datatypeMap.put(int.class, intQName);
507: _classMap.put(intQName, int.class);
508:
509: QName longQName = new QName(XML_SCHEMA_NS, "long",
510: XML_SCHEMA_PREFIX);
511: _datatypeMap.put(Long.class, longQName);
512: _datatypeMap.put(long.class, longQName);
513: _classMap.put(longQName, long.class);
514:
515: QName shortQName = new QName(XML_SCHEMA_NS, "short",
516: XML_SCHEMA_PREFIX);
517: _datatypeMap.put(Short.class, shortQName);
518: _datatypeMap.put(short.class, shortQName);
519: _classMap.put(shortQName, short.class);
520: }
521: }
|