private void increaseSearchIndexStartTimeDelay() throws Exception {
    FileOutputStream fileOutputStream = null;
    XMLStreamWriter writer = null;
    OMElement documentElement = getRegistryXmlOmElement();
    try {
      AXIOMXPath xpathExpression =
          new AXIOMXPath("/wso2registry/indexingConfiguration/startingDelayInSeconds");
      OMElement indexConfigNode = (OMElement) xpathExpression.selectSingleNode(documentElement);
      indexConfigNode.setText("2");

      AXIOMXPath xpathExpression1 =
          new AXIOMXPath("/wso2registry/indexingConfiguration/indexingFrequencyInSeconds");
      OMElement indexConfigNode1 = (OMElement) xpathExpression1.selectSingleNode(documentElement);
      indexConfigNode1.setText("1");

      fileOutputStream = new FileOutputStream(getRegistryXMLPath());
      writer = XMLOutputFactory.newInstance().createXMLStreamWriter(fileOutputStream);
      documentElement.serialize(writer);
      documentElement.build();
      Thread.sleep(2000);

    } catch (Exception e) {
      log.error("registry.xml edit fails" + e.getMessage());
      throw new Exception("registry.xml edit fails" + e.getMessage());
    } finally {
      assert fileOutputStream != null;
      fileOutputStream.close();
      assert writer != null;
      writer.flush();
    }
  }
  public void append(
      final XMLStreamWriter writer,
      final EntityInfoAggregator eia,
      final Map<String, Object> data,
      final boolean isRootElement,
      final boolean isFeedPart)
      throws EntityProviderException {
    try {
      writer.writeStartElement(FormatXml.ATOM_ENTRY);

      if (isRootElement) {
        writer.writeDefaultNamespace(Edm.NAMESPACE_ATOM_2005);
        writer.writeNamespace(Edm.PREFIX_M, Edm.NAMESPACE_M_2007_08);
        writer.writeNamespace(Edm.PREFIX_D, Edm.NAMESPACE_D_2007_08);
      }
      if (!isFeedPart) {
        writer.writeAttribute(
            Edm.PREFIX_XML,
            Edm.NAMESPACE_XML_1998,
            "base",
            properties.getServiceRoot().toASCIIString());
      }

      etag = createETag(eia, data);
      if (etag != null) {
        writer.writeAttribute(Edm.NAMESPACE_M_2007_08, FormatXml.M_ETAG, etag);
      }

      // write all atom infos (mandatory and optional)
      appendAtomMandatoryParts(writer, eia, data);
      appendAtomOptionalParts(writer, eia, data);

      if (eia.getEntityType().hasStream()) {
        // write all links
        appendAtomEditLink(writer, eia, data);
        appendAtomContentLink(writer, eia, data, properties.getMediaResourceMimeType());
        appendAtomNavigationLinks(writer, eia, data);
        // write properties/content
        appendCustomProperties(writer, eia, data);
        appendAtomContentPart(writer, eia, data, properties.getMediaResourceMimeType());
        appendProperties(writer, eia, data);
      } else {
        // write all links
        appendAtomEditLink(writer, eia, data);
        appendAtomNavigationLinks(writer, eia, data);
        // write properties/content
        appendCustomProperties(writer, eia, data);
        writer.writeStartElement(FormatXml.ATOM_CONTENT);
        writer.writeAttribute(FormatXml.ATOM_TYPE, ContentType.APPLICATION_XML.toString());
        appendProperties(writer, eia, data);
        writer.writeEndElement();
      }

      writer.writeEndElement();

      writer.flush();
    } catch (Exception e) {
      throw new EntityProviderException(EntityProviderException.COMMON, e);
    }
  }
