Fri, 24 Oct 2014 15:02:28 +0200
8054367: More references for endpoints
Summary: fix also reviewed by Iaroslav.Savytskyi@oracle.com, Alexander.Fomin@oracle.com
Reviewed-by: mullan, skoivu
1 /*
2 * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.xml.internal.bind.v2.runtime;
28 import java.io.IOException;
29 import java.lang.reflect.InvocationTargetException;
30 import java.lang.reflect.Method;
31 import java.util.Arrays;
32 import java.util.Collection;
33 import java.util.Collections;
34 import java.util.logging.Level;
35 import java.util.logging.Logger;
37 import javax.xml.bind.JAXBContext;
38 import javax.xml.bind.Marshaller;
39 import javax.xml.bind.Unmarshaller;
40 import javax.xml.datatype.XMLGregorianCalendar;
41 import javax.xml.namespace.QName;
42 import javax.xml.stream.XMLStreamException;
44 import com.sun.istack.internal.NotNull;
45 import com.sun.xml.internal.bind.Util;
46 import com.sun.xml.internal.bind.v2.model.runtime.RuntimeTypeInfo;
47 import com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader;
48 import com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl;
49 import com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext;
51 import org.xml.sax.SAXException;
53 /**
54 * Encapsulates various JAXB operations on objects bound by JAXB.
55 * Immutable and thread-safe.
56 *
57 * <p>
58 * Each JAXB-bound class has a corresponding {@link JaxBeanInfo} object,
59 * which performs all the JAXB related operations on behalf of
60 * the JAXB-bound object.
61 *
62 * <p>
63 * Given a class, the corresponding {@link JaxBeanInfo} can be located
64 * via {@link JAXBContextImpl#getBeanInfo(Class,boolean)}.
65 *
66 * <p>
67 * Typically, {@link JaxBeanInfo} implementations should be generated
68 * by XJC/JXC. Those impl classes will register themselves to their
69 * master <tt>ObjectFactory</tt> class.
70 *
71 * <p>
72 * The type parameter BeanT is the Java class of the bean that this represents.
73 *
74 * @author
75 * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
76 */
77 public abstract class JaxBeanInfo<BeanT> {
79 protected boolean isNilIncluded = false;
81 /**
82 * For {@link JaxBeanInfo} that has multiple type names.
83 */
84 protected JaxBeanInfo(JAXBContextImpl grammar, RuntimeTypeInfo rti, Class<BeanT> jaxbType, QName[] typeNames, boolean isElement,boolean isImmutable, boolean hasLifecycleEvents) {
85 this(grammar,rti,jaxbType,(Object)typeNames,isElement,isImmutable,hasLifecycleEvents);
86 }
88 /**
89 * For {@link JaxBeanInfo} that has one type name.
90 */
91 protected JaxBeanInfo(JAXBContextImpl grammar, RuntimeTypeInfo rti, Class<BeanT> jaxbType, QName typeName, boolean isElement,boolean isImmutable, boolean hasLifecycleEvents) {
92 this(grammar,rti,jaxbType,(Object)typeName,isElement,isImmutable,hasLifecycleEvents);
93 }
95 /**
96 * For {@link JaxBeanInfo} that has no type names.
97 */
98 protected JaxBeanInfo(JAXBContextImpl grammar, RuntimeTypeInfo rti, Class<BeanT> jaxbType, boolean isElement,boolean isImmutable, boolean hasLifecycleEvents) {
99 this(grammar,rti,jaxbType,(Object)null,isElement,isImmutable,hasLifecycleEvents);
100 }
102 private JaxBeanInfo(JAXBContextImpl grammar, RuntimeTypeInfo rti, Class<BeanT> jaxbType, Object typeName, boolean isElement,boolean isImmutable, boolean hasLifecycleEvents) {
103 grammar.beanInfos.put(rti,this);
105 this.jaxbType = jaxbType;
106 this.typeName = typeName;
107 this.flag = (short)((isElement?FLAG_IS_ELEMENT:0)
108 |(isImmutable?FLAG_IS_IMMUTABLE:0)
109 |(hasLifecycleEvents?FLAG_HAS_LIFECYCLE_EVENTS:0));
110 }
112 /**
113 * Various boolean flags combined into one field to improve memory footprint.
114 */
115 protected short flag;
117 private static final short FLAG_IS_ELEMENT = 1;
118 private static final short FLAG_IS_IMMUTABLE = 2;
119 private static final short FLAG_HAS_ELEMENT_ONLY_CONTENTMODEL = 4;
120 private static final short FLAG_HAS_BEFORE_UNMARSHAL_METHOD = 8;
121 private static final short FLAG_HAS_AFTER_UNMARSHAL_METHOD = 16;
122 private static final short FLAG_HAS_BEFORE_MARSHAL_METHOD = 32;
123 private static final short FLAG_HAS_AFTER_MARSHAL_METHOD = 64;
124 private static final short FLAG_HAS_LIFECYCLE_EVENTS = 128;
126 /** cache of lifecycle methods */
127 private LifecycleMethods lcm = null;
129 /**
130 * True if {@link #jaxbType} has the lifecycle method.
131 */
132 public final boolean hasBeforeUnmarshalMethod() {
133 return (flag&FLAG_HAS_BEFORE_UNMARSHAL_METHOD) != 0;
134 }
136 /**
137 * True if {@link #jaxbType} has the lifecycle method.
138 */
139 public final boolean hasAfterUnmarshalMethod() {
140 return (flag&FLAG_HAS_AFTER_UNMARSHAL_METHOD) != 0;
141 }
143 /**
144 * True if {@link #jaxbType} has the lifecycle method.
145 */
146 public final boolean hasBeforeMarshalMethod() {
147 return (flag&FLAG_HAS_BEFORE_MARSHAL_METHOD) != 0;
148 }
150 /**
151 * True if {@link #jaxbType} has the lifecycle method.
152 */
153 public final boolean hasAfterMarshalMethod() {
154 return (flag&FLAG_HAS_AFTER_MARSHAL_METHOD) != 0;
155 }
157 /**
158 * Gets the JAXB bound class type that this {@link JaxBeanInfo}
159 * handles.
160 *
161 * <p>
162 * IOW, when a bean info object is requested for T,
163 * sometimes the bean info for one of its base classes might be
164 * returned.
165 */
166 public final Class<BeanT> jaxbType;
168 /**
169 * Returns true if the bean is mapped to/from an XML element.
170 *
171 * <p>
172 * When this method returns true, {@link #getElementNamespaceURI(Object)}
173 * and {@link #getElementLocalName(Object)} returns the element name of
174 * the bean.
175 */
176 public final boolean isElement() {
177 return (flag&FLAG_IS_ELEMENT)!=0;
178 }
180 /**
181 * Returns true if the bean is immutable.
182 *
183 * <p>
184 * If this is true, Binder won't try to ueuse this object, and the unmarshaller
185 * won't create a new instance of it before it starts.
186 */
187 public final boolean isImmutable() {
188 return (flag&FLAG_IS_IMMUTABLE)!=0;
189 }
191 /**
192 * True if this bean has an element-only content model.
193 * <p>
194 * If this flag is true, the unmarshaller can work
195 * faster by ignoring whitespaces more efficiently.
196 */
197 public final boolean hasElementOnlyContentModel() {
198 return (flag&FLAG_HAS_ELEMENT_ONLY_CONTENTMODEL)!=0;
199 }
201 /**
202 * True if this bean has an element-only content model.
203 * <p>
204 * Should be considered immutable, though I can't mark it final
205 * because it cannot be computed in this constructor.
206 */
207 protected final void hasElementOnlyContentModel(boolean value) {
208 if(value)
209 flag |= FLAG_HAS_ELEMENT_ONLY_CONTENTMODEL;
210 else
211 flag &= ~FLAG_HAS_ELEMENT_ONLY_CONTENTMODEL;
212 }
214 public boolean isNilIncluded() {
215 return isNilIncluded;
216 }
218 /**
219 * This method is used to determine which of the sub-classes should be
220 * interrogated for the existence of lifecycle methods.
221 *
222 * @return true if the un|marshaller should look for lifecycle methods
223 * on this beanInfo, false otherwise.
224 */
225 public boolean lookForLifecycleMethods() {
226 return (flag&FLAG_HAS_LIFECYCLE_EVENTS)!=0;
227 }
229 /**
230 * Returns the namespace URI portion of the element name,
231 * if the bean that this class represents is mapped from/to
232 * an XML element.
233 *
234 * @throws UnsupportedOperationException
235 * if {@link #isElement} is false.
236 */
237 public abstract String getElementNamespaceURI(BeanT o);
239 /**
240 * Returns the local name portion of the element name,
241 * if the bean that this class represents is mapped from/to
242 * an XML element.
243 *
244 * @throws UnsupportedOperationException
245 * if {@link #isElement} is false.
246 */
247 public abstract String getElementLocalName(BeanT o);
249 /**
250 * Type names associated with this {@link JaxBeanInfo}.
251 *
252 * @see #getTypeNames()
253 */
254 private final Object typeName; // either null, QName, or QName[]. save memory since most of them have just one.
256 /**
257 * Returns XML Schema type names if the bean is mapped from
258 * a complex/simple type of XML Schema.
259 *
260 * <p>
261 * This is an ugly necessity to correctly handle
262 * the type substitution semantics of XML Schema.
263 *
264 * <p>
265 * A single Java class maybe mapped to more than one
266 * XML types. All the types listed here are recognized
267 * when we are unmarshalling XML.
268 *
269 * <p>
270 * null if the class is not bound to a named schema type.
271 *
272 * <p>
273 */
274 public Collection<QName> getTypeNames() {
275 if(typeName==null) return Collections.emptyList();
276 if(typeName instanceof QName) return Collections.singletonList((QName)typeName);
277 return Arrays.asList((QName[])typeName);
278 }
280 /**
281 * Returns the XML type name to be used to marshal the specified instance.
282 *
283 * <P>
284 * Most of the times the type can be determined regardless of the actual
285 * instance, but there's a few exceptions (most notably {@link XMLGregorianCalendar}),
286 * so as a general rule we need an instance to determine it.
287 */
288 public QName getTypeName(@NotNull BeanT instance) {
289 if(typeName==null) return null;
290 if(typeName instanceof QName) return (QName)typeName;
291 return ((QName[])typeName)[0];
292 }
294 /**
295 * Creates a new instance of the bean.
296 *
297 * <p>
298 * This operation is only supported when {@link #isImmutable} is false.
299 *
300 * @param context
301 * Sometimes the created bean remembers the corresponding source location,
302 */
303 public abstract BeanT createInstance(UnmarshallingContext context) throws IllegalAccessException, InvocationTargetException, InstantiationException, SAXException;
305 /**
306 * Resets the object to the initial state, as if the object
307 * is created fresh.
308 *
309 * <p>
310 * This is used to reuse an existing object for unmarshalling.
311 *
312 * @param context
313 * used for reporting any errors.
314 *
315 * @return
316 * true if the object was successfuly resetted.
317 * False if the object is not resettable, in which case the object will be
318 * discarded and new one will be created.
319 * <p>
320 * If the object is resettable but failed by an error, it should be reported to the context,
321 * then return false. If the object is not resettable to begin with, do not report an error.
322 *
323 * @throws SAXException
324 * as a result of reporting an error, the context may throw a {@link SAXException}.
325 */
326 public abstract boolean reset( BeanT o, UnmarshallingContext context ) throws SAXException;
328 /**
329 * Gets the ID value of the given bean, if it has an ID value.
330 * Otherwise return null.
331 */
332 public abstract String getId(BeanT o, XMLSerializer target) throws SAXException;
334 /**
335 * Serializes child elements and texts into the specified target.
336 */
337 public abstract void serializeBody( BeanT o, XMLSerializer target ) throws SAXException, IOException, XMLStreamException;
339 /**
340 * Serializes attributes into the specified target.
341 */
342 public abstract void serializeAttributes( BeanT o, XMLSerializer target ) throws SAXException, IOException, XMLStreamException;
344 /**
345 * Serializes the bean as the root element.
346 *
347 * <p>
348 * In the java-to-schema binding, an object might marshal in two different
349 * ways depending on whether it is used as the root of the graph or not.
350 * In the former case, an object could marshal as an element, whereas
351 * in the latter case, it marshals as a type.
352 *
353 * <p>
354 * This method is used to marshal the root of the object graph to allow
355 * this semantics to be implemented.
356 *
357 * <p>
358 * It is doubtful to me if it's a good idea for an object to marshal
359 * in two ways depending on the context.
360 *
361 * <p>
362 * For schema-to-java, this is equivalent to {@link #serializeBody(Object, XMLSerializer)}.
363 */
364 public abstract void serializeRoot( BeanT o, XMLSerializer target ) throws SAXException, IOException, XMLStreamException;
366 /**
367 * Declares all the namespace URIs this object is using at
368 * its top-level scope into the specified target.
369 */
370 public abstract void serializeURIs( BeanT o, XMLSerializer target ) throws SAXException;
372 /**
373 * Gets the {@link Loader} that will unmarshall the given object.
374 *
375 * @param context
376 * The {@link JAXBContextImpl} object that governs this object.
377 * This object is taken as a parameter so that {@link JaxBeanInfo} doesn't have
378 * to store them on its own.
379 *
380 * When this method is invoked from within the unmarshaller, tihs parameter can be
381 * null (because the loader is constructed already.)
382 *
383 * @param typeSubstitutionCapable
384 * If true, the returned {@link Loader} is capable of recognizing @xsi:type (if necessary)
385 * and unmarshals a subtype. This allowes an optimization where this bean info
386 * is guaranteed not to have a type substitution.
387 * If false, the returned {@link Loader} doesn't look for @xsi:type.
388 * @return
389 * must return non-null valid object
390 */
391 public abstract Loader getLoader(JAXBContextImpl context, boolean typeSubstitutionCapable);
393 /**
394 * If the bean's representation in XML is just a text,
395 * this method return a {@link Transducer} that lets you convert
396 * values between the text and the bean.
397 */
398 public abstract Transducer<BeanT> getTransducer();
401 /**
402 * Called after all the {@link JaxBeanInfo}s are created.
403 * @param grammar
404 */
405 protected void link(JAXBContextImpl grammar) {
406 }
408 /**
409 * Called at the end of the {@link JAXBContext} initialization phase
410 * to clean up any unnecessary references.
411 */
412 public void wrapUp() {}
415 private static final Class[] unmarshalEventParams = { Unmarshaller.class, Object.class };
416 private static Class[] marshalEventParams = { Marshaller.class };
418 /**
419 * use reflection to determine which of the 4 object lifecycle methods exist on
420 * the JAXB bound type.
421 */
422 protected final void setLifecycleFlags() {
423 try {
424 Class<BeanT> jt = jaxbType;
426 if (lcm == null) {
427 lcm = new LifecycleMethods();
428 }
430 while (jt != null) {
431 for (Method m : jt.getDeclaredMethods()) {
432 String name = m.getName();
434 if (lcm.beforeUnmarshal == null) {
435 if (name.equals("beforeUnmarshal")) {
436 if (match(m, unmarshalEventParams)) {
437 cacheLifecycleMethod(m, FLAG_HAS_BEFORE_UNMARSHAL_METHOD);
438 }
439 }
440 }
442 if (lcm.afterUnmarshal == null) {
443 if (name.equals("afterUnmarshal")) {
444 if (match(m, unmarshalEventParams)) {
445 cacheLifecycleMethod(m, FLAG_HAS_AFTER_UNMARSHAL_METHOD);
446 }
447 }
448 }
450 if (lcm.beforeMarshal == null) {
451 if (name.equals("beforeMarshal")) {
452 if (match(m, marshalEventParams)) {
453 cacheLifecycleMethod(m, FLAG_HAS_BEFORE_MARSHAL_METHOD);
454 }
455 }
456 }
458 if (lcm.afterMarshal == null) {
459 if (name.equals("afterMarshal")) {
460 if (match(m, marshalEventParams)) {
461 cacheLifecycleMethod(m, FLAG_HAS_AFTER_MARSHAL_METHOD);
462 }
463 }
464 }
465 }
466 jt = (Class<BeanT>) jt.getSuperclass();
467 }
468 } catch (SecurityException e) {
469 // this happens when we don't have enough permission.
470 logger.log(Level.WARNING, Messages.UNABLE_TO_DISCOVER_EVENTHANDLER.format(
471 jaxbType.getName(), e));
472 }
473 }
475 private boolean match(Method m, Class[] params) {
476 return Arrays.equals(m.getParameterTypes(),params);
477 }
479 /**
480 * Cache a reference to the specified lifecycle method for the jaxbType
481 * associated with this beanInfo.
482 *
483 * @param m Method reference
484 * @param lifecycleFlag byte representing which of the 4 lifecycle methods
485 * is being cached
486 */
487 private void cacheLifecycleMethod(Method m, short lifecycleFlag) {
488 //LifecycleMethods lcm = getLifecycleMethods();
489 if(lcm==null) {
490 lcm = new LifecycleMethods();
491 //lcmCache.put(jaxbType, lcm);
492 }
494 m.setAccessible(true);
496 flag |= lifecycleFlag;
498 switch (lifecycleFlag) {
499 case FLAG_HAS_BEFORE_UNMARSHAL_METHOD:
500 lcm.beforeUnmarshal = m;
501 break;
502 case FLAG_HAS_AFTER_UNMARSHAL_METHOD:
503 lcm.afterUnmarshal = m;
504 break;
505 case FLAG_HAS_BEFORE_MARSHAL_METHOD:
506 lcm.beforeMarshal = m;
507 break;
508 case FLAG_HAS_AFTER_MARSHAL_METHOD:
509 lcm.afterMarshal = m;
510 break;
511 }
512 }
514 /**
515 * Return the LifecycleMethods cache for this ClassBeanInfo's corresponding
516 * jaxbType if it exists, else return null.
517 *
518 */
519 public final LifecycleMethods getLifecycleMethods() {
520 return lcm;
521 }
523 /**
524 * Invokes the beforeUnmarshal method if applicable.
525 */
526 public final void invokeBeforeUnmarshalMethod(UnmarshallerImpl unm, Object child, Object parent) throws SAXException {
527 Method m = getLifecycleMethods().beforeUnmarshal;
528 invokeUnmarshallCallback(m, child, unm, parent);
529 }
531 /**
532 * Invokes the afterUnmarshal method if applicable.
533 */
534 public final void invokeAfterUnmarshalMethod(UnmarshallerImpl unm, Object child, Object parent) throws SAXException {
535 Method m = getLifecycleMethods().afterUnmarshal;
536 invokeUnmarshallCallback(m, child, unm, parent);
537 }
539 private void invokeUnmarshallCallback(Method m, Object child, UnmarshallerImpl unm, Object parent) throws SAXException {
540 try {
541 m.invoke(child,unm,parent);
542 } catch (IllegalAccessException e) {
543 UnmarshallingContext.getInstance().handleError(e, false);
544 } catch (InvocationTargetException e) {
545 UnmarshallingContext.getInstance().handleError(e, false);
546 }
547 }
549 private static final Logger logger = Util.getClassLogger();
550 }