Top Description Fields Constructors Methods
org.glassfish.jaxb.runtime.v2.runtime

public final Class XMLSerializer

extends Coordinator
Class Inheritance
Imports
com.sun.istack.SAXException2, org.glassfish.jaxb.runtime.CycleRecoverable, org.glassfish.jaxb.runtime.marshaller.NamespacePrefixMapper, org.glassfish.jaxb.runtime.api.AccessorException, org.glassfish.jaxb.runtime.util.ValidationEventLocatorExImpl, org.glassfish.jaxb.runtime.v2.model.runtime.RuntimeBuiltinLeafInfo, org.glassfish.jaxb.runtime.v2.runtime.output.MTOMXmlOutput, .NamespaceContextImpl, .Pcdata, .XmlOutput, org.glassfish.jaxb.runtime.v2.runtime.property.Property, org.glassfish.jaxb.runtime.v2.runtime.unmarshaller.Base64Data, .IntData, org.glassfish.jaxb.runtime.v2.util.CollisionCheckStack, jakarta.activation.MimeType, jakarta.xml.bind.*, jakarta.xml.bind.annotation.DomHandler, .XmlNs, jakarta.xml.bind.attachment.AttachmentMarshaller, jakarta.xml.bind.helpers.NotIdentifiableEventImpl, .ValidationEventImpl, .ValidationEventLocatorImpl, org.xml.sax.SAXException, javax.xml.XMLConstants, javax.xml.namespace.QName, javax.xml.stream.XMLStreamException, javax.xml.transform.Source, .Transformer, .TransformerException, javax.xml.transform.sax.SAXResult, java.io.IOException, java.lang.reflect.Method, java.util.HashSet, .Map, .Set

Receives XML serialization event and writes to XmlOutput.

This object coordinates the overall marshalling efforts across different content-tree objects and different target formats.

The following CFG gives the proper sequence of method invocation.

MARSHALLING  :=  ELEMENT
ELEMENT      :=  "startElement" NSDECL* "endNamespaceDecls"
                       ATTRIBUTE* "endAttributes" BODY "endElement"

NSDECL       :=  "declareNamespace"

ATTRIBUTE    :=  "attribute"
ATTVALUES    :=  "text"*


BODY         :=  ( "text" | ELEMENT )*

A marshalling of one element consists of two stages. The first stage is for marshalling attributes and collecting namespace declarations. The second stage is for marshalling characters/child elements of that element.

Observe that multiple invocation of "text" is allowed.

Also observe that the namespace declarations are allowed only between "startElement" and "endAttributes".

Exceptions in marshaller

IOException, SAXException, and XMLStreamException are thrown from XmlOutput. They are always considered fatal, and therefore caught only by MarshallerImpl.

AccessorException can be thrown when an access to a property/field fails, and this is considered as a recoverable error, so it's caught everywhere.

Author
Kohsuke Kawaguchi

Field Summary

Modifier and TypeField and Description
public AttachmentMarshaller
private Base64Data
base64Data

Cached instance of Base64Data.

private ContentHandlerAdaptor
contentHandlerAdapter

Lazily created.

pack-priv ThreadLocal<Property<BeanT>>
private final CollisionCheckStack<Object>
cycleDetectionStack

Used to detect cycles in the object.

private MimeType
private boolean
public final JAXBContextImpl
private Transformer
identityTransformer

Lazily created identitiy transformer.

private final Set<Object>
idReferencedObjects

Objects referenced through IDREF.

private boolean
inlineBinaryFlag

True to force inlining.

private final IntData
intData

Cached instance of IntData.

public final int[]
private final MarshallerImpl
marshaller

Marshaller object to which this object belongs.

public final NameList
private String
private final NamespaceContextImpl
private NamespaceContextImpl.Element
private final Set<Object>
objectsWithId

Objects with ID.

private XmlOutput
out

The XML printer.

private String
schemaLocation

Optional attributes to go with root element.

private QName
schemaType

Field used to support an jakarta.xml.bind.annotation.XmlSchemaType annotation.

private boolean
seenRoot

Set to false once we see the start tag of the root element.

private boolean
textHasAlreadyPrinted

Set to true if a text is already written, and we need to print ' ' for additional text methods.

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Modifier and TypeMethod and Description
public void
addInscopeBinding(String nsUri, String prefix)

This method can be called after startDocument is called but before the marshalling begins, to set the currently in-scope namespace bindings.