Beispiel #3
0
  /**
   * Конвертирует XMLDOM древо в текстовое представление
   *
   * @param xmlDocument XMLDOM древо
   * @return Текстовое представление XMLDOM древа
   * @throws javax.xml.stream.XMLStreamException Если не смогло
   * @throws javax.xml.transform.TransformerConfigurationException Если не смогло
   * @throws javax.xml.transform.TransformerException Если не смогло
   * @throws java.io.IOException Если не смогло
   */
  public static String toStringWithException(Node xmlDocument)
      throws XMLStreamException, TransformerConfigurationException, TransformerException,
          IOException {
    if (xmlDocument == null) {
      throw new IllegalArgumentException("xmlDocument == null");
    }

    Transformer tr = TransformerFactory.newInstance().newTransformer();

    DOMSource domSrc = new DOMSource(xmlDocument);

    StringWriter sWiter = new StringWriter();
    XMLStreamWriter xml2format = new FormatXMLWriter(sWiter);

    StAXResult sResult = new StAXResult(xml2format);
    Result result = sResult;

    tr.transform(domSrc, result);

    //        sWiter.flush();
    xml2format.writeEndDocument();
    xml2format.flush();

    String toOutput = sWiter.toString();

    xml2format.close();
    sWiter.close();

    return toOutput;
  }
  @Override
  public EndElement endElement(final EndElement element) throws XMLStreamException {
    final String theName = element.getLocalName();

    if ("component".equals(theName)) {
      if (this.componentId == null) {
        final Map components = (Map) outputStreams.get("components");
        components.remove(this.componentId);
      }
      this.inComponent = false;
      this.componentId = null;
    }
    if (this.inside) {
      this.insideLevel--;
      if (this.insideLevel > 0 || this.insideLevel == 0 && !"md-record".equals(theName)) {
        writer.writeEndElement();
      }

      if (this.insideLevel == 0) {
        this.inside = false;
        writer.flush();
        writer.close();
      }
    }

    return element;
  }
Beispiel #5
0
 private byte[] getMessageBytes(Document doc) throws Exception {
   ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
   XMLStreamWriter byteArrayWriter = StaxUtils.createXMLStreamWriter(outputStream);
   StaxUtils.writeDocument(doc, byteArrayWriter, false);
   byteArrayWriter.flush();
   return outputStream.toByteArray();
 }
  /**
   * Creates the <a href="http://wiki.mindmakers.org/projects:BML:main">Behavior Markup Language</a>
   * string for Avatar.
   *
   * @param utterance the utterance to speak <code>null</code>
   * @param ssml SSML with BML annotations
   * @return created XML string
   * @throws XMLStreamException if the stream could not be created.
   */
  private String createBML(final String utterance, final SsmlDocument ssml)
      throws XMLStreamException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final XMLOutputFactory factory = XMLOutputFactory.newInstance();
    final XMLStreamWriter writer = factory.createXMLStreamWriter(out, ENCODING);
    writer.writeStartDocument(ENCODING, "1.0");
    writer.writeStartElement("bml");
    writer.writeAttribute("id", "bml1");
    writer.writeNamespace("ns1", BML_NAMESPACE_URI);
    if (ssml != null) {
      final Speak speak = ssml.getSpeak();
      final NodeList children = speak.getChildNodes();
      for (int i = 0; i < children.getLength(); i++) {
        final Node child = children.item(i);
        final String namespace = child.getNamespaceURI();
        if (namespace != null) {
          writeBMLNode(writer, child, utterance);
        }
      }
    }

    writer.writeEndElement();
    writer.writeEndDocument();
    writer.flush();
    // lastGestureEndTime = 0;
    writer.close();
    try {
      String output = out.toString(ENCODING);
      return output;
    } catch (UnsupportedEncodingException e) {
      LOGGER.warn(e.getMessage(), e);
      return out.toString();
    }
  }
  /**
   * Serialize the given event data as a standalone XML document
   *
   * @param includeProlog if true, include an XML prolog; if not, just render a document fragment
   * @return the XML serialization, or null if <code>data</code> is null.
   */
  public String serialize(EventDataElement data, boolean includeProlog) {
    if (data == null || data.isNull()) return null;

    try {
      // serialize the DOM to our string buffer.
      XMLStreamWriter writer = factory.createXMLStreamWriter(buffer);
      try {
        if (includeProlog) writer.writeStartDocument();
        serializeElement(writer, data);
        writer.writeEndDocument();
        writer.flush();
      } finally {
        writer.close();
      }

      // return buffer contents.
      return buffer.toString();

    } catch (XMLStreamException ioe) {
      // this shouldn't happen, since the target output stream is a StringWriter, but
      // the compiler demands that we handle it.
      throw new RuntimeException("Error serializing XML data", ioe);
    } finally {

      // reset the internal buffer for next run.
      buffer.getBuffer().setLength(0);
    }
  }
