@Override
  public void writeStats(MessageType message) {

    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent end = eventFactory.createDTD("\n");
    XMLEvent tab = eventFactory.createDTD("\t");
    // Create Start node

    List<Attribute> attrs = new LinkedList<Attribute>();

    attrs.add(eventFactory.createAttribute(REQUEST_NUM_ATTR_NAME, "" + countLine++));
    for (Stat stat : message.getValues()) {
      attrs.add(eventFactory.createAttribute(stat.getKey(), "" + stat.getValue()));
    }

    final Iterator<Attribute> attrIt = attrs.iterator();

    StartElement sElement =
        eventFactory.createStartElement(
            "", "", REQUEST_ELEMENT_NAME, attrIt, Collections.<Namespace>emptyList().iterator());
    try {
      eventWriter.add(tab);
      eventWriter.add(sElement);
      // Create End node
      EndElement eElement = eventFactory.createEndElement("", "", REQUEST_ELEMENT_NAME);
      eventWriter.add(eElement);
      eventWriter.add(end);
    } catch (XMLStreamException e) {
      throw new RuntimeException("ERROR IN WRITING XML: ", e);
    }
  }
  public XmlWriter(File output) throws FileNotFoundException, WriterException {
    this.xmlFile = output;
    System.out.println("setting up xml");
    if (output.exists()) {
      System.out.println("deleting existing file: " + output);
      output.delete();
    }

    try {
      FileOutputStream fos = new FileOutputStream(output);
      XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
      eventWriter = outputFactory.createXMLEventWriter(fos);

      eventFactory = XMLEventFactory.newInstance();

      end = eventFactory.createDTD("\n");

      // Create and write Start Tag
      StartDocument startDocument = eventFactory.createStartDocument();
      eventWriter.add(startDocument);

      StartElement configStartElement = eventFactory.createStartElement("", "", DOC_ELEMENT_NAME);
      eventWriter.add(configStartElement);
      eventWriter.add(end);
    } catch (XMLStreamException e) {
      throw new WriterException("unable to instantiate writer to file: " + output, e);
    }
  }
  public InputStream addAtomInlinecount(final InputStream feed, final int count) throws Exception {
    final XMLEventReader reader = getEventReader(feed);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLEventWriter writer = getEventWriter(bos);

    try {

      final XMLElement feedElement =
          extractElement(reader, writer, Collections.<String>singletonList("feed"), 0, 1, 1)
              .getValue();

      writer.add(feedElement.getStart());
      addAtomElement(
          IOUtils.toInputStream(String.format("<m:count>%d</m:count>", count), Constants.ENCODING),
          writer);
      writer.add(feedElement.getContentReader());
      writer.add(feedElement.getEnd());

      while (reader.hasNext()) {
        writer.add(reader.nextEvent());
      }

    } finally {
      writer.flush();
      writer.close();
      reader.close();
      IOUtils.closeQuietly(feed);
    }

    return new ByteArrayInputStream(bos.toByteArray());
  }
  private void addAtomElement(final InputStream content, final XMLEventWriter writer)
      throws Exception {
    final XMLEventReader reader = getEventReader(content);

    final XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent newLine = eventFactory.createSpace("\n");

    try {
      writer.add(newLine);

      while (reader.hasNext()) {
        final XMLEvent event = reader.nextEvent();

        if (event.getEventType() != XMLStreamConstants.START_DOCUMENT
            && event.getEventType() != XMLStreamConstants.END_DOCUMENT
            && event.getEventType() != XMLStreamConstants.COMMENT) {
          writer.add(event);
        }
      }
      writer.add(newLine);
    } finally {
      reader.close();
      IOUtils.closeQuietly(content);
    }
  }
  @Override
  public InputStream addEditLink(final InputStream content, final String title, final String href)
      throws Exception {

    final ByteArrayOutputStream copy = new ByteArrayOutputStream();
    IOUtils.copy(content, copy);
    IOUtils.closeQuietly(content);

    XMLEventReader reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    XMLEventWriter writer = getEventWriter(bos);

    final String editLinkElement =
        String.format("<link rel=\"edit\" title=\"%s\" href=\"%s\" />", title, href);

    try {
      // check edit link existence
      extractElement(
          reader,
          writer,
          Collections.<String>singletonList(Constants.get(ConstantKey.LINK)),
          Collections.<Map.Entry<String, String>>singletonList(
              new AbstractMap.SimpleEntry<String, String>("rel", "edit")),
          false,
          0,
          -1,
          -1);

      addAtomElement(IOUtils.toInputStream(editLinkElement, Constants.ENCODING), writer);
      writer.add(reader);

    } catch (Exception e) {
      reader.close();
      reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

      bos = new ByteArrayOutputStream();
      writer = getEventWriter(bos);

      final XMLElement entryElement =
          extractElement(reader, writer, Collections.<String>singletonList("entry"), 0, 1, 1)
              .getValue();

      writer.add(entryElement.getStart());

      addAtomElement(IOUtils.toInputStream(editLinkElement, Constants.ENCODING), writer);

      writer.add(entryElement.getContentReader());
      writer.add(entryElement.getEnd());

      writer.add(reader);

      writer.flush();
      writer.close();
    } finally {
      reader.close();
    }

    return new ByteArrayInputStream(bos.toByteArray());
  }