public void
attribute(String uri, String local, String value)

public void
public void
attWildcardAsAttributes(Map<QName, String> attributes, String fieldName)

public void
attWildcardAsURIs(Map<QName, String> attributes, String fieldName)

public void
public void
childAsSoleContent(Object child, String fieldName)

The equivalent of:

childAsURIs(child, fieldName);
endNamespaceDecls();
childAsAttributes(child, fieldName);
endAttributes();
childAsBody(child, fieldName);
public void
childAsXsiType(Object
Object to be marshalled. The JaxBeanInfo for this object must return a type name.
child
,
String
property name of the parent objeect from which 'o' comes. Used as a part of the error message in case anything goes wrong with 'o'.
fieldName
,
JaxBeanInfo<BeanT>
Expected type of the object.
expected
,
boolean nillable)

This method is called when a type child object is found.

public void
clearCurrentProperty()

Takes care of cleaning the currentProperty.

public void
public void
endAttributes()

Switches to the "marshal child texts/elements" mode.

public void
public void
endElement()

Ends marshalling of an element.

public void
public void
errorMissingId(Object obj)

Called when a referenced object doesn't have an ID.

private void
fireAfterMarshalEvents(final JaxBeanInfo<BeanT> beanInfo, Object currentTarget)

Invoke the afterMarshal api on the external listener (if it exists) and on the bean embedded afterMarshal api(if it exists).

private void
fireBeforeMarshalEvents(final JaxBeanInfo<BeanT> beanInfo, Object currentTarget)

Invoke the beforeMarshal api on the external listener (if it exists) and on the bean embedded beforeMarshal api(if it exists).

private void
public Base64Data
getCachedBase64DataInstance()
Deprecated Base64Data is no longer cached, so that XMLStreamWriterEx impl can retain the data, like JAX-WS does.

Gets the cached instance of Base64Data.

public ValidationEventLocator
public Property<BeanT>
getCurrentProperty()

May return null when the property hasn't been set.

public Transformer
private String
getIdFromObject(Object identifiableObject)

Gets the ID value from an identifiable object.

public boolean
public static XMLSerializer
getInstance()

When called from within the realm of the marshaller, this method returns the current in charge.

protected ValidationEventLocator
getLocation()

Implements abstract org.glassfish.jaxb.runtime.v2.runtime.Coordinator.getLocation.

Gets the current location.

public NamespaceContext2
public boolean
public QName
public String
getXMIMEContentType()

Gets the MIME type with which the binary content shall be printed.

public boolean
public boolean
handleError(Exception e, Object source, String fieldName)

public boolean
handleEvent(ValidationEvent event)

Implements jakarta.xml.bind.ValidationEventHandler.handleEvent.

Receive notification of a validation warning or error.

private void
public void
leafElement(Name tagName, String data, String fieldName)

public void
leafElement(Name tagName, Pcdata data, String fieldName)

public void
leafElement(Name tagName, int data, String fieldName)

public String
onID(Object owner, String value)

public String
private Object

Returns:

the object that should be marshalled instead of the given obj, or null if the error is found and we need to avoid marshalling this object to prevent infinite recursion. When this method returns null, the error has already been reported.
pushObject
(Object obj, String fieldName)

Pushes the object to cycleDetectionStack and also detect any cycles.

pack-priv void
public void
public void
reportError(String
the name of the property being processed when an error is found.
fieldName
,
Throwable t)

Report an error found as an exception.

private void
public MimeType
setExpectedMimeType(MimeType expectedMimeType)

This method is used by MimeTypedTransducer to set the expected MIME type for the encapsulated Transducer.

public boolean
setInlineBinaryFlag(boolean value)

public void
public void
public QName
public void
startDocument(XmlOutput out, boolean fragment, String
if non-null, this value is printed on the root element as xsi:schemaLocation
schemaLocation
,
String
Similar to 'schemaLocation' but this one works for xsi:noNamespaceSchemaLocation
noNsSchemaLocation
)

Reset this object to write to the specified output.

public void
startElement(Name tagName, Object outerPeer)

public void
startElement(String nsUri, String localName, String preferredPrefix, Object outerPeer)

private void
public void
startElementForce(String nsUri, String localName, String forcedPrefix, Object outerPeer)

Variation of startElement(String, String, String, Object) that forces a specific prefix.

public void
text(String text, String fieldName)

Marshalls text.

public void
text(Pcdata text, String fieldName)

The text(String, String) method that takes Pcdata.

