XMLRoot xroot = (XMLRoot) object;
version = xroot.getXMLVersion() != null ? xroot.getXMLVersion() : version;
encoding = xroot.getEncoding() != null ? xroot.getEncoding() : encoding;
}
MarshalRecord writerRecord;
writer = new BufferedWriter(writer);
if (isFormattedOutput()) {
if(MediaType.APPLICATION_JSON == mediaType) {
writerRecord = new JSONFormattedWriterRecord();
((JSONFormattedWriterRecord) writerRecord).setWriter(writer);
} else {
writerRecord = new FormattedWriterRecord();
((FormattedWriterRecord) writerRecord).setWriter(writer);
}
} else {
if(MediaType.APPLICATION_JSON == mediaType) {
writerRecord = new JSONWriterRecord();
((JSONWriterRecord) writerRecord).setWriter(writer);
} else {
writerRecord = new WriterRecord();
((WriterRecord) writerRecord).setWriter(writer);
}
}
writerRecord.setMarshaller(this);
if(isXMLRoot){
if(session == null || xmlDescriptor == null){
try{
session = xmlContext.getSession(((XMLRoot)object).getObject());
if(session != null){
xmlDescriptor = getDescriptor(((XMLRoot)object).getObject(), session);
}
}catch (XMLMarshalException marshalException) {
if (!isSimpleXMLRoot((XMLRoot) object)) {
throw marshalException;
}
}
}
}else{
Class objectClass = object.getClass();
if(object instanceof Collection) {
try {
writerRecord.startCollection();
for(Object o : (Collection) object) {
marshal(o, writerRecord);
}
writerRecord.endCollection();
writer.flush();
} catch(IOException e) {
throw XMLMarshalException.marshalException(e);
}
return;
} else if(objectClass.isArray()) {
try {
writerRecord.startCollection();
int arrayLength = Array.getLength(object);
for(int x=0; x<arrayLength; x++) {
marshal(Array.get(object, x), writerRecord);
}
writerRecord.endCollection();
writer.flush();
} catch(IOException e) {
throw XMLMarshalException.marshalException(e);
}
return;
}
if(session == null || xmlDescriptor == null){
session = xmlContext.getSession(objectClass);
xmlDescriptor = getDescriptor(objectClass, session);
}
}
//if this is a simple xml root, the session and descriptor will be null
if (!(isXMLRoot && ((XMLRoot)object).getObject() instanceof Node) && ((session == null) || !xmlContext.getDocumentPreservationPolicy(session).shouldPreserveDocument())) {
marshal(object, writerRecord, session, xmlDescriptor, isXMLRoot);
} else {
try {
Node xmlDocument = null;
if(isXMLRoot && session == null) {
xmlDocument = (Node)((XMLRoot)object).getObject();
} else {
xmlDocument = objectToXMLNode(object, session, xmlDescriptor, isXMLRoot);
}
writerRecord.setSession(session);
if (isFragment()) {
writerRecord.node(xmlDocument, xmlDescriptor.getNamespaceResolver());
} else {
writerRecord.startDocument(encoding, version);
writerRecord.node(xmlDocument, writerRecord.getNamespaceResolver());
writerRecord.endDocument();
}
} catch (XMLPlatformException e) {
throw XMLMarshalException.marshalException(e);
}
}