public byte[] serialize(MediaContent content) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(expectedSize); XMLStreamWriter writer = outFactory.createXMLStreamWriter(baos, "UTF-8"); writer.writeStartDocument("UTF-8", "1.0"); writer.writeStartElement("mc"); writeMedia(writer, content.getMedia()); for (int i = 0, len = content.imageCount(); i < len; ++i) { writeImage(writer, content.getImage(i)); } writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); byte[] array = baos.toByteArray(); expectedSize = array.length; return array; }
public MediaContent deserialize(byte[] array) throws Exception { XMLStreamReader parser = inFactory.createXMLStreamReader(new ByteArrayInputStream(array)); searchTag(parser, "mc"); MediaContent content = new MediaContent(readMedia(parser)); if (parser.nextTag() != XMLStreamConstants.START_ELEMENT) { throw new IllegalStateException( "Expected <im>, no START_ELEMENT encountered but " + parser.getEventType()); } do { if (!"im".equals(parser.getLocalName())) { throw new IllegalStateException("Expected <im>, got <" + parser.getLocalName() + ">"); } content.addImage(readImage(parser)); } while (parser.nextTag() == XMLStreamConstants.START_ELEMENT); // and should have closing </mc> at this point if (!"mc".equals(parser.getLocalName())) { throw new IllegalStateException( "Expected closing </mc>, got </" + parser.getLocalName() + ">"); } parser.close(); return content; }