public <E> void
writeDom(E element, DomHandler<E, ?> domHandler, Object parentBean, String fieldName)

public void
writeXsiNilTrue()

Short for the following call sequence:

        getNamespaceContext().declareNamespace(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI,"xsi",true);
        endNamespaceDecls();
        attribute(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI,"nil","true");
        endAttributes();
Inherited from org.glassfish.jaxb.runtime.v2.runtime.Coordinator:
_getInstancecontainsAdaptererrorfatalErrorgetAdapterpopCoordinatorpushCoordinatorputAdapterwarning

Field Detail

attachmentMarshallerback to summary
public AttachmentMarshaller attachmentMarshaller
base64Databack to summary
private Base64Data base64Data

Cached instance of Base64Data.

contentHandlerAdapterback to summary
private ContentHandlerAdaptor contentHandlerAdapter

Lazily created.

currentPropertyback to summary
pack-priv ThreadLocal<Property<BeanT>> currentProperty
cycleDetectionStackback to summary
private final CollisionCheckStack<Object> cycleDetectionStack

Used to detect cycles in the object. Also used to learn what's being marshalled.

expectedMimeTypeback to summary
private MimeType expectedMimeType
fragmentback to summary
private boolean fragment
grammarback to summary
public final JAXBContextImpl grammar
identityTransformerback to summary
private Transformer identityTransformer

Lazily created identitiy transformer.

idReferencedObjectsback to summary
private final Set<Object> idReferencedObjects

Objects referenced through IDREF.

inlineBinaryFlagback to summary
private boolean inlineBinaryFlag

True to force inlining.

intDataback to summary
private final IntData intData

Cached instance of IntData.

knownUri2prefixIndexMapback to summary
public final int[] knownUri2prefixIndexMap
marshallerback to summary
private final MarshallerImpl marshaller

Marshaller object to which this object belongs.

nameListback to summary
public final NameList nameList
noNsSchemaLocationback to summary
private String noNsSchemaLocation
nsContextback to summary
private final NamespaceContextImpl nsContext
nseback to summary
private NamespaceContextImpl.Element nse
objectsWithIdback to summary
private final Set<Object> objectsWithId

Objects with ID.

outback to summary
private XmlOutput out

The XML printer.

schemaLocationback to summary
private String schemaLocation

Optional attributes to go with root element.

schemaTypeback to summary
private QName schemaType

Field used to support an jakarta.xml.bind.annotation.XmlSchemaType annotation.

When we are marshalling a property with an effective jakarta.xml.bind.annotation.XmlSchemaType, this field is set to hold the QName of that type. The Transducer that actually converts a Java object into XML can look this property to decide how to marshal the value.

seenRootback to summary
private boolean seenRoot

Set to false once we see the start tag of the root element.

textHasAlreadyPrintedback to summary
private boolean textHasAlreadyPrinted

Set to true if a text is already written, and we need to print ' ' for additional text methods.

Constructor Detail

XMLSerializerback to summary
pack-priv XMLSerializer(MarshallerImpl _owner)

Method Detail

addInscopeBindingback to summary
public void addInscopeBinding(String nsUri, String prefix)

This method can be called after startDocument is called but before the marshalling begins, to set the currently in-scope namespace bindings.

This method is useful to avoid redundant namespace declarations when the marshalling is producing a sub-document.

attributeback to summary
public void attribute(String uri, String local, String value) throws SAXException
attributeback to summary
public void attribute(Name name, CharSequence value) throws IOException, XMLStreamException
attWildcardAsAttributesback to summary
public void attWildcardAsAttributes(Map<QName, String> attributes, String fieldName) throws SAXException
attWildcardAsURIsback to summary
public void attWildcardAsURIs(Map<QName, String> attributes, String fieldName)
childAsRootback to summary
public void childAsRoot(Object obj) throws JAXBException, IOException, SAXException, XMLStreamException
childAsSoleContentback to summary
public void childAsSoleContent(Object child, String fieldName) throws SAXException, IOException, XMLStreamException

The equivalent of:

childAsURIs(child, fieldName);
endNamespaceDecls();
childAsAttributes(child, fieldName);
endAttributes();
childAsBody(child, fieldName);
This produces the given child object as the sole content of an element. Used to reduce the code size in the generated marshaller.
childAsXsiTypeback to summary
public void childAsXsiType(Object child, String fieldName, JaxBeanInfo<BeanT> expected, boolean nillable) throws SAXException, IOException, XMLStreamException

