Debian Codegraph @

src/main/java/com/fasterxml/jackson/module/jaxb/JaxbAnnotationIntrospector.java

raw
1 package com.fasterxml.jackson.module.jaxb;
2
3 import java.beans.Introspector;
4 import java.lang.annotation.Annotation;
5 import java.lang.reflect.*;
6 import java.util.*;
7
8 import javax.xml.bind.*;
9 import javax.xml.bind.annotation.*;
10 import javax.xml.bind.annotation.adapters.*;
11
12 import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
13 import com.fasterxml.jackson.annotation.*;
14 import com.fasterxml.jackson.core.*;
15 import com.fasterxml.jackson.databind.*;
16 import com.fasterxml.jackson.databind.cfg.MapperConfig;
17 import com.fasterxml.jackson.databind.introspect.*;
18 import com.fasterxml.jackson.databind.jsontype.NamedType;
19 import com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder;
20 import com.fasterxml.jackson.databind.jsontype.impl.StdTypeResolverBuilder;
21 import com.fasterxml.jackson.databind.type.TypeFactory;
22 import com.fasterxml.jackson.databind.util.BeanUtil;
23 import com.fasterxml.jackson.databind.util.ClassUtil;
24 import com.fasterxml.jackson.databind.util.Converter;
25 import com.fasterxml.jackson.module.jaxb.deser.DataHandlerJsonDeserializer;
26 import com.fasterxml.jackson.module.jaxb.ser.DataHandlerJsonSerializer;
27
28 /**
29 * Annotation introspector that leverages JAXB annotations where applicable to JSON mapping.
30 * As of Jackson 2.0, most JAXB annotations are supported at least to some degree.
31 * Ones that are NOT yet supported are:
32 * <ul>
33 * <li>{@link XmlAnyAttribute} not yet used (as of 1.5) but may be in future (as an alias for @JsonAnySetter?)
34 * <li>{@link XmlAnyElement} not yet used, may be as per [JACKSON-253]
35 * <li>{@link javax.xml.bind.annotation.XmlAttachmentRef}: JSON does not support external attachments
36 * <li>{@link XmlElementDecl}
37 * <li>{@link XmlElementRefs} because Jackson doesn't have any support for 'named' collection items -- however,
38 * this may become partially supported as per [JACKSON-253].
39 * <li>{@link javax.xml.bind.annotation.XmlInlineBinaryData} since the underlying concepts
40 * (like XOP) do not exist in JSON -- Jackson will always use inline base64 encoding as the method
41 * <li>{@link javax.xml.bind.annotation.XmlList} because JSON does have (or necessarily need)
42 * method of serializing list of values as space-separated Strings
43 * <li>{@link javax.xml.bind.annotation.XmlMimeType}
44 * <li>{@link javax.xml.bind.annotation.XmlMixed} since JSON has no concept of mixed content
45 * <li>{@link XmlRegistry}
46 * <li>{@link XmlSchema} not used, unlikely to be used
47 * <li>{@link XmlSchemaType} not used, unlikely to be used
48 * <li>{@link XmlSchemaTypes} not used, unlikely to be used
49 * <li>{@link XmlSeeAlso} not yet supported, but [ISSUE-1] filed to use it, so may be supported.
50 * </ul>
51 *
52 * Note also the following limitations:
53 *
54 * <ul>
55 * <li>Any property annotated with {@link XmlValue} will have implicit property named 'value' on
56 * its JSON object; although (as of 2.4) it should be possible to override this name
57 * </li>
58 * </ul>
59 *<p>
60 * A note on compatibility with Jackson XML module: since this module does not depend
61 * on Jackson XML module, it is bit difficult to make sure we will properly expose
62 * all information. But effort is made (as of version 2.3.3) to expose this information,
63 * even without using a specific sub-class from that project.
64 *
65 * @author Ryan Heaton
66 * @author Tatu Saloranta
67 */
68 public class JaxbAnnotationIntrospector
69 extends AnnotationIntrospector
70 implements Versioned
71 {
72 private static final long serialVersionUID = -1L;
73
74 protected final static String DEFAULT_NAME_FOR_XML_VALUE = "value";
75
76 protected final static boolean DEFAULT_IGNORE_XMLIDREF = false;
77
78 protected final static String MARKER_FOR_DEFAULT = "##default";
79
80 // @since 2.5
81 protected final static JsonFormat.Value FORMAT_STRING = new JsonFormat.Value().withShape(JsonFormat.Shape.STRING);
82
83 // @since 2.5
84 protected final static JsonFormat.Value FORMAT_INT = new JsonFormat.Value().withShape(JsonFormat.Shape.NUMBER_INT);
85
86 protected final String _jaxbPackageName;
87 protected final JsonSerializer<?> _dataHandlerSerializer;
88 protected final JsonDeserializer<?> _dataHandlerDeserializer;
89
90 protected final TypeFactory _typeFactory;
91
92 protected final boolean _ignoreXmlIDREF;
93
94 /**
95 * When using {@link XmlValue} annotation, a placeholder name is assigned
96 * to property (unless overridden by explicit name); this configuration
97 * value specified what that name is.
98 */
99 protected String _xmlValueName = DEFAULT_NAME_FOR_XML_VALUE;
100
101 /**
102 * Inclusion value to return for properties annotated with
103 * {@link XmlElement} and {@link XmlElementWrapper}, in case <code>nillable</code>
104 * property is left as <code>false</false>. Default setting is
105 * <code>null</code>; this is typically changed to either
106 * {@link com.fasterxml.jackson.annotation.JsonInclude.Include#NON_NULL}
107 * or {@link com.fasterxml.jackson.annotation.JsonInclude.Include#NON_EMPTY}.
108 *
109 * @since 2.7
110 */
111 protected JsonInclude.Include _nonNillableInclusion = null;
112
113 /**
114 * @deprecated Since 2.1, use constructor that takes TypeFactory.
115 */
116 @Deprecated
117 public JaxbAnnotationIntrospector() {
118 this(TypeFactory.defaultInstance());
119 }
120
121 public JaxbAnnotationIntrospector(MapperConfig<?> config) {
122 this(config.getTypeFactory());
123 }
124
125 public JaxbAnnotationIntrospector(TypeFactory typeFactory) {
126 this(typeFactory, DEFAULT_IGNORE_XMLIDREF);
127 }
128
129 /**
130 * @param typeFactory Type factory used for resolving type information
131 * @param ignoreXmlIDREF Whether {@link XmlIDREF} annotation should be processed
132 * JAXB style (meaning that references are always serialized using id), or
133 * not (first reference as full POJO, others as ids)
134 */
135 public JaxbAnnotationIntrospector(TypeFactory typeFactory, boolean ignoreXmlIDREF)
136 {
137 _typeFactory = (typeFactory == null)? TypeFactory.defaultInstance() : typeFactory;
138 _ignoreXmlIDREF = ignoreXmlIDREF;
139 _jaxbPackageName = XmlElement.class.getPackage().getName();
140
141 JsonSerializer<?> dataHandlerSerializer = null;
142 JsonDeserializer<?> dataHandlerDeserializer = null;
143 /* Data handlers included dynamically, to try to prevent issues on platforms
144 * with less than complete support for JAXB API
145 */
146 try {
147 dataHandlerSerializer = (JsonSerializer<?>) DataHandlerJsonSerializer.class.newInstance();
148 dataHandlerDeserializer = (JsonDeserializer<?>) DataHandlerJsonDeserializer.class.newInstance();
149 } catch (Throwable e) {
150 //dataHandlers not supported...
151 }
152 _dataHandlerSerializer = dataHandlerSerializer;
153 _dataHandlerDeserializer = dataHandlerDeserializer;
154 }
155
156 /**
157 * Method that will return version information stored in and read from jar
158 * that contains this class.
159 */
160 @Override
161 public Version version() {
162 return PackageVersion.VERSION;
163 }
164
165 /*
166 /**********************************************************
167 /* Configuration
168 /**********************************************************
169 */
170
171 /**
172 * Configuration method that can be used to change default name
173 * ("value") used for properties annotated with {@link XmlValue};
174 * note that setting it to <code>null</code> will actually avoid
175 * name override, and name will instead be derived from underlying
176 * method name using standard bean name introspection.
177 *
178 * @since 2.5
179 */
180 public void setNameUsedForXmlValue(String name) {
181 _xmlValueName = name;
182 }
183
184 /**
185 * Accessor for getting currently configured placeholder named
186 * used for property annotated with {@link XmlValue}.
187 */
188 public String getNameUsedForXmlValue() {
189 return _xmlValueName;
190 }
191
192 /**
193 * Method to call to change inclusion criteria used for property annotated
194 * with {@link XmlElement} or {@link XmlElementWrapper}, with <code>nillable</code>
195 * set as <code>false</code>.
196 *
197 * @since 2.7
198 */
199 public JaxbAnnotationIntrospector setNonNillableInclusion(JsonInclude.Include incl) {
200 _nonNillableInclusion = incl;
201 return this;
202 }
203
204 /**
205 * @since 2.7
206 */
207 public JsonInclude.Include getNonNillableInclusion() {
208 return _nonNillableInclusion;
209 }
210
211 /*
212 /**********************************************************
213 /* Extended API (XmlAnnotationIntrospector)
214 /**********************************************************
215 */
216
217 // From XmlAnnotationIntrospector
218 // @Override
219 public String findNamespace(Annotated ann) {
220 String ns = null;
221 if (ann instanceof AnnotatedClass) {
222 // For classes, it must be @XmlRootElement. Also, we do
223 // want to use defaults from package, base class
224 XmlRootElement elem = findRootElementAnnotation((AnnotatedClass) ann);
225 if (elem != null) {
226 ns = elem.namespace();
227 }
228 } else {
229 // For others, XmlElement or XmlAttribute work (anything else?)
230 XmlElement elem = findAnnotation(XmlElement.class, ann, false, false, false);
231 if (elem != null) {
232 ns = elem.namespace();
233 }
234 if (ns == null || MARKER_FOR_DEFAULT.equals(ns)) {
235 XmlAttribute attr = findAnnotation(XmlAttribute.class, ann, false, false, false);
236 if (attr != null) {
237 ns = attr.namespace();
238 }
239 }
240 }
241 // JAXB uses marker for "not defined"
242 if (MARKER_FOR_DEFAULT.equals(ns)) {
243 ns = null;
244 }
245 return ns;
246 }
247
248 // From XmlAnnotationIntrospector
249 // @Override
250 /**
251 * Here we assume fairly simple logic; if there is <code>XmlAttribute</code> to be found,
252 * we consider it an attribute; if <code>XmlElement</code>, not-an-attribute; and otherwise
253 * we will consider there to be no information.
254 * Caller is likely to default to considering things as elements.
255 */
256 public Boolean isOutputAsAttribute(Annotated ann) {
257 XmlAttribute attr = findAnnotation(XmlAttribute.class, ann, false, false, false);
258 if (attr != null) {
259 return Boolean.TRUE;
260 }
261 XmlElement elem = findAnnotation(XmlElement.class, ann, false, false, false);
262 if (elem != null) {
263 return Boolean.FALSE;
264 }
265 return null;
266 }
267
268 // From XmlAnnotationIntrospector
269 // @Override
270 public Boolean isOutputAsText(Annotated ann) {
271 XmlValue attr = findAnnotation(XmlValue.class, ann, false, false, false);
272 if (attr != null) {
273 return Boolean.TRUE;
274 }
275 return null;
276 }
277
278 /*
279 /**********************************************************
280 /* General annotations (for classes, properties)
281 /**********************************************************
282 */
283
284 @Override
285 public ObjectIdInfo findObjectIdInfo(Annotated ann)
286 {
287 /* To work in the way that works with JAXB and Jackson,
288 * we need to do things in bit of round-about way, starting
289 * with AnnotatedClass, locating @XmlID property, if any.
290 */
291 if (!(ann instanceof AnnotatedClass)) {
292 return null;
293 }
294 AnnotatedClass ac = (AnnotatedClass) ann;
295 /* Ideally, should not have to infer settings for class from
296 * individual fields and/or methods; but for now this
297 * has to do ...
298 */
299 PropertyName idPropName = null;
300
301 method_loop:
302 for (AnnotatedMethod m : ac.memberMethods()) {
303 XmlID idProp = m.getAnnotation(XmlID.class);
304 if (idProp == null) {
305 continue;
306 }
307 switch (m.getParameterCount()) {
308 case 0: // getter
309 idPropName = findJaxbPropertyName(m, m.getRawType(),
310 BeanUtil.okNameForGetter(m, true));
311 break method_loop;
312 case 1: // setter
313 idPropName = findJaxbPropertyName(m, m.getRawType(),
314 BeanUtil.okNameForSetter(m, true));
315 break method_loop;
316 }
317 }
318 if (idPropName == null) {
319 for (AnnotatedField f : ac.fields()) {
320 XmlID idProp = f.getAnnotation(XmlID.class);
321 if (idProp != null) {
322 idPropName = findJaxbPropertyName(f, f.getRawType(), f.getName());
323 break;
324 }
325 }
326 }
327 if (idPropName != null) {
328 /* Scoping... hmmh. Could XML requires somewhat global scope, n'est pas?
329 * The alternative would be to use declared type of this class.
330 */
331 Class<?> scope = Object.class; // alternatively would use 'ac.getRawType()'
332 // and we will assume that there exists property thus named...
333 return new ObjectIdInfo(idPropName,
334 scope, ObjectIdGenerators.PropertyGenerator.class,
335 // should we customize Object Id resolver somehow?
336 SimpleObjectIdResolver.class);
337 }
338
339 return null;
340 }
341
342 @Override
343 public ObjectIdInfo findObjectReferenceInfo(Annotated ann, ObjectIdInfo base)
344 {
345 if (!_ignoreXmlIDREF) {
346 XmlIDREF idref = ann.getAnnotation(XmlIDREF.class);
347 /* JAXB makes XmlIDREF mean "always as id", as far as I know.
348 * May need to make it configurable in future, but for not that
349 * is fine...
350 */
351 if (idref != null) {
352 if (base == null) {
353 base = ObjectIdInfo.empty();
354 }
355 base = base.withAlwaysAsId(true);
356 }
357 }
358 return base;
359 }
360
361 /*
362 /**********************************************************
363 /* General class annotations
364 /**********************************************************
365 */
366
367 @Override
368 public PropertyName findRootName(AnnotatedClass ac)
369 {
370 XmlRootElement elem = findRootElementAnnotation(ac);
371 if (elem != null) {
372 return _combineNames(elem.name(), elem.namespace(), "");
373 }
374 return null;
375 }
376
377 /*
378 @Override
379 public String[] findPropertiesToIgnore(Annotated a) {
380 // nothing in JAXB for this?
381 return null;
382 }
383 */
384
385 /* 08-Nov-2009, tatus: This is bit trickier: by default JAXB
386 * does actually ignore all unknown properties.
387 * But since there is no annotation to
388 * specify or change this, it seems wrong to claim such setting
389 * is in effect. May need to revisit this issue in future
390 */
391 /*
392 @Override
393 public Boolean findIgnoreUnknownProperties(AnnotatedClass ac);
394
395 @Override
396 public JsonIgnoreProperties.Value findPropertyIgnorals(Annotated ac);
397 */
398
399 @Override
400 public Boolean isIgnorableType(AnnotatedClass ac) {
401 // Does JAXB have any such indicators? No?
402 return null;
403 }
404
405 /*
406 /**********************************************************
407 /* General member (field, method/constructor) annotations
408 /**********************************************************
409 */
410
411 @Override
412 public boolean hasIgnoreMarker(AnnotatedMember m) {
413 return m.getAnnotation(XmlTransient.class) != null;
414 }
415
416 //(ryan) JAXB has @XmlAnyAttribute and @XmlAnyElement annotations, but they're not applicable in this case
417 // because JAXB says those annotations are only applicable to methods with specific signatures
418 // that Jackson doesn't support (Jackson's any setter needs 2 arguments, name and value, whereas
419 // JAXB expects use of Map
420
421 // 28-May-2016, tatu: While `@XmlAnyAttribute` looks ALMOST like applicable (esp.
422 // assuming Jackson could use `Map` field, not just setter/getter), it is alas not.
423 // The reason is that key is expected to be `QNmae`, XML/JAXB specific name and
424 // something Jackson does not require or use
425
426 /*
427 @Override
428 public boolean hasAnySetterAnnotation(AnnotatedMethod am) { }
429
430 @Override
431 public boolean hasAnySetterAnnotation(AnnotatedMethod am)
432 */
433
434 @Override
435 public Boolean hasRequiredMarker(AnnotatedMember m) {
436 XmlElement elem = m.getAnnotation(XmlElement.class);
437 if ((elem != null) && elem.required()) {
438 return Boolean.TRUE;
439 }
440 XmlAttribute attr = m.getAnnotation(XmlAttribute.class);
441 if ((attr != null) && attr.required()) {
442 return Boolean.TRUE;
443 }
444 // 09-Sep-2015, tatu: Not 100% sure that we should ever return `false`
445 // here (as it blocks calls to secondary introspector), but since that
446 // was the existing behavior before 2.6, is retained for now.
447 if ((elem != null) || (attr != null)) {
448 return null;
449 }
450 return Boolean.FALSE;
451 }
452
453 @Override
454 public PropertyName findWrapperName(Annotated ann)
455 {
456 XmlElementWrapper w = findAnnotation(XmlElementWrapper.class, ann, false, false, false);
457 if (w != null) {
458 /* 18-Sep-2013, tatu: As per [jaxb-annotations#24], need to take special care with empty
459 * String, as that should indicate here "use underlying unmodified
460 * property name" (that is, one NOT overridden by @JsonProperty)
461 */
462 PropertyName name = _combineNames(w.name(), w.namespace(), "");
463 // clumsy, yes, but has to do:
464 if (!name.hasSimpleName()) {
465 if (ann instanceof AnnotatedMethod) {
466 AnnotatedMethod am = (AnnotatedMethod) ann;
467 String str;
468 if (am.getParameterCount() == 0) {
469 str = BeanUtil.okNameForGetter(am, true);
470 } else {
471 str = BeanUtil.okNameForSetter(am, true);
472 }
473 if (str != null) {
474 return name.withSimpleName(str);
475 }
476 }
477 return name.withSimpleName(ann.getName());
478 }
479 return name;
480 }
481 return null;
482 }
483
484 // since 2.4
485 @Override
486 public String findImplicitPropertyName(AnnotatedMember m) {
487 XmlValue valueInfo = m.getAnnotation(XmlValue.class);
488 if (valueInfo != null) {
489 return _xmlValueName;
490 }
491 return null;
492 }
493
494 @Override
495 public JsonFormat.Value findFormat(Annotated m) {
496 /* [jaxb-annotations#33]: Use @XmlEnum value (Class) to indicate format,
497 * iff it makes sense
498 */
499 if (m instanceof AnnotatedClass) {
500 XmlEnum ann = m.getAnnotation(XmlEnum.class);
501 if (ann != null) {
502 Class<?> type = ann.value();
503 if (type == String.class || type.isEnum()) {
504 return FORMAT_STRING;
505 }
506 if (Number.class.isAssignableFrom(type)) {
507 return FORMAT_INT;
508 }
509 }
510 }
511 return null;
512 }
513
514 /*
515 /**********************************************************
516 /* Property auto-detection
517 /**********************************************************
518 */
519
520 @Override
521 public VisibilityChecker<?> findAutoDetectVisibility(AnnotatedClass ac,
522 VisibilityChecker<?> checker)
523 {
524 XmlAccessType at = findAccessType(ac);
525 if (at == null) {
526 /* JAXB default is "PUBLIC_MEMBER"; however, here we should not
527 * override settings if there is no annotation -- that would mess
528 * up global baseline. Fortunately Jackson defaults are very close
529 * to JAXB 'PUBLIC_MEMBER' settings (considering that setters and
530 * getters must come in pairs)
531 */
532 return checker;
533 }
534
535 // Note: JAXB does not do creator auto-detection, can (and should) ignore
536 switch (at) {
537 case FIELD: // all fields, independent of visibility; no methods
538 return checker.withFieldVisibility(Visibility.ANY)
539 .withSetterVisibility(Visibility.NONE)
540 .withGetterVisibility(Visibility.NONE)
541 .withIsGetterVisibility(Visibility.NONE)
542 ;
543 case NONE: // no auto-detection
544 return checker.withFieldVisibility(Visibility.NONE)
545 .withSetterVisibility(Visibility.NONE)
546 .withGetterVisibility(Visibility.NONE)
547 .withIsGetterVisibility(Visibility.NONE)
548 ;
549 case PROPERTY:
550 return checker.withFieldVisibility(Visibility.NONE)
551 .withSetterVisibility(Visibility.PUBLIC_ONLY)
552 .withGetterVisibility(Visibility.PUBLIC_ONLY)
553 .withIsGetterVisibility(Visibility.PUBLIC_ONLY)
554 ;
555 case PUBLIC_MEMBER:
556 return checker.withFieldVisibility(Visibility.PUBLIC_ONLY)
557 .withSetterVisibility(Visibility.PUBLIC_ONLY)
558 .withGetterVisibility(Visibility.PUBLIC_ONLY)
559 .withIsGetterVisibility(Visibility.PUBLIC_ONLY)
560 ;
561 }
562 return checker;
563 }
564
565 /**
566 * Method for locating JAXB {@link XmlAccessType} annotation value
567 * for given annotated entity, if it has one, or inherits one from
568 * its ancestors (in JAXB sense, package etc). Returns null if
569 * nothing has been explicitly defined.
570 */
571 protected XmlAccessType findAccessType(Annotated ac)
572 {
573 XmlAccessorType at = findAnnotation(XmlAccessorType.class, ac, true, true, true);
574 return (at == null) ? null : at.value();
575 }
576
577 /*
578 /**********************************************************
579 /* Class annotations for PM type handling (1.5+)
580 /**********************************************************
581 */
582
583 @Override
584 public TypeResolverBuilder<?> findTypeResolver(MapperConfig<?> config,
585 AnnotatedClass ac, JavaType baseType)
586 {
587 // no per-class type resolvers, right?
588 return null;
589 }
590
591 @Override
592 public TypeResolverBuilder<?> findPropertyTypeResolver(MapperConfig<?> config,
593 AnnotatedMember am, JavaType baseType)
594 {
595 /* First: @XmlElements and @XmlElementRefs only applies type for immediate property, if it
596 * is NOT a structured type.
597 */
598 if (baseType.isContainerType()) return null;
599 return _typeResolverFromXmlElements(am);
600 }
601
602 @Override
603 public TypeResolverBuilder<?> findPropertyContentTypeResolver(MapperConfig<?> config,
604 AnnotatedMember am, JavaType containerType)
605 {
606 /* First: let's ensure property is a container type: caller should have
607 * verified but just to be sure
608 */
609 if (containerType.getContentType() == null) {
610 throw new IllegalArgumentException("Must call method with a container or reference type (got "+containerType+")");
611 }
612 return _typeResolverFromXmlElements(am);
613 }
614
615 protected TypeResolverBuilder<?> _typeResolverFromXmlElements(AnnotatedMember am)
616 {
617 /* If simple type, @XmlElements and @XmlElementRefs are applicable.
618 * Note: @XmlElement and @XmlElementRef are NOT handled here, since they
619 * are handled specifically as non-polymorphic indication
620 * of the actual type
621 */
622 XmlElements elems = findAnnotation(XmlElements.class, am, false, false, false);
623 XmlElementRefs elemRefs = findAnnotation(XmlElementRefs.class, am, false, false, false);
624 if (elems == null && elemRefs == null) {
625 return null;
626 }
627
628 TypeResolverBuilder<?> b = new StdTypeResolverBuilder();
629 // JAXB always uses type name as id
630 b = b.init(JsonTypeInfo.Id.NAME, null);
631 // and let's consider WRAPPER_OBJECT to be canonical inclusion method
632 b = b.inclusion(JsonTypeInfo.As.WRAPPER_OBJECT);
633 return b;
634 }
635
636 @Override
637 public List<NamedType> findSubtypes(Annotated a)
638 {
639 // No package/superclass defaulting (only used with fields, methods)
640 XmlElements elems = findAnnotation(XmlElements.class, a, false, false, false);
641 ArrayList<NamedType> result = null;
642 if (elems != null) {
643 result = new ArrayList<NamedType>();
644 for (XmlElement elem : elems.value()) {
645 String name = elem.name();
646 if (MARKER_FOR_DEFAULT.equals(name)) name = null;
647 result.add(new NamedType(elem.type(), name));
648 }
649 } else {
650 XmlElementRefs elemRefs = findAnnotation(XmlElementRefs.class, a, false, false, false);
651 if (elemRefs != null) {
652 result = new ArrayList<NamedType>();
653 for (XmlElementRef elemRef : elemRefs.value()) {
654 Class<?> refType = elemRef.type();
655 // only good for types other than JAXBElement (which is XML based)
656 if (!JAXBElement.class.isAssignableFrom(refType)) {
657 // first consider explicit name declaration
658 String name = elemRef.name();
659 if (name == null || MARKER_FOR_DEFAULT.equals(name)) {
660 XmlRootElement rootElement = (XmlRootElement) refType.getAnnotation(XmlRootElement.class);
661 if (rootElement != null) {
662 name = rootElement.name();
663 }
664 }
665 if (name == null || MARKER_FOR_DEFAULT.equals(name)) {
666 name = Introspector.decapitalize(refType.getSimpleName());
667 }
668 result.add(new NamedType(refType, name));
669 }
670 }
671 }
672 }
673
674 // Check @XmlSeeAlso as well.
675 /* 17-Aug-2012, tatu: But wait! For structured type, what we really is
676 * value (content) type!
677 * If code below does not make full (or any) sense, do not despair -- it
678 * is wrong. Yet it works. The call sequence before we get here is mangled,
679 * its logic twisted... but as Dire Straits put it: "That ain't working --
680 * that's The Way You Do It!"
681 */
682 XmlSeeAlso ann = a.getAnnotation(XmlSeeAlso.class);
683 if (ann != null) {
684 if (result == null) {
685 result = new ArrayList<NamedType>();
686 }
687 for (Class<?> cls : ann.value()) {
688 result.add(new NamedType(cls));
689 }
690 }
691 return result;
692 }
693
694 @Override
695 public String findTypeName(AnnotatedClass ac) {
696 XmlType type = findAnnotation(XmlType.class, ac, false, false, false);
697 if (type != null) {
698 String name = type.name();
699 if (!MARKER_FOR_DEFAULT.equals(name)) return name;
700 }
701 return null;
702 }
703
704 /*
705 /**********************************************************
706 /* Serialization: general annotations
707 /**********************************************************
708 */
709
710 @Override
711 public JsonSerializer<?> findSerializer(Annotated am)
712 {
713 final Class<?> type = _rawSerializationType(am);
714
715 /*
716 // As per [JACKSON-722], more checks for structured types
717 XmlAdapter<Object,Object> adapter = findAdapter(am, true, type);
718 if (adapter != null) {
719 boolean fromClass = !(am instanceof AnnotatedMember);
720 // Ugh. Must match to see if adapter's bounded type (result to map to) matches property type
721 if (isContainerType(type)) {
722 Class<?> bt = findAdapterBoundType(adapter);
723 if (bt.isAssignableFrom(type)) {
724 return new XmlAdapterJsonSerializer(adapter, fromClass);
725 }
726 // Note: if used for value type, handled in different place
727 } else {
728 return new XmlAdapterJsonSerializer(adapter, fromClass);
729 }
730 }
731 */
732
733 // Add support for additional core XML types needed by JAXB
734 if (type != null) {
735 if (_dataHandlerSerializer != null && isDataHandler(type)) {
736 return _dataHandlerSerializer;
737 }
738 }
739 return null;
740 }
741
742 /**
743 * Determines whether the type is assignable to class javax.activation.DataHandler without requiring that class
744 * to be on the classpath.
745 *
746 * @param type The type.
747 * @return Whether the type is assignable to class javax.activation.DataHandler
748 */
749 private boolean isDataHandler(Class<?> type)
750 {
751 return type != null && (Object.class != type)
752 && (("javax.activation.DataHandler".equals(type.getName()) || isDataHandler(type.getSuperclass())));
753 }
754
755 @Override
756 public Object findContentSerializer(Annotated a) {
757 return null;
758 }
759
760 @Override
761 @Deprecated // since 2.7
762 public Class<?> findSerializationType(Annotated a)
763 {
764 Class<?> allegedType = _getTypeFromXmlElement(a);
765 if (allegedType != null){
766 Class<?> rawPropType = _rawSerializationType(a);
767 if (!isContainerType(rawPropType)) {
768 return allegedType;
769 }
770 }
771 return null;
772 }
773
774 /**
775 * Implementation of this method is slightly tricky, given that JAXB defaults differ
776 * from Jackson defaults. As of version 1.5 and above, this is resolved by honoring
777 * Jackson defaults (which are configurable), and only using JAXB explicit annotations.
778 */
779 @Override
780 @Deprecated // since 2.7; remove from 2.8
781 public JsonInclude.Include findSerializationInclusion(Annotated a, JsonInclude.Include defValue)
782 {
783 XmlElementWrapper w = a.getAnnotation(XmlElementWrapper.class);
784 if (w != null) {
785 if (w.nillable()) {
786 return JsonInclude.Include.ALWAYS;
787 }
788 // [jaxb-annotations#52]: Allow specifying inclusion for `nillable=false` too
789 if (_nonNillableInclusion != null) {
790 return _nonNillableInclusion;
791 }
792 }
793 XmlElement e = a.getAnnotation(XmlElement.class);
794 if (e != null) {
795 if (e.nillable()) {
796 return JsonInclude.Include.ALWAYS;
797 }
798 // [jaxb-annotations#52]: Allow specifying inclusion for `nillable=false` too
799 if (_nonNillableInclusion != null) {
800 return _nonNillableInclusion;
801 }
802 }
803 //better pass default value through, if no explicit direction indicating otherwise
804 return defValue;
805 }
806
807 @Override // @since 2.7
808 public JsonInclude.Value findPropertyInclusion(Annotated a)
809 {
810 JsonInclude.Include incl = findSerializationInclusion(a, null);
811 if (incl == null) {
812 return JsonInclude.Value.empty();
813 }
814 return JsonInclude.Value.construct(incl, null);
815 }
816
817 @Override // @since 2.7
818 public JavaType refineSerializationType(final MapperConfig<?> config,
819 final Annotated a, final JavaType baseType) throws JsonMappingException
820 {
821 Class<?> serClass = _getTypeFromXmlElement(a);
822 if (serClass == null) {
823 return baseType;
824 }
825 // First, JAXB has no annotations for key type, so can skip that part (wrt std annotations)
826 // But the meaning of main annotation(s) varies between container/non-container types
827 final TypeFactory tf = config.getTypeFactory();
828 if (baseType.getContentType() == null) { // non-container/-structured types, usually scalar:
829 // 27-Nov-2015, tatu: Since JAXB has just one annotation, must ignore it in
830 // one direction, typically serialization (but not always):
831 if (!serClass.isAssignableFrom(baseType.getRawClass())) {
832 return baseType;
833 }
834 if (baseType.hasRawClass(serClass)) {
835 // 30-Nov-2015, tatu: As per [databind#1023], need to allow forcing of
836 // static typing this way
837 return baseType.withStaticTyping();
838 }
839 try {
840 return tf.constructGeneralizedType(baseType, serClass);
841 } catch (IllegalArgumentException iae) {
842 throw new JsonMappingException(null,
843 String.format("Failed to widen type %s with annotation (value %s), from '%s': %s",
844 baseType, serClass.getName(), a.getName(), iae.getMessage()),
845 iae);
846 }
847 } else {
848 // Otherwise, structured type:
849 JavaType contentType = baseType.getContentType();
850 if (contentType != null) { // collection[like], map[like], array, reference
851 // as per earlier, may need to ignore annotation meant for deserialization
852 if (!serClass.isAssignableFrom(contentType.getRawClass())) {
853 return baseType;
854 }
855 // And then value types for all containers:
856 if (contentType.hasRawClass(serClass)) {
857 contentType = contentType.withStaticTyping();
858 } else {
859 try {
860 contentType = tf.constructGeneralizedType(contentType, serClass);
861 } catch (IllegalArgumentException iae) {
862 throw new JsonMappingException(null,
863 String.format("Failed to widen value type of %s with concrete-type annotation (value %s), from '%s': %s",
864 baseType, serClass.getName(), a.getName(), iae.getMessage()),
865 iae);
866 }
867 }
868 return baseType.withContentType(contentType);
869 }
870 }
871 return baseType;
872 }
873
874 /*
875 /**********************************************************
876 /* Serialization: class annotations
877 /**********************************************************
878 */
879
880 @Override
881 public String[] findSerializationPropertyOrder(AnnotatedClass ac)
882 {
883 // @XmlType.propOrder fits the bill here:
884 XmlType type = findAnnotation(XmlType.class, ac, true, true, true);
885 if (type == null) {
886 return null;
887 }
888 String[] order = type.propOrder();
889 if (order == null || order.length == 0) {
890 return null;
891 }
892 return order;
893 }
894
895 @Override
896 public Boolean findSerializationSortAlphabetically(Annotated ann) {
897 return _findAlpha(ann);
898 }
899
900 private final Boolean _findAlpha(Annotated ann) {
901 XmlAccessorOrder order = findAnnotation(XmlAccessorOrder.class, ann, true, true, true);
902 return (order == null) ? null : (order.value() == XmlAccessOrder.ALPHABETICAL);
903 }
904
905 @Override
906 public Object findSerializationConverter(Annotated a)
907 {
908 Class<?> serType = _rawSerializationType(a);
909 // Can apply to both container and regular type; no difference yet here
910 XmlAdapter<?,?> adapter = findAdapter(a, true, serType);
911 if (adapter != null) {
912 return _converter(adapter, true);
913 }
914 return null;
915 }
916
917 @Override
918 public Object findSerializationContentConverter(AnnotatedMember a)
919 {
920 // But this one only applies to structured (container) types:
921 Class<?> serType = _rawSerializationType(a);
922 if (isContainerType(serType)) {
923 XmlAdapter<?,?> adapter = _findContentAdapter(a, true);
924 if (adapter != null) {
925 return _converter(adapter, true);
926 }
927 }
928 return null;
929 }
930
931 /*
932 /**********************************************************
933 /* Serialization: property annotations
934 /**********************************************************
935 */
936
937 @Override
938 public PropertyName findNameForSerialization(Annotated a)
939 {
940 // need bit of delegation (note: copy of super-class functionality)
941 if (a instanceof AnnotatedMethod) {
942 AnnotatedMethod am = (AnnotatedMethod) a;
943 if (!isVisible(am)) {
944 return null;
945 }
946 return findJaxbPropertyName(am, am.getRawType(),
947 BeanUtil.okNameForGetter(am, true));
948 }
949 if (a instanceof AnnotatedField) {
950 AnnotatedField af = (AnnotatedField) a;
951 if (!isVisible(af)) {
952 return null;
953 }
954 // Hmmh. As per [jaxb-annotations#61], looks like we must do one more thing to
955 // avoid accidentally exposing transient fields: this is necessary because later on
956 // our returning of "" suggests explicit annotation, which is NOT true, but may be
957 // necessary to indicate that visibility level is satisfied. That works ok except
958 // for specific case of transient fields that we must suppress now
959 if (af.isTransient()) {
960 return null;
961 }
962
963 PropertyName name = findJaxbPropertyName(af, af.getRawType(), null);
964 /* This may seem wrong, but since JAXB field auto-detection
965 * needs to find even non-public fields (if enabled by
966 * JAXB access type), we need to return name like so:
967 */
968 // 31-Oct-2014, tatu: As per [jaxb-annotations#31], need to be careful to indicate "use default"
969 // and NOT to force use of specific name; latter would establish explicit name
970 // and what we want is implicit (unless there is real explicitly annotated name)
971 if (name == null) {
972 return PropertyName.USE_DEFAULT;
973 }
974 return name;
975 }
976 return null;
977 }
978
979 @Override
980 public boolean hasAsValueAnnotation(AnnotatedMethod am) {
981 //since jaxb says @XmlValue can exist with attributes, this won't map as a JSON value.
982 return false;
983 }
984
985 /**
986 *<p>
987 * This is very slow implementation, but as of Jackson 2.7, should not be called any more;
988 * instead, {@link #findEnumValues} should be called which has less overhead.
989 */
990 @Deprecated // since 2.8, remove from 2.9?
991 @Override
992 public String findEnumValue(Enum<?> e)
993 {
994 Class<?> enumClass = e.getDeclaringClass();
995 String enumValue = e.name();
996 try {
997 XmlEnumValue xmlEnumValue = enumClass.getDeclaredField(enumValue).getAnnotation(XmlEnumValue.class);
998 return (xmlEnumValue != null) ? xmlEnumValue.value() : enumValue;
999 } catch (NoSuchFieldException e1) {
1000 throw new IllegalStateException("Could not locate Enum entry '"+enumValue+"' (Enum class "+enumClass.getName()+")", e1);
1001 }
1002 }
1003
1004 @Override // since 2.7
1005 public String[] findEnumValues(Class<?> enumType, Enum<?>[] enumValues, String[] names) {
1006 HashMap<String,String> expl = null;
1007 for (Field f : ClassUtil.getDeclaredFields(enumType)) {
1008 if (!f.isEnumConstant()) {
1009 continue;
1010 }
1011 XmlEnumValue enumValue = f.getAnnotation(XmlEnumValue.class);
1012 if (enumValue == null) {
1013 continue;
1014 }
1015 String n = enumValue.value();
1016 if (n.isEmpty()) {
1017 continue;
1018 }
1019 if (expl == null) {
1020 expl = new HashMap<String,String>();
1021 }
1022 expl.put(f.getName(), n);
1023 }
1024 // and then stitch them together if and as necessary
1025 if (expl != null) {
1026 for (int i = 0, end = enumValues.length; i < end; ++i) {
1027 String defName = enumValues[i].name();
1028 String explValue = expl.get(defName);
1029 if (explValue != null) {
1030 names[i] = explValue;
1031 }
1032 }
1033 }
1034 return names;
1035 }
1036
1037 /*
1038 /**********************************************************
1039 /* Deserialization: general annotations
1040 /**********************************************************
1041 */
1042
1043 @Override
1044 public Object findDeserializer(Annotated am)
1045 {
1046 final Class<?> type = _rawDeserializationType(am);
1047
1048 /*
1049 // As per [JACKSON-722], more checks for structured types
1050 XmlAdapter<Object,Object> adapter = findAdapter(am, true, type);
1051 if (adapter != null) {
1052 // Ugh. Must match to see if adapter's bounded type (result to map to) matches property type
1053 if (isContainerType(type)) {
1054 if (adapterTypeMatches(adapter, type)) {
1055 return new XmlAdapterJsonDeserializer(adapter);
1056 }
1057 } else {
1058 return new XmlAdapterJsonDeserializer(adapter);
1059 }
1060 }
1061 */
1062
1063 // [JACKSON-150]: add support for additional core XML types needed by JAXB
1064 if (type != null) {
1065 if (_dataHandlerDeserializer != null && isDataHandler(type)) {
1066 return _dataHandlerDeserializer;
1067 }
1068 }
1069
1070 return null;
1071 }
1072
1073 @Override
1074 public Object findKeyDeserializer(Annotated am) {
1075 // Is there something like this in JAXB?
1076 return null;
1077 }
1078
1079 @Override
1080 public Object findContentDeserializer(Annotated a) {
1081 return null;
1082 }
1083
1084 /**
1085 * JAXB does allow specifying (more) concrete class for
1086 * deserialization by using \@XmlElement annotation.
1087 */
1088 @Override
1089 @Deprecated // since 2.7
1090 public Class<?> findDeserializationType(Annotated a, JavaType baseType)
1091 {
1092 // First: only applicable for non-structured types (yes, JAXB annotations are tricky)
1093 if (!baseType.isContainerType()) {
1094 return _doFindDeserializationType(a, baseType);
1095 }
1096 return null;
1097 }
1098
1099 //public Class<?> findDeserializationKeyType(Annotated am, JavaType baseKeyType)
1100
1101 @Override
1102 @Deprecated // since 2.7
1103 public Class<?> findDeserializationContentType(Annotated a, JavaType baseContentType)
1104 {
1105 /* 15-Feb-2010, tatus: JAXB usage of XmlElement/XmlElements is really
1106 * confusing: sometimes it's for type (non-container types), sometimes for
1107 * contents (container) types. I guess it's frugal to reuse these... but
1108 * I think it's rather short-sighted. Whatever, it is what it is, and here
1109 * we are being given content type explicitly.
1110 */
1111 return _doFindDeserializationType(a, baseContentType);
1112 }
1113
1114 protected Class<?> _doFindDeserializationType(Annotated a, JavaType baseType)
1115 {
1116 /* As per [JACKSON-288], @XmlJavaTypeAdapter will complicate handling of type
1117 * information; basically we better just ignore type we might find here altogether
1118 * in that case
1119 */
1120 if (a.hasAnnotation(XmlJavaTypeAdapter.class)) {
1121 return null;
1122 }
1123
1124 /* false for class, package, super-class, since annotation can
1125 * only be attached to fields and methods
1126 */
1127 XmlElement annotation = findAnnotation(XmlElement.class, a, false, false, false);
1128 if (annotation != null) {
1129 Class<?> type = annotation.type();
1130 if (type != XmlElement.DEFAULT.class) {
1131 return type;
1132 }
1133 }
1134 return null;
1135 }
1136
1137 // @since 2.7
1138 @Override
1139 public JavaType refineDeserializationType(final MapperConfig<?> config,
1140 final Annotated a, final JavaType baseType) throws JsonMappingException
1141 {
1142 Class<?> deserClass = _getTypeFromXmlElement(a);
1143 if (deserClass == null) {
1144 return baseType;
1145 }
1146
1147 final TypeFactory tf = config.getTypeFactory();
1148
1149 if (baseType.getContentType() == null) { // non-container/-structured types, usually scalar:
1150 if (baseType.hasRawClass(deserClass)) { // no change
1151 return baseType;
1152 }
1153 // 27-Nov-2015, tatu: Since JAXB has just one annotation, must ignore it in
1154 // one direction, typically serialization (but not always):
1155 if (!baseType.getRawClass().isAssignableFrom(deserClass)) {
1156 return baseType;
1157 }
1158 try {
1159 return tf.constructSpecializedType(baseType, deserClass);
1160 } catch (IllegalArgumentException iae) {
1161 throw new JsonMappingException(null,
1162 String.format("Failed to narrow type %s with annotation (value %s), from '%s': %s",
1163 baseType, deserClass.getName(), a.getName(), iae.getMessage()),
1164 iae);
1165 }
1166 } else {
1167 // Otherwise, structured type:
1168 JavaType contentType = baseType.getContentType();
1169 if (contentType != null) { // collection[like], map[like], array, reference
1170 // as per earlier, may need to ignore annotation meant for deserialization
1171 if (!contentType.getRawClass().isAssignableFrom(deserClass)) {
1172 return baseType;
1173 }
1174 // And then value types for all containers:
1175 try {
1176 contentType = tf.constructSpecializedType(contentType, deserClass);
1177 return baseType.withContentType(contentType);
1178 } catch (IllegalArgumentException iae) {
1179 throw new JsonMappingException(null,
1180 String.format("Failed to narrow type %s with annotation (value %s), from '%s': %s",
1181 baseType, deserClass.getName(), a.getName(), iae.getMessage()),
1182 iae);
1183 }
1184 }
1185 }
1186 return baseType;
1187 }
1188
1189 /*
1190 /**********************************************************
1191 /* Deserialization: property annotations
1192 /**********************************************************
1193 */
1194
1195 @Override
1196 public PropertyName findNameForDeserialization(Annotated a)
1197 {
1198 // need bit of delegation -- note: copy from super-class
1199 // TODO: should simplify, messy.
1200 if (a instanceof AnnotatedMethod) {
1201 AnnotatedMethod am = (AnnotatedMethod) a;
1202 if (!isVisible((AnnotatedMethod) a)) {
1203 return null;
1204 }
1205 Class<?> rawType = am.getRawParameterType(0);
1206 return findJaxbPropertyName(am, rawType, BeanUtil.okNameForSetter(am, true));
1207 }
1208 if (a instanceof AnnotatedField) {
1209 AnnotatedField af = (AnnotatedField) a;
1210
1211 if (!isVisible(af)) {
1212 return null;
1213 }
1214 // As per [jaxb-annotations#61] need to do explicit suppress (see
1215 // `findNameForSerialization` for details)
1216 if (af.isTransient()) {
1217 return null;
1218 }
1219
1220 PropertyName name = findJaxbPropertyName(af, af.getRawType(), null);
1221
1222 /* This may seem wrong, but since JAXB field auto-detection
1223 * needs to find even non-public fields (if enabled by
1224 * JAXB access type), we need to return name like so:
1225 */
1226 // 31-Oct-2014, tatu: As per [jaxb-annotations#31], need to be careful to indicate "use default"
1227 // and NOT to force use of specific name; latter would establish explicit name
1228 // and what we want is implicit (unless there is real explicitly annotated name)
1229 if (name == null) {
1230 return PropertyName.USE_DEFAULT;
1231 }
1232 return name;
1233 }
1234 return null;
1235 }
1236
1237 @Override
1238 public boolean hasCreatorAnnotation(Annotated am) {
1239 return false;
1240 }
1241
1242 @Override
1243 public Object findDeserializationConverter(Annotated a)
1244 {
1245 // One limitation: for structured types this is done later on
1246 Class<?> deserType = _rawDeserializationType(a);
1247 if (isContainerType(deserType)) {
1248 XmlAdapter<?,?> adapter = findAdapter(a, true, deserType);
1249 if (adapter != null) {
1250 return _converter(adapter, false);
1251 }
1252 } else {
1253 XmlAdapter<?,?> adapter = findAdapter(a, true, deserType);
1254 if (adapter != null) {
1255 return _converter(adapter, false);
1256 }
1257 }
1258 return null;
1259 }
1260
1261 @Override
1262 public Object findDeserializationContentConverter(AnnotatedMember a)
1263 {
1264 // conversely, here we only apply this to container types:
1265 Class<?> deserType = _rawDeserializationType(a);
1266 if (isContainerType(deserType)) {
1267 XmlAdapter<?,?> adapter = _findContentAdapter(a, false);
1268 if (adapter != null) {
1269 return _converter(adapter, false);
1270 }
1271 }
1272 return null;
1273 }
1274 /*
1275 /**********************************************************
1276 /* Helper methods (non-API)
1277 /**********************************************************
1278 */
1279
1280 /**
1281 * Whether the specified field is invisible, per the JAXB visibility rules.
1282 *
1283 * @param f The field.
1284 * @return Whether the field is invisible.
1285 */
1286 private boolean isVisible(AnnotatedField f)
1287 {
1288 // TODO: use AnnotatedField's annotations directly
1289 for (Annotation annotation : f.getAnnotated().getDeclaredAnnotations()) {
1290 if (isJAXBAnnotation(annotation)) {
1291 return true;
1292 }
1293 }
1294 XmlAccessType accessType = XmlAccessType.PUBLIC_MEMBER;
1295 XmlAccessorType at = findAnnotation(XmlAccessorType.class, f, true, true, true);
1296 if (at != null) {
1297 accessType = at.value();
1298 }
1299 if (accessType == XmlAccessType.FIELD) {
1300 return true;
1301 }
1302 if (accessType == XmlAccessType.PUBLIC_MEMBER) {
1303 return Modifier.isPublic(f.getAnnotated().getModifiers());
1304 }
1305 return false;
1306 }
1307
1308 private boolean isVisible(AnnotatedMethod m)
1309 {
1310 // TODO: use AnnotatedField's annotations directly
1311 for (Annotation annotation : m.getAnnotated().getDeclaredAnnotations()) {
1312 if (isJAXBAnnotation(annotation)) {
1313 return true;
1314 }
1315 }
1316 XmlAccessType accessType = XmlAccessType.PUBLIC_MEMBER;
1317 XmlAccessorType at = findAnnotation(XmlAccessorType.class, m, true, true, true);
1318 if (at != null) {
1319 accessType = at.value();
1320 }
1321 if (accessType == XmlAccessType.PROPERTY || accessType == XmlAccessType.PUBLIC_MEMBER) {
1322 return Modifier.isPublic(m.getModifiers());
1323 }
1324 return false;
1325 }
1326
1327 /**
1328 * Finds an annotation associated with given annotatable thing; or if
1329 * not found, a default annotation it may have (from super class, package
1330 * and so on)
1331 *
1332 * @param annotationClass the annotation class.
1333 * @param annotated The annotated element.
1334 * @param includePackage Whether the annotation can be found on the package of the annotated element.
1335 * @param includeClass Whether the annotation can be found on the class of the annotated element.
1336 * @param includeSuperclasses Whether the annotation can be found on any superclasses of the class of the annotated element.
1337 * @return The annotation, or null if not found.
1338 */
1339 private <A extends Annotation> A findAnnotation(Class<A> annotationClass, Annotated annotated,
1340 boolean includePackage, boolean includeClass, boolean includeSuperclasses)
1341 {
1342 A annotation = annotated.getAnnotation(annotationClass);
1343 if (annotation != null) {
1344 return annotation;
1345 }
1346 Class<?> memberClass = null;
1347 /* 13-Feb-2011, tatu: [JACKSON-495] - need to handle AnnotatedParameter
1348 * bit differently, since there is no JDK counterpart. We can still
1349 * access annotations directly, just using different calls.
1350 */
1351 if (annotated instanceof AnnotatedParameter) {
1352 memberClass = ((AnnotatedParameter) annotated).getDeclaringClass();
1353 } else {
1354 AnnotatedElement annType = annotated.getAnnotated();
1355 if (annType instanceof Member) {
1356 memberClass = ((Member) annType).getDeclaringClass();
1357 if (includeClass) {
1358 annotation = (A) memberClass.getAnnotation(annotationClass);
1359 if (annotation != null) {
1360 return annotation;
1361 }
1362 }
1363 } else if (annType instanceof Class<?>) {
1364 memberClass = (Class<?>) annType;
1365 } else {
1366 throw new IllegalStateException("Unsupported annotated member: " + annotated.getClass().getName());
1367 }
1368 }
1369 if (memberClass != null) {
1370 if (includeSuperclasses) {
1371 Class<?> superclass = memberClass.getSuperclass();
1372 while (superclass != null && superclass != Object.class) {
1373 annotation = (A) superclass.getAnnotation(annotationClass);
1374 if (annotation != null) {
1375 return annotation;
1376 }
1377 superclass = superclass.getSuperclass();
1378 }
1379 }
1380 if (includePackage) {
1381 Package pkg = memberClass.getPackage();
1382 if (pkg != null) {
1383 return memberClass.getPackage().getAnnotation(annotationClass);
1384 }
1385 }
1386 }
1387 return null;
1388 }
1389
1390 /*
1391 /**********************************************************
1392 /* Helper methods for bean property introspection
1393 /**********************************************************
1394 */
1395
1396 /**
1397 * An annotation is handled if it's in the same package as @XmlElement, including subpackages.
1398 *
1399 * @param ann The annotation.
1400 * @return Whether the annotation is in the JAXB package.
1401 */
1402 protected boolean isJAXBAnnotation(Annotation ann)
1403 {
1404 /* note: class we want is the annotation class, not instance
1405 * (since annotation instances, like enums, may be of different
1406 * physical type!)
1407 */
1408 Class<?> cls = ann.annotationType();
1409 Package pkg = cls.getPackage();
1410 String pkgName = (pkg != null) ? pkg.getName() : cls.getName();
1411 if (pkgName.startsWith(_jaxbPackageName)) {
1412 return true;
1413 }
1414 return false;
1415 }
1416
1417 private static PropertyName findJaxbPropertyName(Annotated ae, Class<?> aeType, String defaultName)
1418 {
1419 XmlAttribute attribute = ae.getAnnotation(XmlAttribute.class);
1420 if (attribute != null) {
1421 return _combineNames(attribute.name(), attribute.namespace(), defaultName);
1422 }
1423 XmlElement element = ae.getAnnotation(XmlElement.class);
1424 if (element != null) {
1425 return _combineNames(element.name(), element.namespace(), defaultName);
1426 }
1427 XmlElementRef elementRef = ae.getAnnotation(XmlElementRef.class);
1428 boolean hasAName = (elementRef != null);
1429 if (hasAName) {
1430 if (!MARKER_FOR_DEFAULT.equals(elementRef.name())) {
1431 return _combineNames(elementRef.name(), elementRef.namespace(), defaultName);
1432 }
1433 if (aeType != null) {
1434 XmlRootElement rootElement = (XmlRootElement) aeType.getAnnotation(XmlRootElement.class);
1435 if (rootElement != null) {
1436 String name = rootElement.name();
1437 if (!MARKER_FOR_DEFAULT.equals(name)) {
1438 return _combineNames(name, rootElement.namespace(), defaultName);
1439 }
1440 // Is there a namespace there to use? Probably not?
1441 return new PropertyName(Introspector.decapitalize(aeType.getSimpleName()));
1442 }
1443 }
1444 }
1445 if (!hasAName) {
1446 hasAName = ae.hasAnnotation(XmlElementWrapper.class);
1447 }
1448 // 09-Aug-2014, tatu: Note: prior to 2.4.2, we used to give explicit name "value"
1449 // if there was "@XmlValue" annotation; since then, only implicit name.
1450
1451 // One more thing:
1452 return hasAName ? PropertyName.USE_DEFAULT : null;
1453 }
1454
1455 private static PropertyName _combineNames(String localName, String namespace,
1456 String defaultName)
1457 {
1458 if (MARKER_FOR_DEFAULT.equals(localName)) {
1459 if (MARKER_FOR_DEFAULT.equals(namespace)) {
1460 return new PropertyName(defaultName);
1461 }
1462 return new PropertyName(defaultName, namespace);
1463 }
1464 if (MARKER_FOR_DEFAULT.equals(namespace)) {
1465 return new PropertyName(localName);
1466 }
1467 return new PropertyName(localName, namespace);
1468 }
1469
1470 private XmlRootElement findRootElementAnnotation(AnnotatedClass ac)
1471 {
1472 // Yes, check package, no class (already included), yes superclasses
1473 return findAnnotation(XmlRootElement.class, ac, true, false, true);
1474 }
1475
1476 /**
1477 * Finds the XmlAdapter for the specified annotation.
1478 *
1479 * @param am The annotated element.
1480 * @param forSerialization If true, adapter for serialization; if false, for deserialization
1481 * @param type
1482 *
1483 * @return The adapter, or null if none.
1484 */
1485 private XmlAdapter<Object,Object> findAdapter(Annotated am, boolean forSerialization,
1486 Class<?> type)
1487 {
1488 // First of all, are we looking for annotations for class?
1489 if (am instanceof AnnotatedClass) {
1490 return findAdapterForClass((AnnotatedClass) am, forSerialization);
1491 }
1492 // Otherwise for a member. First, let's figure out type of property
1493 XmlJavaTypeAdapter adapterInfo = findAnnotation(XmlJavaTypeAdapter.class, am, true, false, false);
1494 if (adapterInfo != null) {
1495 XmlAdapter<Object,Object> adapter = checkAdapter(adapterInfo, type, forSerialization);
1496 if (adapter != null) {
1497 return adapter;
1498 }
1499 }
1500 XmlJavaTypeAdapters adapters = findAnnotation(XmlJavaTypeAdapters.class, am, true, false, false);
1501 if (adapters != null) {
1502 for (XmlJavaTypeAdapter info : adapters.value()) {
1503 XmlAdapter<Object,Object> adapter = checkAdapter(info, type, forSerialization);
1504 if (adapter != null) {
1505 return adapter;
1506 }
1507 }
1508 }
1509 return null;
1510 }
1511
1512 @SuppressWarnings("unchecked")
1513 private final XmlAdapter<Object,Object> checkAdapter(XmlJavaTypeAdapter adapterInfo, Class<?> typeNeeded,
1514 boolean forSerialization)
1515 {
1516 // if annotation has no type, it's applicable; if it has, must match
1517 Class<?> adaptedType = adapterInfo.type();
1518
1519 if (adaptedType == XmlJavaTypeAdapter.DEFAULT.class) {
1520 JavaType type = _typeFactory.constructType(adapterInfo.value());
1521 JavaType[] params = _typeFactory.findTypeParameters(type, XmlAdapter.class);
1522 adaptedType = params[1].getRawClass();
1523 }
1524 if (adaptedType.isAssignableFrom(typeNeeded)) {
1525 @SuppressWarnings("rawtypes")
1526 Class<? extends XmlAdapter> cls = adapterInfo.value();
1527 // true -> yes, force access if need be
1528 return ClassUtil.createInstance(cls, true);
1529 }
1530 return null;
1531 }
1532
1533 @SuppressWarnings("unchecked")
1534 private XmlAdapter<Object,Object> findAdapterForClass(AnnotatedClass ac, boolean forSerialization)
1535 {
1536 /* As per [JACKSON-411], XmlJavaTypeAdapter should not be inherited from super-class.
1537 * It would still be nice to be able to use mix-ins; but unfortunately we seem to lose
1538 * knowledge of class that actually declared the annotation. Thus, we'll only accept
1539 * declaration from specific class itself.
1540 */
1541 XmlJavaTypeAdapter adapterInfo = ac.getAnnotated().getAnnotation(XmlJavaTypeAdapter.class);
1542 if (adapterInfo != null) { // should we try caching this?
1543 @SuppressWarnings("rawtypes")
1544 Class<? extends XmlAdapter> cls = adapterInfo.value();
1545 // true -> yes, force access if need be
1546 return ClassUtil.createInstance(cls, true);
1547 }
1548 return null;
1549 }
1550
1551 protected final TypeFactory getTypeFactory() {
1552 return _typeFactory;
1553 }
1554
1555 /**
1556 * Helper method used to distinguish structured types (arrays, Lists, Maps),
1557 * which with JAXB use different rules for defining content types.
1558 */
1559 private boolean isContainerType(Class<?> raw)
1560 {
1561 return raw.isArray() || Collection.class.isAssignableFrom(raw)
1562 || Map.class.isAssignableFrom(raw);
1563 }
1564
1565 private boolean adapterTypeMatches(XmlAdapter<?,?> adapter, Class<?> targetType)
1566 {
1567 return findAdapterBoundType(adapter).isAssignableFrom(targetType);
1568 }
1569
1570 private Class<?> findAdapterBoundType(XmlAdapter<?,?> adapter)
1571 {
1572 TypeFactory tf = getTypeFactory();
1573 JavaType adapterType = tf.constructType(adapter.getClass());
1574 JavaType[] params = tf.findTypeParameters(adapterType, XmlAdapter.class);
1575 // should not happen, except if our type resolution has a flaw, but:
1576 if (params == null || params.length < 2) {
1577 return Object.class;
1578 }
1579 return params[1].getRawClass();
1580 }
1581
1582 protected XmlAdapter<?,?> _findContentAdapter(Annotated ann,
1583 boolean forSerialization)
1584 {
1585 Class<?> rawType = forSerialization ?
1586 _rawSerializationType(ann) : _rawDeserializationType(ann);
1587
1588 // and let's assume this only applies as member annotation:
1589 if (isContainerType(rawType) && (ann instanceof AnnotatedMember)) {
1590 AnnotatedMember member = (AnnotatedMember) ann;
1591 JavaType fullType = forSerialization ?
1592 _fullSerializationType(member) : _fullDeserializationType(member);
1593 Class<?> contentType = fullType.getContentType().getRawClass();
1594 XmlAdapter<Object,Object> adapter = findAdapter(member, forSerialization, contentType);
1595 if (adapter != null && adapterTypeMatches(adapter, contentType)) {
1596 return adapter;
1597 }
1598 }
1599 return null;
1600 }
1601
1602 protected String _propertyNameToString(PropertyName n)
1603 {
1604 return (n == null) ? null : n.getSimpleName();
1605 }
1606
1607 protected Class<?> _rawDeserializationType(Annotated a)
1608 {
1609 if (a instanceof AnnotatedMethod) {
1610 AnnotatedMethod am = (AnnotatedMethod) a;
1611 // 27-Nov-2012, tatu: Bit nasty, as we are assuming
1612 // things about method signatures here... but has to do
1613 if (am.getParameterCount() == 1) {
1614 return am.getRawParameterType(0);
1615 }
1616 }
1617 return a.getRawType();
1618 }
1619
1620 protected JavaType _fullDeserializationType(AnnotatedMember am)
1621 {
1622 if (am instanceof AnnotatedMethod) {
1623 AnnotatedMethod method = (AnnotatedMethod) am;
1624 // 27-Nov-2012, tatu: Bit nasty, as we are assuming
1625 // things about method signatures here... but has to do
1626 if (method.getParameterCount() == 1) {
1627 return ((AnnotatedMethod) am).getParameterType(0);
1628 }
1629 }
1630 return am.getType();
1631 }
1632
1633 protected Class<?> _rawSerializationType(Annotated a)
1634 {
1635 // 27-Nov-2012, tatu: No work-arounds needed yet...
1636 return a.getRawType();
1637 }
1638
1639 protected JavaType _fullSerializationType(AnnotatedMember am) {
1640 return am.getType();
1641 }
1642
1643 protected Converter<Object,Object> _converter(XmlAdapter<?,?> adapter, boolean forSerialization)
1644 {
1645 TypeFactory tf = getTypeFactory();
1646 JavaType adapterType = tf.constructType(adapter.getClass());
1647 JavaType[] pt = tf.findTypeParameters(adapterType, XmlAdapter.class);
1648 // Order of type parameters for Converter is reverse between serializer, deserializer,
1649 // whereas JAXB just uses single ordering
1650 if (forSerialization) {
1651 return new AdapterConverter(adapter, pt[1], pt[0], forSerialization);
1652 }
1653 return new AdapterConverter(adapter, pt[0], pt[1], forSerialization);
1654 }
1655
1656 protected Class<?> _getTypeFromXmlElement(Annotated a) {
1657 XmlElement annotation = findAnnotation(XmlElement.class, a, false, false, false);
1658 if (annotation != null) {
1659 // Further, JAXB has peculiar notion of declaring intermediate (and, for the
1660 // most part, useless) type... So basically we betterjust ignore type if there
1661 // is adapter annotation (we could check to see if intermediate type is compatible,
1662 // but let's not yet bother)
1663 if (a.getAnnotation(XmlJavaTypeAdapter.class) != null) {
1664 return null;
1665 }
1666 Class<?> type = annotation.type();
1667 if (type != XmlElement.DEFAULT.class) {
1668 return type;
1669 }
1670 }
1671 return null;
1672 }
1673 }