Exemple #6
0
  /**
   * Annotates a block of values of a heatmap.plus SVG file by giving them an id and row/column
   * attributes. A heatmap.plus can contain up to three 'blocks': row annotations, column
   * annotations and the matrix.
   *
   * @param nRow number of rows of this block
   * @param nCol number of columns of this block
   * @param blockId value of the id attribute to give elements in this block
   * @throws XMLStreamException
   */
  private void annotateHeatMapBlock(
      int nRow, int nCol, String blockId, XMLEventWriter writer, XMLEventReader reader)
      throws XMLStreamException {
    int counter = 0;
    int nPath = nRow * nCol;
    int currentRow = nRow; // elements drawn from bottom to top, so start counting at last row
    int currentCol = 1;
    while (counter < nPath) {
      XMLEvent event = (XMLEvent) reader.next();
      if (event.isStartElement() && event.asStartElement().getName().getLocalPart().equals(PATH)) {
        // make a new start element with the same attributes plus the extra annotations
        @SuppressWarnings("unchecked")
        Iterator<Attribute> attributes = event.asStartElement().getAttributes();

        StartElement newSe = eventFactory.createStartElement(new QName(PATH), attributes, null);
        writer.add(newSe);
        writer.add(eventFactory.createAttribute(ID, blockId));
        writer.add(eventFactory.createAttribute(new QName("row"), Integer.toString(currentRow)));
        writer.add(eventFactory.createAttribute(new QName("col"), Integer.toString(currentCol)));

        currentRow--;
        if (currentRow == 0) {
          // finished one column, reset currentRow and increment currentCol
          currentRow = nRow;
          currentCol++;
        }
        counter++;
      } else {
        // write the rest untouched
        writer.add(event);
      }
    }
  }
  @Override
  public InputStream deleteProperty(final InputStream src, final List<String> path)
      throws Exception {
    final XMLEventReader reader = getEventReader(src);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLEventWriter writer = getEventWriter(bos);

    final XMLEventReader changesReader =
        new XMLEventReaderWrapper(
            IOUtils.toInputStream(
                String.format("<%s m:null=\"true\" />", path.get(path.size() - 1)),
                Constants.ENCODING));

    writer.add(changesReader);
    changesReader.close();

    writer.add(reader);

    reader.close();
    IOUtils.closeQuietly(src);

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

    return new ByteArrayInputStream(bos.toByteArray());
  }
  /**
   * Creates the node.
   *
   * @param eventWriter the event writer
   * @param name the name
   * @param d the d
   * @param string2 the string2
   * @param string3 the string3
   * @throws XMLStreamException the xML stream exception
   */
  private void createNode(
      final XMLEventWriter eventWriter,
      final String name,
      final HashMap<String, String> d,
      final String string2,
      final String string3)
      throws XMLStreamException {

    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent end = eventFactory.createCharacters("\n");
    XMLEvent tab = eventFactory.createCharacters("\t");
    // Create Start node
    StartElement sElement = eventFactory.createStartElement(string2, string3, name);
    eventWriter.add(tab);
    eventWriter.add(sElement);
    // FIXME nullpointer abfangen!!1
    eventWriter.add(end);

    for (String str : d.keySet()) {
      createNode(eventWriter, "docPart", d.get(str), str, PREFIX, URI);
    }
    if (d.isEmpty()) {
      createNode(eventWriter, "docPart", "", "de", PREFIX, URI);
    }
    eventWriter.add(eventFactory.createEndElement(string2, string3, name));
    eventWriter.add(end);
  }
 private void putValue(RelationalProfile.Column column, ResultSet resultSet, int indent)
     throws XMLStreamException, SQLException {
   String value = getValue(column, resultSet);
   if (value == null) return;
   while (indent-- > 0) out.add(event.createCharacters("   "));
   out.add(event.createStartElement("", "", column.name, null, null));
   out.add(event.createCharacters(value));
   out.add(event.createEndElement("", "", column.name));
   out.add(event.createCharacters("\n"));
 }
  @Override
  public void close() throws WriterException {

    try {
      eventWriter.add(eventFactory.createEndElement("", "", DOC_ELEMENT_NAME));
      eventWriter.add(end);
      eventWriter.add(eventFactory.createEndDocument());
      eventWriter.close();
    } catch (XMLStreamException e) {
      throw new WriterException("unable to close stream for file: " + xmlFile, e);
    }
  }
  /**
   * Write a new element with the specified name and text
   *
   * @return the end element
   */
  private XMLEvent getAddedEvent(
      XMLEvent event, XMLEventWriter writer, String elementName, String text)
      throws XMLStreamException {
    StartElement oldStartEvent = event.asStartElement();
    StartElement newStartEvent =
        xmlEventFactory.createStartElement(
            new QName(elementName), null, oldStartEvent.getNamespaces());

    writer.add(newStartEvent);
    writer.add(xmlEventFactory.createCharacters(text));
    return xmlEventFactory.createEndElement(newStartEvent.getName(), newStartEvent.getNamespaces());
  }
  public static String xmlToJson(String xml, boolean formatted) throws XMLStreamException {
    InputStream input = new ByteArrayInputStream(xml.getBytes());
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    JsonXMLConfig config =
        new JsonXMLConfigBuilder()
            .autoArray(true)
            .autoPrimitive(true)
            .prettyPrint(formatted)
            .build();

    try {
      XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(input);
      XMLEventWriter writer = new JsonXMLOutputFactory(config).createXMLEventWriter(output);
      writer.add(reader);
      reader.close();
      writer.close();
      try {
        return output.toString("UTF-8");
      } catch (UnsupportedEncodingException e) {
        throw new XMLStreamException(e.getMessage());
      }
    } finally {
      // dp nothing
    }
  }
  @Override
  public Scenario parse(InputStream inputStream)
      throws IOException, SAXException, ParserConfigurationException {

    OutputStream output = new ByteArrayOutputStream();
    JsonXMLConfig config = new JsonXMLConfigBuilder().autoArray(true).prettyPrint(false).build();

    try {

      /* Create source (XML). */
      XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(inputStream);
      // XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
      // Source source = new StAXSource(reader);

      /* Create result (JSON). */
      XMLEventWriter writer = new JsonXMLOutputFactory(config).createXMLEventWriter(output);
      // XMLStreamWriter writer = new JsonXMLOutputFactory(config).createXMLStreamWriter(output);
      // Result result = new StAXResult(writer);

      /*
       * Copy events from reader to writer.
       */
      writer.add(reader);

      /* Copy source to result via "identity transform". */
      // TransformerFactory.newInstance().newTransformer().transform(source, result);
    } catch (XMLStreamException e) {
      e.printStackTrace();
    } finally {

      /* As per StAX specification, XMLStreamReader/Writer.close()
      doesn't close
      the underlying stream. */
      output.close();
      inputStream.close();
    }

    /*
    try {
        json = xmlToJson(inputStream);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    String jsonString = json.toString();

    System.out.println(jsonString);

    GenericDocument genericDocument = new GenericDocument();
    genericDocument.setJson(jsonString);
    */

    GenericDocument genericDocument = new GenericDocument();
    String json = output.toString();

    genericDocument.setJson(json);

    return genericDocument;
  }
  /**
   * Creates the node.
   *
   * @param eventWriter the event writer
   * @param name the name
   * @param value the value
   * @param lang the lang
   * @param string2 the string2
   * @param string3 the string3
   * @throws XMLStreamException the xML stream exception
   */
  private void createNode(
      final XMLEventWriter eventWriter,
      final String name,
      final String value,
      final String lang,
      final String string2,
      final String string3)
      throws XMLStreamException {
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent end = eventFactory.createCharacters("\n");
    XMLEvent tab = eventFactory.createCharacters("\t");
    // Create Start node
    StartElement sElement = eventFactory.createStartElement(string2, string3, name);
    eventWriter.add(tab);
    eventWriter.add(sElement);
    eventWriter.add(eventFactory.createAttribute("xml:lang", lang));
    eventWriter.add(end);

    if (value.trim().length() > 0) {
      Characters characters = eventFactory.createCharacters(value.trim());
      eventWriter.add(characters);
    }
    eventWriter.add(eventFactory.createEndElement(string2, string3, name));
    eventWriter.add(end);
  }
 private void writeEvent(final XMLEvent event, final XMLEventWriter writer) {
   if (writer != null) {
     try {
       writer.add(event);
     } catch (XMLStreamException e) {
       LOG.error("Error writing event {}", event, e);
     }
   }
 }
 private void addMessageIdElement(XMLEventWriter writer, String id, StartElement startElement)
     throws XMLStreamException {
   writer.add(
       eventFactory.createStartElement(
           "",
           startElement.getName().getNamespaceURI(),
           startElement.getName().getLocalPart(),
           startElement.getAttributes(),
           startElement.getNamespaces(),
           startElement.getNamespaceContext()));
   writer.add(eventFactory.createCharacters(id));
   writer.add(
       eventFactory.createEndElement(
           "",
           startElement.getName().getNamespaceURI(),
           startElement.getName().getLocalPart(),
           startElement.getNamespaces()));
 }
 private void addRewrittenAddressElement(
     XMLEventWriter writer, String address, int port, StartElement startElement)
     throws XMLStreamException {
   writer.add(
       eventFactory.createStartElement(
           "",
           startElement.getName().getNamespaceURI(),
           startElement.getName().getLocalPart(),
           startElement.getAttributes(),
           startElement.getNamespaces(),
           startElement.getNamespaceContext()));
   writer.add(eventFactory.createCharacters(address.replaceFirst(":\\d+/", ":" + port + "/")));
   writer.add(
       eventFactory.createEndElement(
           "",
           startElement.getName().getNamespaceURI(),
           startElement.getName().getLocalPart(),
           startElement.getNamespaces()));
 }
 /* (non-Javadoc)
  * @see org.springframework.batch.item.xml.StaxWriterCallback#write(javax.xml.stream.XMLEventWriter)
  */
 @Override
 public void write(XMLEventWriter writer) throws IOException {
   XMLEventFactory factory = XMLEventFactory.newInstance();
   try {
     writer.add(
         factory.createComment(
             "Total write count = " + stepExecution.getWriteCount() + ";credit 201310 end."));
   } catch (XMLStreamException e) {
     e.printStackTrace();
   }
 }
  private void copyEvents(int length) throws IOException {
    try {
      while (reader.hasNext() && stream.getInputStream().available() < length) {
        writer.add(reader.nextEvent());
      }

      writer.flush();
    } catch (XMLStreamException e) {
      throw new be.re.io.IOException(e);
    }
  }
  public void rewriteEndpoint(Reader reader, Writer writer, int port, Exchange exc)
      throws XMLStreamException {
    XMLEventReader parser = inputFactory.createXMLEventReader(reader);
    XMLEventWriter eventWriter = XMLOutputFactory.newInstance().createXMLEventWriter(writer);

    String id = null;
    String url = null;

    skip:
    while (parser.hasNext()) {
      XMLEvent e = parser.nextEvent();

      if (e.isStartElement()) {
        if (isReplyTo(e.asStartElement())) {
          while (e.isStartElement() || !isReplyTo(e.asEndElement())) {
            if (e.isStartElement() && isAddress(e.asStartElement())) {
              url = parser.getElementText();
              addRewrittenAddressElement(eventWriter, url, port, e.asStartElement());

              continue skip;
            }

            eventWriter.add(e);
            e = parser.nextTag();
          }
        }

        if (isMessageId(e.asStartElement())) {
          id = parser.getElementText();
          exc.setProperty("messageId", id);
          addMessageIdElement(eventWriter, id, e.asStartElement());

          continue skip;
        }
      }

      eventWriter.add(e);
    }

    registry.register(id, url);
  }
