001: /*
002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003: *
004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005: *
006: * The contents of this file are subject to the terms of either the GNU
007: * General Public License Version 2 only ("GPL") or the Common Development
008: * and Distribution License("CDDL") (collectively, the "License"). You
009: * may not use this file except in compliance with the License. You can obtain
010: * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
011: * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
012: * language governing permissions and limitations under the License.
013: *
014: * When distributing the software, include this License Header Notice in each
015: * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
016: * Sun designates this particular file as subject to the "Classpath" exception
017: * as provided by Sun in the GPL Version 2 section of the License file that
018: * accompanied this code. If applicable, add the following below the License
019: * Header, with the fields enclosed by brackets [] replaced by your own
020: * identifying information: "Portions Copyrighted [year]
021: * [name of copyright owner]"
022: *
023: * Contributor(s):
024: *
025: * If you wish your version of this file to be governed by only the CDDL or
026: * only the GPL Version 2, indicate your decision by adding "[Contributor]
027: * elects to include this software in this distribution under the [CDDL or GPL
028: * Version 2] license." If you don't indicate a single choice of license, a
029: * recipient has the option to distribute your version of this file under
030: * either the CDDL, the GPL Version 2 or to extend the choice of license to
031: * its licensees as provided above. However, if you add GPL Version 2 code
032: * and therefore, elected the GPL Version 2 license, then the option applies
033: * only if the new code is made subject to such option by the copyright
034: * holder.
035: */
036: package com.sun.xml.bind.v2.runtime;
037:
038: import java.io.IOException;
039: import java.lang.reflect.InvocationTargetException;
040: import java.lang.reflect.Method;
041: import java.util.Arrays;
042: import java.util.Collection;
043: import java.util.Collections;
044: import java.util.logging.Level;
045: import java.util.logging.Logger;
046:
047: import javax.xml.bind.JAXBContext;
048: import javax.xml.bind.Marshaller;
049: import javax.xml.bind.Unmarshaller;
050: import javax.xml.datatype.XMLGregorianCalendar;
051: import javax.xml.namespace.QName;
052: import javax.xml.stream.XMLStreamException;
053:
054: import com.sun.istack.NotNull;
055: import com.sun.xml.bind.Util;
056: import com.sun.xml.bind.v2.model.runtime.RuntimeTypeInfo;
057: import com.sun.xml.bind.v2.runtime.unmarshaller.Loader;
058: import com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl;
059: import com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext;
060:
061: import org.xml.sax.SAXException;
062:
063: /**
064: * Encapsulates various JAXB operations on objects bound by JAXB.
065: * Immutable and thread-safe.
066: *
067: * <p>
068: * Each JAXB-bound class has a corresponding {@link JaxBeanInfo} object,
069: * which performs all the JAXB related operations on behalf of
070: * the JAXB-bound object.
071: *
072: * <p>
073: * Given a class, the corresponding {@link JaxBeanInfo} can be located
074: * via {@link JAXBContextImpl#getBeanInfo(Class,boolean)}.
075: *
076: * <p>
077: * Typically, {@link JaxBeanInfo} implementations should be generated
078: * by XJC/JXC. Those impl classes will register themselves to their
079: * master <tt>ObjectFactory</tt> class.
080: *
081: * <p>
082: * The type parameter BeanT is the Java class of the bean that this represents.
083: *
084: * @author
085: * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
086: */
087: public abstract class JaxBeanInfo<BeanT> {
088:
089: /**
090: * For {@link JaxBeanInfo} that has multiple type names.
091: */
092: protected JaxBeanInfo(JAXBContextImpl grammar, RuntimeTypeInfo rti,
093: Class<BeanT> jaxbType, QName[] typeNames,
094: boolean isElement, boolean isImmutable,
095: boolean hasLifecycleEvents) {
096: this (grammar, rti, jaxbType, (Object) typeNames, isElement,
097: isImmutable, hasLifecycleEvents);
098: }
099:
100: /**
101: * For {@link JaxBeanInfo} that has one type name.
102: */
103: protected JaxBeanInfo(JAXBContextImpl grammar, RuntimeTypeInfo rti,
104: Class<BeanT> jaxbType, QName typeName, boolean isElement,
105: boolean isImmutable, boolean hasLifecycleEvents) {
106: this (grammar, rti, jaxbType, (Object) typeName, isElement,
107: isImmutable, hasLifecycleEvents);
108: }
109:
110: /**
111: * For {@link JaxBeanInfo} that has no type names.
112: */
113: protected JaxBeanInfo(JAXBContextImpl grammar, RuntimeTypeInfo rti,
114: Class<BeanT> jaxbType, boolean isElement,
115: boolean isImmutable, boolean hasLifecycleEvents) {
116: this (grammar, rti, jaxbType, (Object) null, isElement,
117: isImmutable, hasLifecycleEvents);
118: }
119:
120: private JaxBeanInfo(JAXBContextImpl grammar, RuntimeTypeInfo rti,
121: Class<BeanT> jaxbType, Object typeName, boolean isElement,
122: boolean isImmutable, boolean hasLifecycleEvents) {
123: grammar.beanInfos.put(rti, this );
124:
125: this .jaxbType = jaxbType;
126: this .typeName = typeName;
127: this .flag = (short) ((isElement ? FLAG_IS_ELEMENT : 0)
128: | (isImmutable ? FLAG_IS_IMMUTABLE : 0) | (hasLifecycleEvents ? FLAG_HAS_LIFECYCLE_EVENTS
129: : 0));
130: }
131:
132: /**
133: * Various boolean flags combined into one field to improve memory footprint.
134: */
135: protected short flag;
136:
137: private static final short FLAG_IS_ELEMENT = 1;
138: private static final short FLAG_IS_IMMUTABLE = 2;
139: private static final short FLAG_HAS_ELEMENT_ONLY_CONTENTMODEL = 4;
140: private static final short FLAG_HAS_BEFORE_UNMARSHAL_METHOD = 8;
141: private static final short FLAG_HAS_AFTER_UNMARSHAL_METHOD = 16;
142: private static final short FLAG_HAS_BEFORE_MARSHAL_METHOD = 32;
143: private static final short FLAG_HAS_AFTER_MARSHAL_METHOD = 64;
144: private static final short FLAG_HAS_LIFECYCLE_EVENTS = 128;
145:
146: /** cache of lifecycle methods */
147: private LifecycleMethods lcm = null;
148:
149: /**
150: * True if {@link #jaxbType} has the lifecycle method.
151: */
152: public final boolean hasBeforeUnmarshalMethod() {
153: return (flag & FLAG_HAS_BEFORE_UNMARSHAL_METHOD) != 0;
154: }
155:
156: /**
157: * True if {@link #jaxbType} has the lifecycle method.
158: */
159: public final boolean hasAfterUnmarshalMethod() {
160: return (flag & FLAG_HAS_AFTER_UNMARSHAL_METHOD) != 0;
161: }
162:
163: /**
164: * True if {@link #jaxbType} has the lifecycle method.
165: */
166: public final boolean hasBeforeMarshalMethod() {
167: return (flag & FLAG_HAS_BEFORE_MARSHAL_METHOD) != 0;
168: }
169:
170: /**
171: * True if {@link #jaxbType} has the lifecycle method.
172: */
173: public final boolean hasAfterMarshalMethod() {
174: return (flag & FLAG_HAS_AFTER_MARSHAL_METHOD) != 0;
175: }
176:
177: /**
178: * Gets the JAXB bound class type that this {@link JaxBeanInfo}
179: * handles.
180: *
181: * <p>
182: * IOW, when a bean info object is requested for T,
183: * sometimes the bean info for one of its base classes might be
184: * returned.
185: */
186: public final Class<BeanT> jaxbType;
187:
188: /**
189: * Returns true if the bean is mapped to/from an XML element.
190: *
191: * <p>
192: * When this method returns true, {@link #getElementNamespaceURI(Object)}
193: * and {@link #getElementLocalName(Object)} returns the element name of
194: * the bean.
195: */
196: public final boolean isElement() {
197: return (flag & FLAG_IS_ELEMENT) != 0;
198: }
199:
200: /**
201: * Returns true if the bean is immutable.
202: *
203: * <p>
204: * If this is true, Binder won't try to ueuse this object, and the unmarshaller
205: * won't create a new instance of it before it starts.
206: */
207: public final boolean isImmutable() {
208: return (flag & FLAG_IS_IMMUTABLE) != 0;
209: }
210:
211: /**
212: * True if this bean has an element-only content model.
213: * <p>
214: * If this flag is true, the unmarshaller can work
215: * faster by ignoring whitespaces more efficiently.
216: */
217: public final boolean hasElementOnlyContentModel() {
218: return (flag & FLAG_HAS_ELEMENT_ONLY_CONTENTMODEL) != 0;
219: }
220:
221: /**
222: * True if this bean has an element-only content model.
223: * <p>
224: * Should be considered immutable, though I can't mark it final
225: * because it cannot be computed in this constructor.
226: */
227: protected final void hasElementOnlyContentModel(boolean value) {
228: if (value)
229: flag |= FLAG_HAS_ELEMENT_ONLY_CONTENTMODEL;
230: else
231: flag &= ~FLAG_HAS_ELEMENT_ONLY_CONTENTMODEL;
232: }
233:
234: /**
235: * This method is used to determine which of the sub-classes should be
236: * interrogated for the existence of lifecycle methods.
237: *
238: * @return true if the un|marshaller should look for lifecycle methods
239: * on this beanInfo, false otherwise.
240: */
241: public boolean lookForLifecycleMethods() {
242: return (flag & FLAG_HAS_LIFECYCLE_EVENTS) != 0;
243: }
244:
245: /**
246: * Returns the namespace URI portion of the element name,
247: * if the bean that this class represents is mapped from/to
248: * an XML element.
249: *
250: * @throws UnsupportedOperationException
251: * if {@link #isElement} is false.
252: */
253: public abstract String getElementNamespaceURI(BeanT o);
254:
255: /**
256: * Returns the local name portion of the element name,
257: * if the bean that this class represents is mapped from/to
258: * an XML element.
259: *
260: * @throws UnsupportedOperationException
261: * if {@link #isElement} is false.
262: */
263: public abstract String getElementLocalName(BeanT o);
264:
265: /**
266: * Type names associated with this {@link JaxBeanInfo}.
267: *
268: * @see #getTypeNames()
269: */
270: private final Object typeName; // either null, QName, or QName[]. save memory since most of them have just one.
271:
272: /**
273: * Returns XML Schema type names if the bean is mapped from
274: * a complex/simple type of XML Schema.
275: *
276: * <p>
277: * This is an ugly necessity to correctly handle
278: * the type substitution semantics of XML Schema.
279: *
280: * <p>
281: * A single Java class maybe mapped to more than one
282: * XML types. All the types listed here are recognized
283: * when we are unmarshalling XML.
284: *
285: * <p>
286: * null if the class is not bound to a named schema type.
287: *
288: * <p>
289: */
290: public Collection<QName> getTypeNames() {
291: if (typeName == null)
292: return Collections.emptyList();
293: if (typeName instanceof QName)
294: return Collections.singletonList((QName) typeName);
295: return Arrays.asList((QName[]) typeName);
296: }
297:
298: /**
299: * Returns the XML type name to be used to marshal the specified instance.
300: *
301: * <P>
302: * Most of the times the type can be determined regardless of the actual
303: * instance, but there's a few exceptions (most notably {@link XMLGregorianCalendar}),
304: * so as a general rule we need an instance to determine it.
305: */
306: public QName getTypeName(@NotNull
307: BeanT instance) {
308: if (typeName == null)
309: return null;
310: if (typeName instanceof QName)
311: return (QName) typeName;
312: return ((QName[]) typeName)[0];
313: }
314:
315: /**
316: * Creates a new instance of the bean.
317: *
318: * <p>
319: * This operation is only supported when {@link #isImmutable} is false.
320: *
321: * @param context
322: * Sometimes the created bean remembers the corresponding source location,
323: */
324: public abstract BeanT createInstance(UnmarshallingContext context)
325: throws IllegalAccessException, InvocationTargetException,
326: InstantiationException, SAXException;
327:
328: /**
329: * Resets the object to the initial state, as if the object
330: * is created fresh.
331: *
332: * <p>
333: * This is used to reuse an existing object for unmarshalling.
334: *
335: * @param context
336: * used for reporting any errors.
337: *
338: * @return
339: * true if the object was successfuly resetted.
340: * False if the object is not resettable, in which case the object will be
341: * discarded and new one will be created.
342: * <p>
343: * If the object is resettable but failed by an error, it should be reported to the context,
344: * then return false. If the object is not resettable to begin with, do not report an error.
345: *
346: * @throws SAXException
347: * as a result of reporting an error, the context may throw a {@link SAXException}.
348: */
349: public abstract boolean reset(BeanT o, UnmarshallingContext context)
350: throws SAXException;
351:
352: /**
353: * Gets the ID value of the given bean, if it has an ID value.
354: * Otherwise return null.
355: */
356: public abstract String getId(BeanT o, XMLSerializer target)
357: throws SAXException;
358:
359: /**
360: * Serializes child elements and texts into the specified target.
361: */
362: public abstract void serializeBody(BeanT o, XMLSerializer target)
363: throws SAXException, IOException, XMLStreamException;
364:
365: /**
366: * Serializes attributes into the specified target.
367: */
368: public abstract void serializeAttributes(BeanT o,
369: XMLSerializer target) throws SAXException, IOException,
370: XMLStreamException;
371:
372: /**
373: * Serializes the bean as the root element.
374: *
375: * <p>
376: * In the java-to-schema binding, an object might marshal in two different
377: * ways depending on whether it is used as the root of the graph or not.
378: * In the former case, an object could marshal as an element, whereas
379: * in the latter case, it marshals as a type.
380: *
381: * <p>
382: * This method is used to marshal the root of the object graph to allow
383: * this semantics to be implemented.
384: *
385: * <p>
386: * It is doubtful to me if it's a good idea for an object to marshal
387: * in two ways depending on the context.
388: *
389: * <p>
390: * For schema-to-java, this is equivalent to {@link #serializeBody(Object, XMLSerializer)}.
391: */
392: public abstract void serializeRoot(BeanT o, XMLSerializer target)
393: throws SAXException, IOException, XMLStreamException;
394:
395: /**
396: * Declares all the namespace URIs this object is using at
397: * its top-level scope into the specified target.
398: */
399: public abstract void serializeURIs(BeanT o, XMLSerializer target)
400: throws SAXException;
401:
402: /**
403: * Gets the {@link Loader} that will unmarshall the given object.
404: *
405: * @param context
406: * The {@link JAXBContextImpl} object that governs this object.
407: * This object is taken as a parameter so that {@link JaxBeanInfo} doesn't have
408: * to store them on its own.
409: *
410: * When this method is invoked from within the unmarshaller, tihs parameter can be
411: * null (because the loader is constructed already.)
412: *
413: * @param typeSubstitutionCapable
414: * If true, the returned {@link Loader} is capable of recognizing @xsi:type (if necessary)
415: * and unmarshals a subtype. This allowes an optimization where this bean info
416: * is guaranteed not to have a type substitution.
417: * If false, the returned {@link Loader} doesn't look for @xsi:type.
418: * @return
419: * must return non-null valid object
420: */
421: public abstract Loader getLoader(JAXBContextImpl context,
422: boolean typeSubstitutionCapable);
423:
424: /**
425: * If the bean's representation in XML is just a text,
426: * this method return a {@link Transducer} that lets you convert
427: * values between the text and the bean.
428: */
429: public abstract Transducer<BeanT> getTransducer();
430:
431: /**
432: * Called after all the {@link JaxBeanInfo}s are created.
433: * @param grammar
434: */
435: protected void link(JAXBContextImpl grammar) {
436: }
437:
438: /**
439: * Called at the end of the {@link JAXBContext} initialization phase
440: * to clean up any unnecessary references.
441: */
442: public void wrapUp() {
443: }
444:
445: private static final Class[] unmarshalEventParams = {
446: Unmarshaller.class, Object.class };
447: private static Class[] marshalEventParams = { Marshaller.class };
448:
449: /**
450: * use reflection to determine which of the 4 object lifecycle methods exist on
451: * the JAXB bound type.
452: */
453: protected final void setLifecycleFlags() {
454: try {
455: for (Method m : jaxbType.getDeclaredMethods()) {
456: String name = m.getName();
457: if (name.equals("beforeUnmarshal")) {
458: if (match(m, unmarshalEventParams)) {
459: cacheLifecycleMethod(m,
460: FLAG_HAS_BEFORE_UNMARSHAL_METHOD);
461: }
462: } else if (name.equals("afterUnmarshal")) {
463: if (match(m, unmarshalEventParams)) {
464: cacheLifecycleMethod(m,
465: FLAG_HAS_AFTER_UNMARSHAL_METHOD);
466: }
467: } else if (name.equals("beforeMarshal")) {
468: if (match(m, marshalEventParams)) {
469: cacheLifecycleMethod(m,
470: FLAG_HAS_BEFORE_MARSHAL_METHOD);
471: }
472: } else if (name.equals("afterMarshal")) {
473: if (match(m, marshalEventParams)) {
474: cacheLifecycleMethod(m,
475: FLAG_HAS_AFTER_MARSHAL_METHOD);
476: }
477: }
478: }
479: } catch (SecurityException e) {
480: // this happens when we don't have enough permission.
481: logger.log(Level.WARNING,
482: Messages.UNABLE_TO_DISCOVER_EVENTHANDLER.format(
483: jaxbType.getName(), e));
484: }
485: }
486:
487: private boolean match(Method m, Class[] params) {
488: return Arrays.equals(m.getParameterTypes(), params);
489: }
490:
491: /**
492: * Cache a reference to the specified lifecycle method for the jaxbType
493: * associated with this beanInfo.
494: *
495: * @param m Method reference
496: * @param lifecycleFlag byte representing which of the 4 lifecycle methods
497: * is being cached
498: */
499: private void cacheLifecycleMethod(Method m, short lifecycleFlag) {
500: //LifecycleMethods lcm = getLifecycleMethods();
501: if (lcm == null) {
502: lcm = new LifecycleMethods();
503: //lcmCache.put(jaxbType, lcm);
504: }
505:
506: m.setAccessible(true);
507:
508: flag |= lifecycleFlag;
509:
510: switch (lifecycleFlag) {
511: case FLAG_HAS_BEFORE_UNMARSHAL_METHOD:
512: lcm.beforeUnmarshal = m;
513: break;
514: case FLAG_HAS_AFTER_UNMARSHAL_METHOD:
515: lcm.afterUnmarshal = m;
516: break;
517: case FLAG_HAS_BEFORE_MARSHAL_METHOD:
518: lcm.beforeMarshal = m;
519: break;
520: case FLAG_HAS_AFTER_MARSHAL_METHOD:
521: lcm.afterMarshal = m;
522: break;
523: }
524: }
525:
526: /**
527: * Return the LifecycleMethods cache for this ClassBeanInfo's corresponding
528: * jaxbType if it exists, else return null.
529: *
530: */
531: public final LifecycleMethods getLifecycleMethods() {
532: return lcm;
533: }
534:
535: /**
536: * Invokes the beforeUnmarshal method if applicable.
537: */
538: public final void invokeBeforeUnmarshalMethod(UnmarshallerImpl unm,
539: Object child, Object parent) throws SAXException {
540: Method m = getLifecycleMethods().beforeUnmarshal;
541: invokeUnmarshallCallback(m, child, unm, parent);
542: }
543:
544: /**
545: * Invokes the afterUnmarshal method if applicable.
546: */
547: public final void invokeAfterUnmarshalMethod(UnmarshallerImpl unm,
548: Object child, Object parent) throws SAXException {
549: Method m = getLifecycleMethods().afterUnmarshal;
550: invokeUnmarshallCallback(m, child, unm, parent);
551: }
552:
553: private void invokeUnmarshallCallback(Method m, Object child,
554: UnmarshallerImpl unm, Object parent) throws SAXException {
555: try {
556: m.invoke(child, unm, parent);
557: } catch (IllegalAccessException e) {
558: UnmarshallingContext.getInstance().handleError(e);
559: } catch (InvocationTargetException e) {
560: UnmarshallingContext.getInstance().handleError(e);
561: }
562: }
563:
564: private static final Logger logger = Util.getClassLogger();
565: }
|