Пример #1
0
  public Layer<T> transform(final Layer<T> source) throws IOException, XMLStreamException {
    this.source = source;
    this.target = configuration.start(source);

    try {
      source.stream(
          new Text.Consumer() {
            @Override
            public void consume(Reader sourceReader) throws IOException {
              XMLStreamReader xmlStream = null;
              try {
                xmlStream = xmlInputFactory.createXMLStreamReader(sourceReader);

                final Stack<XMLEntity> entities = new Stack<XMLEntity>();
                start();
                while (xmlStream.hasNext()) {
                  final int event = xmlStream.next();
                  mapOffsetDelta(0, xmlStream.getLocation().getCharacterOffset() - sourceOffset);

                  switch (event) {
                    case XMLStreamConstants.START_ELEMENT:
                      endText();
                      nextSibling();
                      start(entities.push(XMLEntity.newElement(xmlStream)));
                      break;
                    case XMLStreamConstants.END_ELEMENT:
                      endText();
                      end(entities.pop());
                      break;
                    case XMLStreamConstants.COMMENT:
                      endText();
                      nextSibling();
                      emptyEntity(XMLEntity.newComment(xmlStream));
                      break;
                    case XMLStreamConstants.PROCESSING_INSTRUCTION:
                      endText();
                      nextSibling();
                      emptyEntity(XMLEntity.newPI(xmlStream));
                      break;
                    case XMLStreamConstants.CHARACTERS:
                    case XMLStreamConstants.ENTITY_REFERENCE:
                    case XMLStreamConstants.CDATA:
                      newText(xmlStream.getText());
                      break;
                  }
                }
                end();
              } catch (XMLStreamException e) {
                throw Throwables.propagate(e);
              } finally {
                XML.closeQuietly(xmlStream);
              }
            }
          });
      Reader textReader = null;
      try {
        configuration.end(target, textReader = read());
        return target;
      } finally {
        Closeables.close(textReader, false);
      }
    } catch (Throwable t) {
      Throwables.propagateIfInstanceOf(t, IOException.class);
      Throwables.propagateIfInstanceOf(Throwables.getRootCause(t), XMLStreamException.class);
      throw Throwables.propagate(t);
    }
  }