This method is called when a type child object is found.

This method produces events of the following form:

NSDECL* "endNamespaceDecls" ATTRIBUTE* "endAttributes" BODY
optionally including @xsi:type if necessary.
Parameters
child:Object

Object to be marshalled. The JaxBeanInfo for this object must return a type name.

fieldName:String

property name of the parent objeect from which 'o' comes. Used as a part of the error message in case anything goes wrong with 'o'.

expected:JaxBeanInfo<BeanT>

Expected type of the object.

clearCurrentPropertyback to summary
public void clearCurrentProperty()

Takes care of cleaning the currentProperty. Must be called from the same thread that created the XMLSerializer.

closeback to summary
public void close()
endAttributesback to summary
public void endAttributes() throws SAXException, IOException, XMLStreamException

Switches to the "marshal child texts/elements" mode. This method has to be called after the 1st pass is completed.

endDocumentback to summary
public void endDocument() throws IOException, SAXException, XMLStreamException
endElementback to summary
public void endElement() throws SAXException, IOException, XMLStreamException

Ends marshalling of an element. Pops the internal stack.

endNamespaceDeclsback to summary
public void endNamespaceDecls(Object innerPeer) throws IOException, XMLStreamException
errorMissingIdback to summary
public void errorMissingId(Object obj) throws SAXException

Called when a referenced object doesn't have an ID.

fireAfterMarshalEventsback to summary
private void fireAfterMarshalEvents(final JaxBeanInfo<BeanT> beanInfo, Object currentTarget)

Invoke the afterMarshal api on the external listener (if it exists) and on the bean embedded afterMarshal api(if it exists). This method is called only after the callee has determined that beanInfo.lookForLifecycleMethods == true.

fireBeforeMarshalEventsback to summary
private void fireBeforeMarshalEvents(final JaxBeanInfo<BeanT> beanInfo, Object currentTarget)

Invoke the beforeMarshal api on the external listener (if it exists) and on the bean embedded beforeMarshal api(if it exists). This method is called only after the callee has determined that beanInfo.lookForLifecycleMethods == true.

fireMarshalEventback to summary
private void fireMarshalEvent(Object target, Method m)
getCachedBase64DataInstanceback to summary
public Base64Data getCachedBase64DataInstance()

Deprecated

Base64Data is no longer cached, so that XMLStreamWriterEx impl can retain the data, like JAX-WS does.

Gets the cached instance of Base64Data.

Annotations
@Deprecated
getCurrentLocationback to summary
public ValidationEventLocator getCurrentLocation(String fieldName)
getCurrentPropertyback to summary
public Property<BeanT> getCurrentProperty()

May return null when the property hasn't been set. Introduced based on Jersey requirements.

getIdentityTransformerback to summary
public Transformer getIdentityTransformer()
getIdFromObjectback to summary
private String getIdFromObject(Object identifiableObject) throws SAXException, JAXBException

Gets the ID value from an identifiable object.

getInlineBinaryFlagback to summary
public boolean getInlineBinaryFlag()
getInstanceback to summary
public static XMLSerializer getInstance()

When called from within the realm of the marshaller, this method returns the current in charge.

getLocationback to summary
protected ValidationEventLocator getLocation()

Implements abstract org.glassfish.jaxb.runtime.v2.runtime.Coordinator.getLocation.

Doc from org.glassfish.jaxb.runtime.v2.runtime.Coordinator.getLocation.

Gets the current location. Used for reporting the error source location.

Annotations
@Override
getNamespaceContextback to summary
public NamespaceContext2 getNamespaceContext()
getObjectIdentityCycleDetectionback to summary
public boolean getObjectIdentityCycleDetection()
getSchemaTypeback to summary
public QName getSchemaType()
getXMIMEContentTypeback to summary
public String getXMIMEContentType()

Gets the MIME type with which the binary content shall be printed.

This method shall be used from those RuntimeBuiltinLeafInfo that are bound to base64Binary.

See Also
JAXBContextImpl#getXMIMEContentType(Object)
handleErrorback to summary
public boolean handleError(Exception e)
handleErrorback to summary
public boolean handleError(Exception e, Object source, String fieldName)
handleEventback to summary
public boolean handleEvent(ValidationEvent event)

Implements jakarta.xml.bind.ValidationEventHandler.handleEvent.

Doc from jakarta.xml.bind.ValidationEventHandler.handleEvent.