Beispiel #8
0
  public void close() {
    if (closed) {
      return;
    }
    closed = true;

    // finish off anything
    try {
      xmlw.writeEndElement(); // msRun element

      // declare the index does not exist
      xmlw.writeEmptyElement("indexOffset");
      xmlw.writeAttribute("xsi:nil", "1");

      xmlw.writeEndElement(); // mzXML element

      // close out the xml writer
      xmlw.flush();
      xmlw.close();
    } catch (XMLStreamException e) {
      throw new RuntimeException("Can't write all of XML!", e);
    } finally {
      super.close();
    }
  }
 public void safeFlush(final XMLStreamWriter flushable) {
   if (flushable != null)
     try {
       flushable.flush();
     } catch (Throwable ignore) {
     }
 }
Beispiel #10
0
  public void export(File f, ConceptMap cmap) {
    this.cmap = cmap;
    try (OutputStream outputStream = new FileOutputStream(f)) {

      out =
          XMLOutputFactory.newInstance()
              .createXMLStreamWriter(new OutputStreamWriter(outputStream, "utf-8"));

      out.writeStartElement("cmap");

      out.writeStartElement("map");

      writeConceptList();
      writeLinkList();
      writeConnections();

      out.writeEndElement();

      out.writeEndElement();

      out.writeEndDocument();

      out.flush();
    } catch (Exception e) {
      LOG.error(ERROR_MESSAGE, e);
    }
  }
  private void initialiseProjectFiles(
      IProject project, IContainer container, IProgressMonitor monitor) throws CoreException {

    // create a config Dir
    IFolder configFolder = project.getFolder("config");
    configFolder.create(false, true, null);
    File configDir = configFolder.getLocation().toFile();

    monitor.beginTask("Creating config file ", 1);

    XMLOutputFactory factory = XMLOutputFactory.newInstance();

    try {
      XMLStreamWriter writer =
          factory.createXMLStreamWriter(
              new FileWriter(configDir.getAbsolutePath() + "\\config.xml"));

      writer.writeStartDocument();
      writer.writeStartElement("document");
      writer.writeStartElement("data");
      writer.writeAttribute("name", "value");
      writer.writeEndElement();
      writer.writeEndElement();
      writer.writeEndDocument();

      writer.flush();
      writer.close();

    } catch (XMLStreamException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Beispiel #12
0
  /**
   * @param args
   * @throws Exception
   */
  public static void main(String[] args) throws Exception {
    try {
      String fileName = null;
      try {
        if (args[0].equals("-f")) {
          fileName = args[1];
        } else {
          printUsage();
          return;
        }
      } catch (Exception ex) {
        printUsage();
        return;
      }

      XMLOutputFactory xof = XMLOutputFactory.newInstance();
      XMLStreamWriter xtw = null;
      xtw = xof.createXMLStreamWriter(new FileOutputStream(fileName), "utf-8");
      xtw.writeStartDocument("utf-8", "1.0");
      xtw.writeComment("StAX Sample: writer.HelloWorld");
      xtw.writeStartElement("hello");
      xtw.writeDefaultNamespace("http://samples");
      xtw.writeCharacters("this crazy");
      xtw.writeEmptyElement("world");
      xtw.writeEndElement();
      xtw.writeEndDocument();
      xtw.flush();
      xtw.close();
    } catch (Exception ex) {
      ex.printStackTrace();
      System.err.println("Exception occurred while running Hello World samples");
    }
    System.out.println("Done");
  }
 public void flush() {
   try {
     out.flush();
   } catch (XMLStreamException e) {
     throw new TxwException(e);
   }
 }
  @Override
  public SerializerResult metadataDocument(final ServiceMetadata serviceMetadata)
      throws SerializerException {
    CircleStreamBuffer buffer;
    XMLStreamWriter xmlStreamWriter = null;

    try {
      buffer = new CircleStreamBuffer();
      xmlStreamWriter =
          XMLOutputFactory.newInstance()
              .createXMLStreamWriter(buffer.getOutputStream(), DEFAULT_CHARSET);
      MetadataDocumentXmlSerializer serializer = new MetadataDocumentXmlSerializer(serviceMetadata);
      serializer.writeMetadataDocument(xmlStreamWriter);
      xmlStreamWriter.flush();
      xmlStreamWriter.close();

      return SerializerResultImpl.with().content(buffer.getInputStream()).build();
    } catch (final XMLStreamException e) {
      log.error(e.getMessage(), e);
      throw new SerializerException(
          "An I/O exception occurred.", e, SerializerException.MessageKeys.IO_EXCEPTION);
    } finally {
      if (xmlStreamWriter != null) {
        try {
          xmlStreamWriter.close();
        } catch (XMLStreamException e) {
          throw new SerializerException(
              "An I/O exception occurred.", e, SerializerException.MessageKeys.IO_EXCEPTION);
        }
      }
    }
  }
 public void endDocument() {
   try {
     out.writeEndDocument();
     out.flush();
   } catch (XMLStreamException e) {
     throw new TxwException(e);
   }
 }
Beispiel #16
0
 public Binary getContent() throws UserException {
   try {
     xtw.flush();
     xtw.close();
     return content;
   } catch (Exception e) {
     throw new UserException(455, e.getMessage());
   }
 }
Beispiel #17
0
  public byte[] convertToXML(BpmnModel model) {
    try {

      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

      XMLOutputFactory xof = XMLOutputFactory.newInstance();
      OutputStreamWriter out = new OutputStreamWriter(outputStream, "UTF-8");

      XMLStreamWriter writer = xof.createXMLStreamWriter(out);
      XMLStreamWriter xtw = new IndentingXMLStreamWriter(writer);

      DefinitionsRootExport.writeRootElement(model, xtw);
      SignalAndMessageDefinitionExport.writeSignalsAndMessages(model, xtw);
      PoolExport.writePools(model, xtw);

      for (Process process : model.getProcesses()) {

        if (process.getFlowElements().size() == 0 && process.getLanes().size() == 0) {
          // empty process, ignore it
          continue;
        }

        ProcessExport.writeProcess(process, xtw);

        for (FlowElement flowElement : process.getFlowElements()) {
          createXML(flowElement, model, xtw);
        }

        for (Artifact artifact : process.getArtifacts()) {
          createXML(artifact, model, xtw);
        }

        // end process element
        xtw.writeEndElement();
      }

      BPMNDIExport.writeBPMNDI(model, xtw);

      // end definitions root element
      xtw.writeEndElement();
      xtw.writeEndDocument();

      xtw.flush();

      outputStream.close();

      xtw.close();

      return outputStream.toByteArray();

    } catch (Exception e) {
      LOGGER.error("Error writing BPMN XML", e);
      throw new XMLException("Error writing BPMN XML", e);
    }
  }
  /**
   * Copies the current node and its children to the <code>sink</code>.
   *
   * @param sink the output sink
   */
  public void copyNode(OutputStream sink) throws XMLStreamException {
    Assertion.notNull(sink);

    outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", isNsRepairing);
    final XMLStreamWriter writer = outputFactory.createXMLStreamWriter(sink);

    final DcsStreamSupport dcsStream = new DcsStreamSupport();
    dcsStream.copyNode(in, writer);
    writer.flush();
    writer.close();
  }
Beispiel #19
0
 @Override
 public void finish() {
   try {
     writer.writeEndElement();
     writer.writeEndDocument();
     writer.flush();
     writer.close();
     out.close();
   } catch (XMLStreamException | IOException e) {
     throw new RuntimeException(e);
   }
 }
Beispiel #20
0
  void writeWithoutAttachments(MessageContext context, OutMessage message, OutputStream out)
      throws XFireException {
    XMLStreamWriter writer = STAXUtils.createXMLStreamWriter(out, message.getEncoding(), context);

    message.getSerializer().writeMessage(message, writer, context);

    try {
      writer.flush();
    } catch (XMLStreamException e) {
      logger.error(e);
      throw new XFireException("Couldn't send message.", e);
    }
  }
 private static String dto2ddi(DatasetDTO datasetDto) throws XMLStreamException {
   OutputStream outputStream = new ByteArrayOutputStream();
   XMLStreamWriter xmlw = XMLOutputFactory.newInstance().createXMLStreamWriter(outputStream);
   xmlw.writeStartElement("codeBook");
   xmlw.writeDefaultNamespace("http://www.icpsr.umich.edu/DDI");
   writeAttribute(xmlw, "version", "2.0");
   createStdyDscr(xmlw, datasetDto);
   createdataDscr(xmlw, datasetDto.getDatasetVersion().getFiles());
   xmlw.writeEndElement(); // codeBook
   xmlw.flush();
   String xml = outputStream.toString();
   return XmlPrinter.prettyPrintXml(xml);
 }
Beispiel #22
0
  @Override
  public void encodeResourceToWriter(IBaseResource theResource, Writer theWriter)
      throws DataFormatException {
    XMLStreamWriter eventWriter;
    try {
      eventWriter = createXmlWriter(theWriter);

      encodeResourceToXmlStreamWriter(theResource, eventWriter, false);
      eventWriter.flush();
    } catch (XMLStreamException e) {
      throw new ConfigurationException("Failed to initialize STaX event factory", e);
    }
  }
 @Override
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
   Object result = null;
   Throwable error = null;
   try {
     result = method.invoke(target, args);
   } catch (InvocationTargetException e) {
     error = e.getTargetException();
   } catch (Throwable e) {
     // Proxy not allowed to throw exception
   }
   if (method.getDeclaringClass() != Object.class) {
     try {
       StringWriter stringWriter = new StringWriter();
       this.writer = XMLOutputFactory.newInstance().createXMLStreamWriter(stringWriter);
       writer.writeStartElement("invoke");
       writer.writeAttribute("timestamp", Long.valueOf(System.currentTimeMillis()).toString());
       writer.writeAttribute("class", target.getClass().getName());
       writer.writeAttribute("name", method.getName());
       if (args != null && args.length != 0) {
         writer.writeStartElement("arguments");
         for (int i = 0; i < args.length; i++) {
           writer.writeStartElement("argument");
           writeObject(args[i]);
           writer.writeEndElement();
         }
         writer.writeEndElement();
       } else {
         writer.writeEmptyElement("arguments");
       }
       if (method.getReturnType() != void.class && error == null) {
         writer.writeStartElement("return");
         writeObject(result);
         writer.writeEndElement();
       } else if (error != null) {
         writer.writeStartElement("thrown");
         writer.writeCharacters(error.toString());
         writer.writeEndElement();
       }
       writer.writeEndElement();
       writer.flush();
       initialWriter.write(stringWriter.toString() + System.lineSeparator());
     } catch (Exception e) {
       // Proxy not allowed to throw exceptions
     }
   }
   if (error != null) {
     throw error;
   }
   return result;
 }
  public static void main(String[] args) {
    try {
      // FLUJO DE ESCRITURA
      XMLStreamWriter sw =
          XMLOutputFactory.newInstance().createXMLStreamWriter(new FileOutputStream("autores.xml"));

      // ESCRITURA
      sw.writeStartDocument("1.0");
      sw.writeStartElement("autores");
      sw.writeStartElement("autor");
      sw.writeAttribute("codigo", "a1");
      sw.writeStartElement("nome");
      sw.writeCharacters("Alexandre Dumas");
      sw.writeEndElement();
      sw.writeStartElement("titulo");
      sw.writeCharacters("El conde de montecristo");
      sw.writeEndElement();
      sw.writeStartElement("titulo");
      sw.writeCharacters("Los miserables");
      sw.writeEndElement();
      sw.writeEndElement();
      sw.writeStartElement("autor");
      sw.writeAttribute("codigo", "a2");
      sw.writeStartElement("nome");
      sw.writeCharacters("Fiodor Dostoyevski");
      sw.writeEndElement();
      sw.writeStartElement("titulo");
      sw.writeCharacters(" El idiota");
      sw.writeEndElement();
      sw.writeStartElement("titulo");
      sw.writeCharacters("Noches blancas");
      sw.writeEndDocument();
      sw.flush();
      sw.close();

      // FLUJO DE LECTURA
      XMLEventReader er =
          XMLInputFactory.newInstance()
              .createXMLEventReader("autores.xml", new FileInputStream("autores.xml"));

      // LECTURA
      while (er.hasNext()) {
        System.out.println(er.nextEvent().toString());
      }
      er.close();

    } catch (XMLStreamException | FileNotFoundException ex) {
      Logger.getLogger(XMLprueba0.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Beispiel #25
0
  public void writeSchema(XMLStreamWriter out) throws XMLStreamException, JAXBException {
    out.writeStartElement("xsd", "schema", W3C_XML_SCHEMA_NS_URI);
    out.writeAttribute("version", "1.0");
    out.writeAttribute("targetNamespace", _namespace);
    out.writeNamespace(TARGET_NAMESPACE_PREFIX, _namespace);

    _context.generateSchemaWithoutHeader(out);

    for (AbstractAction action : _actionNames.values())
      action.writeSchema(out, _namespace, _context);

    out.writeEndElement(); // schema

    out.flush();
  }
  public void testObjectToXMLStreamWriterRecord() throws Exception {
    if (XML_OUTPUT_FACTORY != null) {
      StringWriter writer = new StringWriter();

      XMLOutputFactory factory = XMLOutputFactory.newInstance();
      factory.setProperty(factory.IS_REPAIRING_NAMESPACES, new Boolean(false));
      XMLStreamWriter streamWriter = factory.createXMLStreamWriter(writer);

      Object objectToWrite = getWriteControlObject();
      XMLDescriptor desc = null;
      if (objectToWrite instanceof XMLRoot) {
        desc =
            (XMLDescriptor)
                xmlContext
                    .getSession(0)
                    .getProject()
                    .getDescriptor(((XMLRoot) objectToWrite).getObject().getClass());
      } else {
        desc =
            (XMLDescriptor)
                xmlContext.getSession(0).getProject().getDescriptor(objectToWrite.getClass());
      }
      jaxbMarshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/xml");

      int sizeBefore = getNamespaceResolverSize(desc);
      XMLStreamWriterRecord record = new XMLStreamWriterRecord(streamWriter);
      try {
        ((org.eclipse.persistence.jaxb.JAXBMarshaller) jaxbMarshaller)
            .marshal(objectToWrite, record);
      } catch (Exception e) {
        assertMarshalException(e);
        return;
      }
      if (expectsMarshalException) {
        fail("An exception should have occurred but didn't.");
        return;
      }

      streamWriter.flush();
      int sizeAfter = getNamespaceResolverSize(desc);

      assertEquals(sizeBefore, sizeAfter);

      Document testDocument = getTestDocument(writer.toString());
      writer.close();
      objectToXMLDocumentTest(testDocument);
    }
  }
Beispiel #27
0
 //    public static void write(OutputStream stream, Element element, int hashLength) throws
 // XMLStreamException {
 //        XMLOutputFactory xof = XMLOutputFactory.newInstance();
 //        IndentingXMLStreamWriter xtw = new
 // IndentingXMLStreamWriter(xof.createXMLStreamWriter(stream));
 //        writeXMLStreamWriter(xtw, element, hashLength);
 //    }
 //
 private static void writeXMLStreamWriter(XMLStreamWriter xtw, Element element, int hashLength)
     throws XMLStreamException {
   if (hashLength > 0) {
     String hash = element.getHash(hashLength);
     Element hashElement = new Element(CRC_ELEMENT);
     hashElement.setText(hash);
     element.addChild(hashElement);
   }
   writeElement(xtw, element);
   xtw.writeEndDocument();
   xtw.flush();
   xtw.close();
   if (hashLength > 0) {
     element.removeChildren(CRC_ELEMENT);
   }
 }
 @Override
 protected Object unmarshalFromReader(
     Unmarshaller unmarshaller, XMLStreamReader reader, Annotation[] anns, MediaType mt)
     throws JAXBException {
   CachedOutputStream out = new CachedOutputStream();
   try {
     XMLStreamWriter writer = StaxUtils.createXMLStreamWriter(out);
     StaxUtils.copy(new StaxSource(reader), writer);
     writer.writeEndDocument();
     writer.flush();
     writer.close();
     return unmarshalFromInputStream(unmarshaller, out.getInputStream(), anns, mt);
   } catch (Exception ex) {
     throw ExceptionUtils.toBadRequestException(ex, null);
   }
 }
 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;
 }
 @Override
 public void saveToXML(Writer out) throws IOException {
   XMLOutputFactory factory = XMLOutputFactory.newInstance();
   try {
     XMLStreamWriter writer = factory.createXMLStreamWriter(out);
     writer.writeStartElement("filter");
     writer.writeAttribute("class", getClass().getCanonicalName());
     super.saveToXML(writer);
     writer.writeAttribute("caseSensitive", Boolean.toString(caseSensitive));
     writer.writeCharacters(regex == null ? "" : regex);
     writer.writeEndElement();
     writer.flush();
     writer.close();
   } catch (XMLStreamException e) {
     throw new IOException("Cannot save as XML.", e);
   }
 }