Exemple #21
0
  private void writeContours(XMLEventWriter writer, XMLEvent indent, TDRStructure structure) {

    XMLEventFactory efac = XMLEventFactory.newInstance();

    Collection<XMLEvent> attrContour = new ArrayList<XMLEvent>();
    XMLEvent startContour;
    XMLEvent endContour = efac.createEndElement("", "", "contour");

    Vector<TDRContour> contours = structure.getContours();
    Iterator<TDRContour> it = contours.iterator();

    try {

      while (it.hasNext()) {
        TDRContour contour = it.next();
        String section = String.valueOf(contour.getSection().getNumber());
        String startpoint = contour.get_startpoint_x() + "," + contour.get_startpoint_y();
        String offset = String.valueOf(contour.get_offset());
        String numpoints = String.valueOf(contour.get_numpoints());

        /* prepare contour's attributes */
        attrContour.clear(); /*clear existing attributes*/
        attrContour.add(efac.createAttribute("section", section));
        attrContour.add(efac.createAttribute("startpoint", startpoint));
        attrContour.add(efac.createAttribute("offset", offset));
        attrContour.add(efac.createAttribute("numpoints", numpoints));
        startContour = efac.createStartElement("", "", "contour", attrContour.iterator(), null);

        /*<contour>*/
        writer.add(indent);
        writer.add(startContour);
        writer.add(endContour);
        writer.add(newLine);
      }

    } catch (XMLStreamException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  /** {@inheritDoc } */
  @Override
  protected InputStream addLinks(
      final String entitySetName,
      final String entitykey,
      final InputStream is,
      final Set<String> links)
      throws Exception {

    // -----------------------------------------
    // 0. Build reader and writer
    // -----------------------------------------
    final XMLEventReader reader = getEventReader(is);
    final XMLEventFactory eventFactory = XMLEventFactory.newInstance();

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLEventWriter writer = getEventWriter(bos);
    // -----------------------------------------
    final Map.Entry<Integer, XMLElement> entry =
        extractElement(reader, writer, Collections.singletonList("entry"), 0, 1, 1);

    writer.add(entry.getValue().getStart());

    final Map<String, NavigationProperty> navigationProperties =
        metadata.getNavigationProperties(entitySetName);

    // add for links
    for (String link : links) {
      final Set<Attribute> attributes = new HashSet<Attribute>();
      attributes.add(eventFactory.createAttribute(new QName("title"), link));
      attributes.add(
          eventFactory.createAttribute(
              new QName("href"), Commons.getLinksURI(entitySetName, entitykey, link)));
      attributes.add(
          eventFactory.createAttribute(
              new QName("rel"), Constants.get(ConstantKey.ATOM_LINK_REL) + link));
      attributes.add(
          eventFactory.createAttribute(
              new QName("type"),
              navigationProperties.get(link).isEntitySet()
                  ? Constants.get(ConstantKey.ATOM_LINK_FEED)
                  : Constants.get(ConstantKey.ATOM_LINK_ENTRY)));

      writer.add(
          eventFactory.createStartElement(
              new QName(Constants.get(ConstantKey.LINK)), attributes.iterator(), null));
      writer.add(eventFactory.createEndElement(new QName(Constants.get(ConstantKey.LINK)), null));
    }

    writer.add(entry.getValue().getContentReader());
    writer.add(entry.getValue().getEnd());
    writer.add(reader);
    IOUtils.closeQuietly(is);

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

    return new ByteArrayInputStream(bos.toByteArray());
  }
  @Override
  public InputStream replaceProperty(
      final InputStream src,
      final InputStream replacement,
      final List<String> path,
      final boolean justValue)
      throws Exception {

    final List<String> pathElements = new ArrayList<String>();

    for (String element : path) {
      pathElements.add(Constants.get(ConstantKey.ATOM_PROPERTY_PREFIX) + element);
    }

    final XMLEventReader reader = getEventReader(src);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLEventWriter writer = getEventWriter(bos);

    final Map.Entry<Integer, XMLElement> element =
        extractElement(reader, writer, pathElements, 0, 3, 4);

    if (justValue) {
      writer.add(element.getValue().getStart());
    }

    final XMLEventReader changesReader = new XMLEventReaderWrapper(replacement);

    while (changesReader.hasNext()) {
      final XMLEvent event = changesReader.nextEvent();
      if (event.isStartElement()
          && event.asStartElement().getName().equals(element.getValue().getStart().getName())) {
        writer.add(element.getValue().getStart());
        writer.add(changesReader);
      } else {
        writer.add(event);
      }
    }

    changesReader.close();
    IOUtils.closeQuietly(replacement);

    if (justValue) {
      writer.add(element.getValue().getEnd());
    }

    writer.add(reader);

    reader.close();
    IOUtils.closeQuietly(src);

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

    return new ByteArrayInputStream(bos.toByteArray());
  }
  @Override
  protected InputStream replaceLink(
      final InputStream toBeChanged, final String linkName, final InputStream replacement)
      throws Exception {
    final XMLEventReader reader = getEventReader(toBeChanged);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLEventWriter writer = getEventWriter(bos);

    final XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent newLine = eventFactory.createSpace("\n");

    try {
      final XMLElement linkElement =
          extractElement(
                  reader,
                  writer,
                  Collections.<String>singletonList(Constants.get(ConstantKey.LINK)),
                  Collections.<Map.Entry<String, String>>singletonList(
                      new SimpleEntry<String, String>("title", linkName)),
                  false,
                  0,
                  -1,
                  -1)
              .getValue();
      writer.add(linkElement.getStart());

      // ------------------------------------------
      // write inline ...
      // ------------------------------------------
      writer.add(newLine);
      writer.add(eventFactory.createStartElement("m", null, "inline"));

      addAtomElement(replacement, writer);

      writer.add(eventFactory.createEndElement("m", null, "inline"));
      writer.add(newLine);
      // ------------------------------------------

      writer.add(linkElement.getEnd());

      writer.add(reader);
      writer.flush();
      writer.close();
    } finally {
      reader.close();
      IOUtils.closeQuietly(toBeChanged);
    }

    return new ByteArrayInputStream(bos.toByteArray());
  }
  @Test
  public void testMailWithNamespace() throws FileNotFoundException, XMLStreamException {
    final String XMLNS = "http://fh-joanneum.at";

    XMLEventWriter writer = factory.createXMLEventWriter(System.out);
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();

    writer.add(eventFactory.createStartDocument("UTF-8", "1.0", true));

    writer.add(eventFactory.createStartElement("", XMLNS, "mail"));
    writer.add(eventFactory.createNamespace(XMLNS));
    writer.add(eventFactory.createAttribute("from", "*****@*****.**"));

    writer.add(eventFactory.createStartElement("", XMLNS, "to"));
    writer.add(eventFactory.createCharacters("*****@*****.**"));
    writer.add(eventFactory.createEndElement("", XMLNS, "to"));

    // ...

    writer.add(eventFactory.createEndElement("", XMLNS, "mail"));

    writer.add(eventFactory.createEndDocument());
    writer.flush();
  }
  /**
   * Write a new element with the specified name and attribute before the end element is written out
   *
   * @return the end element
   */
  private XMLEvent getAddedEventBeforeEndElement(
      XMLEvent event,
      XMLEventWriter writer,
      String elementName,
      String attributeName,
      String attributeValue)
      throws XMLStreamException {
    Attribute newAttribute = xmlEventFactory.createAttribute(attributeName, attributeValue);
    Set attributes = new HashSet();
    attributes.add(newAttribute);

    EndElement oldEvent = event.asEndElement();
    StartElement newStartEvent =
        xmlEventFactory.createStartElement(
            new QName(elementName), attributes.iterator(), oldEvent.getNamespaces());

    writer.add(newStartEvent);
    return xmlEventFactory.createEndElement(newStartEvent.getName(), newStartEvent.getNamespaces());
  }
  private void read(Source source) throws IOException, XMLStreamException {

    // Read in XML, extracting and removing the updates list in the process
    StringWriter buffer = new StringWriter(BUFFER_SIZE);
    XMLEventWriter eventWriter = this.xmlOutputFactory.createXMLEventWriter(buffer);
    XMLEventReader eventReader = this.xmlInputFactory.createXMLEventReader(source);
    UpdatesXMLEventReader updatesReader = new UpdatesXMLEventReader(eventReader);
    eventWriter.add(updatesReader);
    eventWriter.close();
    eventReader.close();

    // Was the update list found?
    List<String> updateNames = updatesReader.getUpdates();
    if (updateNames == null)
      throw new PersistentObjectException("XML file does not contain an updates list");

    // Save current content (without updates) and updates list
    this.current = buffer.toString();
    this.updates.clear();
    this.updates.addAll(updateNames);
  }
  public void testEncodingXmlEventReader() throws Exception {
    TEST_XML_WITH_XML_HEADER_ISO_8859_1_AS_BYTE_ARRAY_STREAM.reset();
    XMLEventReader reader = null;
    XMLEventWriter writer = null;
    ByteArrayOutputStream output = null;
    try {
      // enter text encoded with Latin1
      reader =
          context
              .getTypeConverter()
              .mandatoryConvertTo(
                  XMLEventReader.class, TEST_XML_WITH_XML_HEADER_ISO_8859_1_AS_BYTE_ARRAY_STREAM);

      output = new ByteArrayOutputStream();
      // ensure UTF-8 encoding
      Exchange exchange = new DefaultExchange(context);
      exchange.setProperty(Exchange.CHARSET_NAME, UTF_8.name());
      writer =
          context.getTypeConverter().mandatoryConvertTo(XMLEventWriter.class, exchange, output);
      while (reader.hasNext()) {
        writer.add(reader.nextEvent());
      }
    } finally {
      if (reader != null) {
        reader.close();
      }
      if (writer != null) {
        writer.close();
      }
    }
    assertNotNull(output);

    String result = new String(output.toByteArray(), UTF_8.name());

    boolean equals =
        TEST_XML_WITH_XML_HEADER.equals(result)
            || TEST_XML_WITH_XML_HEADER_ISO_8859_1.equals(result);
    assertTrue("Should match header", equals);
  }
  /**
   * Creates the node.
   *
   * @param eventWriter the event writer
   * @param name the name
   * @param textNode the text node
   * @param prefix the prefix
   * @param namespace the namespace
   * @throws XMLStreamException the xML stream exception
   */
  private void createNode(
      final XMLEventWriter eventWriter,
      final String name,
      final String textNode,
      final String prefix,
      final String namespace)
      throws XMLStreamException {
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent end = eventFactory.createCharacters("\n");
    XMLEvent tab = eventFactory.createCharacters("\t");
    // Create Start node
    StartElement sElement = eventFactory.createStartElement(PREFIX, URI, name);
    eventWriter.add(tab);
    eventWriter.add(sElement);
    eventWriter.add(end);

    if (textNode.trim().length() > 0) {
      Characters characters = eventFactory.createCharacters(textNode.trim());
      eventWriter.add(characters);
    }
    eventWriter.add(eventFactory.createEndElement(PREFIX, URI, name));
    eventWriter.add(end);
  }
 private void endDocument() throws XMLStreamException {
   out.add(event.createEndElement("", "", DUMP_ENVELOP_TAG));
   out.add(event.createCharacters("\n"));
   out.add(event.createEndDocument());
 }