Receive notification of a validation warning or error. The ValidationEvent will have a ValidationEventLocator embedded in it that indicates where the error or warning occurred.

If an unchecked runtime exception is thrown from this method, the Jakarta XML Binding provider will treat it as if the method returned false and interrupt the current unmarshal, validate, or marshal operation.

Annotations
@Override
handleMissingObjectErrorback to summary
private void handleMissingObjectError(String fieldName) throws SAXException, IOException, XMLStreamException
leafElementback to summary
public void leafElement(Name tagName, String data, String fieldName) throws SAXException, IOException, XMLStreamException
leafElementback to summary
public void leafElement(Name tagName, Pcdata data, String fieldName) throws SAXException, IOException, XMLStreamException
leafElementback to summary
public void leafElement(Name tagName, int data, String fieldName) throws SAXException, IOException, XMLStreamException
onIDback to summary
public String onID(Object owner, String value)
onIDREFback to summary
public String onIDREF(Object obj) throws SAXException
pushObjectback to summary
private Object pushObject(Object obj, String fieldName) throws SAXException

Pushes the object to cycleDetectionStack and also detect any cycles. When a cycle is found, this method tries to recover from it.

Returns:Object

the object that should be marshalled instead of the given obj, or null if the error is found and we need to avoid marshalling this object to prevent infinite recursion. When this method returns null, the error has already been reported.

reconcileIDback to summary
pack-priv void reconcileID() throws SAXException
reportErrorback to summary
public void reportError(ValidationEvent ve) throws SAXException
reportErrorback to summary
public void reportError(String fieldName, Throwable t) throws SAXException

Report an error found as an exception.

Parameters
fieldName:String

the name of the property being processed when an error is found.

reportMissingObjectErrorback to summary
private void reportMissingObjectError(String fieldName) throws SAXException
setExpectedMimeTypeback to summary
public MimeType setExpectedMimeType(MimeType expectedMimeType)

This method is used by MimeTypedTransducer to set the expected MIME type for the encapsulated Transducer.

setInlineBinaryFlagback to summary
public boolean setInlineBinaryFlag(boolean value)
setObjectIdentityCycleDetectionback to summary
public void setObjectIdentityCycleDetection(boolean val)
setPrefixMapperback to summary
public void setPrefixMapper(NamespacePrefixMapper prefixMapper)
setSchemaTypeback to summary
public QName setSchemaType(QName st)
startDocumentback to summary
public void startDocument(XmlOutput out, boolean fragment, String schemaLocation, String noNsSchemaLocation) throws IOException, SAXException, XMLStreamException

Reset this object to write to the specified output.

Parameters
schemaLocation:String

if non-null, this value is printed on the root element as xsi:schemaLocation

noNsSchemaLocation:String

Similar to 'schemaLocation' but this one works for xsi:noNamespaceSchemaLocation

startElementback to summary
public void startElement(Name tagName, Object outerPeer)
startElementback to summary
public void startElement(String nsUri, String localName, String preferredPrefix, Object outerPeer)
startElementback to summary
private void startElement()
startElementForceback to summary
public void startElementForce(String nsUri, String localName, String forcedPrefix, Object outerPeer)

Variation of startElement(String, String, String, Object) that forces a specific prefix. Needed to preserve the prefix when marshalling DOM.

textback to summary
public void text(String text, String fieldName) throws SAXException, IOException, XMLStreamException

Marshalls text.

This method can be called after the endAttributes() method to marshal texts inside elements. If the method is called more than once, those texts are considered as separated by whitespaces. For example,

c.startElement("","foo");
c.endAttributes();
c.text("abc");
c.text("def");
  c.startElement("","bar");
  c.endAttributes();
  c.endElement();
c.text("ghi");
c.endElement();
will generate <foo>abc def<bar/>ghi</foo>.
textback to summary
public void text(Pcdata text, String fieldName) throws SAXException, IOException, XMLStreamException

The text(String, String) method that takes Pcdata.

writeDomback to summary
public <E> void writeDom(E element, DomHandler<E, ?> domHandler, Object parentBean, String fieldName) throws SAXException
writeXsiNilTrueback to summary
public void writeXsiNilTrue() throws SAXException, IOException, XMLStreamException

Short for the following call sequence:

        getNamespaceContext().declareNamespace(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI,"xsi",true);
        endNamespaceDecls();
        attribute(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI,"nil","true");
        endAttributes();