use of org.apache.axiom.ext.stax.datahandler.DataHandlerReader in project webservices-axiom by apache.
the class XMLStreamReaderUtils method getDataHandlerFromElement.
/**
* Get a {@link DataHandler} for the binary data encoded in an element. The method supports
* base64 encoded character data as well as optimized binary data through the
* {@link DataHandlerReader} extension.
* <p>
* <em>Precondition</em>: the reader is on a {@link XMLStreamConstants#START_ELEMENT}
* <p>
* <em>Postcondition</em>: the reader is on the corresponding
* {@link XMLStreamConstants#END_ELEMENT}
*
* @param reader the stream to read the data from
* @return the binary data from the element
*/
public static DataHandler getDataHandlerFromElement(XMLStreamReader reader) throws XMLStreamException {
int event = reader.next();
if (event == XMLStreamConstants.END_ELEMENT) {
// This means that the element is actually empty -> return empty DataHandler
return new DataHandler(new EmptyDataSource("application/octet-stream"));
} else if (event != XMLStreamConstants.CHARACTERS) {
throw new XMLStreamException("Expected a CHARACTER event");
}
DataHandlerReader dhr = getDataHandlerReader(reader);
if (dhr != null && dhr.isBinary()) {
DataHandler dh = dhr.getDataHandler();
reader.next();
return dh;
} else {
MemoryBlob blob = Blobs.createMemoryBlob();
Writer out = new Base64DecodingOutputStreamWriter(blob.getOutputStream());
try {
writeTextTo(reader, out);
// CHARACTERS events
loop: while (true) {
switch(reader.next()) {
case XMLStreamConstants.CHARACTERS:
writeTextTo(reader, out);
break;
case XMLStreamConstants.END_ELEMENT:
break loop;
default:
throw new XMLStreamException("Expected a CHARACTER event");
}
}
out.close();
} catch (IOException ex) {
throw new XMLStreamException("Error during base64 decoding", ex);
}
return new DataHandler(new BlobDataSource(blob, "application/octet-string"));
}
}
Aggregations