Java Code Examples for javax.xml.stream.events.XMLEvent#isEndDocument()

The following examples show how to use javax.xml.stream.events.XMLEvent#isEndDocument() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WstxEventReader.java    From woodstox with Apache License 2.0 6 votes vote down vote up
@Override
public XMLEvent nextEvent() throws XMLStreamException
{
    if (mState == STATE_END_OF_INPUT) {
        throwEndOfInput();
    } else if (mState == STATE_INITIAL) {
        mState = STATE_CONTENT;
        return createStartDocumentEvent();
    }
    if (mPeekedEvent != null) {
        XMLEvent evt = mPeekedEvent;
        mPeekedEvent = null;
        if (evt.isEndDocument()) {
            updateStateEndDocument();
        }
        return evt;
    }
    return createNextEvent(true, mReader.next());
}
 
Example 2
Source File: StreamReader.java    From simplexml with Apache License 2.0 6 votes vote down vote up
/**
 * This is used to read the next node from the document. This will
 * scan through the document, ignoring any comments to find the
 * next relevant XML event to acquire. Typically events will be
 * the start and end of an element, as well as any text nodes.
 * 
 * @return this returns the next event taken from the document 
 */
private EventNode read() throws Exception {
   XMLEvent event = reader.nextEvent();
   
   if(!event.isEndDocument()) {
      if(event.isStartElement()) {
         return start(event);
      } 
      if(event.isCharacters()) {
         return text(event);
      } 
      if(event.isEndElement()) {
         return end();
      }
      return read();
   }
   return null;
}
 
Example 3
Source File: AbstractStaxOperation.java    From butterfly with MIT License 6 votes vote down vote up
private XMLEvent consumeUntil(XMLEventReader reader, XMLEventWriter writer, EventCondition condition) throws XMLStreamException {
    XMLEvent xmlEvent = null;

    while (reader.hasNext() && xmlEvent == null) {
        XMLEvent event = (XMLEvent)reader.next();
        if (event.isEndDocument()) {
            break;
        }
        if (condition.evaluateEvent(event)) {
            xmlEvent = event;
        } else {
            if (writer != null) {
                writer.add(event);
            }
        }
    }

    return xmlEvent;
}
 
Example 4
Source File: XmlEventDecoder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public List<? extends XMLEvent> apply(DataBuffer dataBuffer) {
	try {
		this.streamReader.getInputFeeder().feedInput(dataBuffer.asByteBuffer());
		List<XMLEvent> events = new ArrayList<>();
		while (true) {
			if (this.streamReader.next() == AsyncXMLStreamReader.EVENT_INCOMPLETE) {
				// no more events with what currently has been fed to the reader
				break;
			}
			else {
				XMLEvent event = this.eventAllocator.allocate(this.streamReader);
				events.add(event);
				if (event.isEndDocument()) {
					break;
				}
			}
		}
		return events;
	}
	catch (XMLStreamException ex) {
		throw Exceptions.propagate(ex);
	}
	finally {
		DataBufferUtils.release(dataBuffer);
	}
}
 
Example 5
Source File: SkipRootElementXMLEventReader.java    From exificient with MIT License 5 votes vote down vote up
public SkipRootElementXMLEventReader(XMLEventReader parent)
		throws XMLStreamException {
	events = new ArrayList<XMLEvent>();
	int openElement = 0;

	while (parent.hasNext()) {
		XMLEvent next = parent.nextEvent();

		if (next.isStartDocument()) {
			events.add(next);
		} else if (next.isEndDocument()) {
			events.add(next);
		} else if (next.isStartElement()) {
			if (openElement > 0) {
				events.add(next);
			}
			openElement++;
		} else if (next.isEndElement()) {
			openElement--;
			if (openElement > 0) {
				events.add(next);
			}
		} else {
			if (openElement > 0) {
				events.add(next);
			}
		}

	}

}
 
Example 6
Source File: LambdaConfigurationStaxUnmarshaller.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public Entry<String, NotificationConfiguration> unmarshall(StaxUnmarshallerContext context) throws Exception {
    int originalDepth = context.getCurrentDepth();
    int targetDepth = originalDepth + 1;

    if (context.isStartOfDocument()) {
        targetDepth += 1;
    }

    String id = null;
    List<String> events = new ArrayList<String>();
    Filter filter = null;
    String functionArn = null;
    String invocationRole = null;

    while (true) {
        XMLEvent xmlEvent = context.nextEvent();
        if (xmlEvent.isEndDocument()) {
            return createLambdaConfig(id, events, functionArn, invocationRole, filter);
        }

        if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
            if (context.testExpression("Id", targetDepth)) {
                id = StringStaxUnmarshaller.getInstance().unmarshall(context);
            } else if (context.testExpression("Event", targetDepth)) {
                events.add(StringStaxUnmarshaller.getInstance().unmarshall(context));
            } else if (context.testExpression("Filter", targetDepth)) {
                filter = FilterStaxUnmarshaller.getInstance().unmarshall(context);
            } else if (context.testExpression("CloudFunction", targetDepth)) {
                functionArn = StringStaxUnmarshaller.getInstance().unmarshall(context);
            } else if (context.testExpression("InvocationRole", targetDepth)) {
                invocationRole = StringStaxUnmarshaller.getInstance().unmarshall(context);
            }
        } else if (xmlEvent.isEndElement()) {
            if (context.getCurrentDepth() < originalDepth) {
                return createLambdaConfig(id, events, functionArn, invocationRole, filter);
            }
        }
    }
}
 
Example 7
Source File: FilterRuleStaxUnmarshaller.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public FilterRule unmarshall(StaxUnmarshallerContext context) throws Exception {
    int originalDepth = context.getCurrentDepth();
    int targetDepth = originalDepth + 1;

    if (context.isStartOfDocument()) {
        targetDepth += 1;
    }

    FilterRule filter = new FilterRule();

    while (true) {
        XMLEvent xmlEvent = context.nextEvent();
        if (xmlEvent.isEndDocument()) {
            return filter;
        }
        if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
            if (context.testExpression("Name", targetDepth)) {
                filter.setName(StringStaxUnmarshaller.getInstance().unmarshall(context));
            } else if (context.testExpression("Value", targetDepth)) {
                filter.setValue(StringStaxUnmarshaller.getInstance().unmarshall(context));
            }
        } else if (xmlEvent.isEndElement()) {
            if (context.getCurrentDepth() < originalDepth) {
                return filter;
            }
        }
    }

}
 
Example 8
Source File: S3KeyFilterStaxUnmarshaller.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public S3KeyFilter unmarshall(StaxUnmarshallerContext context) throws Exception {
    int originalDepth = context.getCurrentDepth();
    int targetDepth = originalDepth + 1;

    if (context.isStartOfDocument()) {
        targetDepth += 1;
    }

    S3KeyFilter filter = new S3KeyFilter();

    while (true) {
        XMLEvent xmlEvent = context.nextEvent();
        if (xmlEvent.isEndDocument()) {
            return filter;
        }

        if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
            if (context.testExpression("FilterRule", targetDepth)) {
                filter.addFilterRule(FilterRuleStaxUnmarshaller.getInstance().unmarshall(context));
            }
        } else if (xmlEvent.isEndElement()) {
            if (context.getCurrentDepth() < originalDepth) {
                return filter;
            }
        }
    }
}
 
Example 9
Source File: NotificationConfigurationStaxUnmarshaller.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Id (aka configuration name) isn't modeled on the actual {@link NotificationConfiguration}
 * class but as the key name in the map of configurations in
 * {@link BucketNotificationConfiguration}
 */
@Override
public Entry<String, NotificationConfiguration> unmarshall(StaxUnmarshallerContext context) throws Exception {
    int originalDepth = context.getCurrentDepth();
    int targetDepth = originalDepth + 1;

    if (context.isStartOfDocument()) {
        targetDepth += 1;
    }

    T topicConfig = createConfiguration();
    String id = null;

    while (true) {
        XMLEvent xmlEvent = context.nextEvent();
        if (xmlEvent.isEndDocument()) {
            return new SimpleEntry<String, NotificationConfiguration>(id, topicConfig);
        }

        if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
            if (handleXmlEvent(topicConfig, context, targetDepth)) {
                // Do nothing, subclass has handled it
            } else if (context.testExpression("Id", targetDepth)) {
                id = StringStaxUnmarshaller.getInstance().unmarshall(context);
            } else if (context.testExpression("Event", targetDepth)) {
                topicConfig.addEvent(StringStaxUnmarshaller.getInstance().unmarshall(context));
            } else if (context.testExpression("Filter", targetDepth)) {
                topicConfig.setFilter(FilterStaxUnmarshaller.getInstance().unmarshall(context));
            }
        } else if (xmlEvent.isEndElement()) {
            if (context.getCurrentDepth() < originalDepth) {
                return new SimpleEntry<String, NotificationConfiguration>(id, topicConfig);
            }
        }
    }
}
 
Example 10
Source File: XmlEventDecoder.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Publisher<? extends XMLEvent> apply(DataBuffer dataBuffer) {
	try {
		this.streamReader.getInputFeeder().feedInput(dataBuffer.asByteBuffer());
		List<XMLEvent> events = new ArrayList<>();
		while (true) {
			if (this.streamReader.next() == AsyncXMLStreamReader.EVENT_INCOMPLETE) {
				// no more events with what currently has been fed to the reader
				break;
			}
			else {
				XMLEvent event = this.eventAllocator.allocate(this.streamReader);
				events.add(event);
				if (event.isEndDocument()) {
					break;
				}
			}
		}
		return Flux.fromIterable(events);
	}
	catch (XMLStreamException ex) {
		return Mono.error(ex);
	}
	finally {
		DataBufferUtils.release(dataBuffer);
	}
}
 
Example 11
Source File: BaseXMLEventReader.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public final String getElementText() throws XMLStreamException {
	XMLEvent event = this.previousEvent;
	if (event == null) {
		throw new XMLStreamException("Must be on START_ELEMENT to read next text, element was null");
	}
	if (!event.isStartElement()) {
		throw new XMLStreamException("Must be on START_ELEMENT to read next text", event.getLocation());
	}

	final StringBuilder text = new StringBuilder();
	while (!event.isEndDocument()) {
		switch (event.getEventType()) {
			case XMLStreamConstants.CHARACTERS:
			case XMLStreamConstants.SPACE:
			case XMLStreamConstants.CDATA: {
				final Characters characters = event.asCharacters();
				text.append(characters.getData());
				break;
			}
			case XMLStreamConstants.ENTITY_REFERENCE: {
				final EntityReference entityReference = (EntityReference)event;
				final EntityDeclaration declaration = entityReference.getDeclaration();
				text.append(declaration.getReplacementText());
				break;
			}
			case XMLStreamConstants.COMMENT:
			case XMLStreamConstants.PROCESSING_INSTRUCTION: {
				//Ignore
				break;
			}
			default: {
				throw new XMLStreamException("Unexpected event type '" + XMLStreamConstantsUtils.getEventName(event.getEventType()) + "' encountered. Found event: " + event, event.getLocation());
			}
		}

		event = this.nextEvent();
	}

	return text.toString();
}
 
Example 12
Source File: BaseXMLEventReader.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public final String getElementText() throws XMLStreamException {
	XMLEvent event = this.previousEvent;
	if (event == null) {
		throw new XMLStreamException("Must be on START_ELEMENT to read next text, element was null");
	}
	if (!event.isStartElement()) {
		throw new XMLStreamException("Must be on START_ELEMENT to read next text", event.getLocation());
	}

	final StringBuilder text = new StringBuilder();
	while (!event.isEndDocument()) {
		switch (event.getEventType()) {
			case XMLStreamConstants.CHARACTERS:
			case XMLStreamConstants.SPACE:
			case XMLStreamConstants.CDATA: {
				final Characters characters = event.asCharacters();
				text.append(characters.getData());
				break;
			}
			case XMLStreamConstants.ENTITY_REFERENCE: {
				final EntityReference entityReference = (EntityReference)event;
				final EntityDeclaration declaration = entityReference.getDeclaration();
				text.append(declaration.getReplacementText());
				break;
			}
			case XMLStreamConstants.COMMENT:
			case XMLStreamConstants.PROCESSING_INSTRUCTION: {
				//Ignore
				break;
			}
			default: {
				throw new XMLStreamException("Unexpected event type '" + XMLStreamConstantsUtils.getEventName(event.getEventType()) + "' encountered. Found event: " + event, event.getLocation());
			}
		}

		event = this.nextEvent();
	}

	return text.toString();
}
 
Example 13
Source File: XmlRecordSource.java    From nifi with Apache License 2.0 4 votes vote down vote up
private XmlNode readNext(final StartElement startElement) throws XMLStreamException, IOException {
    // Parse everything until we encounter the end element
    final StringBuilder content = new StringBuilder();
    final Map<String, XmlNode> childNodes = new LinkedHashMap<>();

    while (xmlEventReader.hasNext()) {
        final XMLEvent xmlEvent = xmlEventReader.nextEvent();

        if (xmlEvent.isEndDocument()) {
            throw new EOFException("Expected to encounter End-of-Element tag for start tag '" + startElement.getName() + "'");
        }

        if (xmlEvent.isEndElement()) {
            break;
        }

        if (xmlEvent.isCharacters()) {
            final Characters characters = xmlEvent.asCharacters();
            if (!characters.isWhiteSpace()) {
                content.append(characters.getData());
            }
        }

        if (xmlEvent.isStartElement()) {
            final StartElement childStartElement = xmlEvent.asStartElement();
            final XmlNode childNode = readNext(childStartElement);
            final String childName = childStartElement.getName().getLocalPart();

            final XmlNode existingNode = childNodes.get(childName);
            if (existingNode == null) {
                childNodes.put(childName, childNode);
            } else if (existingNode.getNodeType() == XmlNodeType.ARRAY) {
                ((XmlArrayNode) existingNode).addElement(childNode);
            } else {
                final XmlArrayNode arrayNode = new XmlArrayNode(childStartElement.getName().getLocalPart());
                arrayNode.addElement(existingNode);
                arrayNode.addElement(childNode);
                childNodes.put(childName, arrayNode);
            }
        }
    }

    final String nodeName = startElement.getName().getLocalPart();
    if (childNodes.isEmpty()) {
        return new XmlTextNode(nodeName, content.toString().trim());
    } else {
        return new XmlContainerNode(nodeName, childNodes);
    }
}
 
Example 14
Source File: StaxEventXMLReader.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected void parseInternal() throws SAXException, XMLStreamException {
	boolean documentStarted = false;
	boolean documentEnded = false;
	int elementDepth = 0;
	while (this.reader.hasNext() && elementDepth >= 0) {
		XMLEvent event = this.reader.nextEvent();
		if (!event.isStartDocument() && !event.isEndDocument() && !documentStarted) {
			handleStartDocument(event);
			documentStarted = true;
		}
		switch (event.getEventType()) {
			case XMLStreamConstants.START_DOCUMENT:
				handleStartDocument(event);
				documentStarted = true;
				break;
			case XMLStreamConstants.START_ELEMENT:
				elementDepth++;
				handleStartElement(event.asStartElement());
				break;
			case XMLStreamConstants.END_ELEMENT:
				elementDepth--;
				if (elementDepth >= 0) {
					handleEndElement(event.asEndElement());
				}
				break;
			case XMLStreamConstants.PROCESSING_INSTRUCTION:
				handleProcessingInstruction((ProcessingInstruction) event);
				break;
			case XMLStreamConstants.CHARACTERS:
			case XMLStreamConstants.SPACE:
			case XMLStreamConstants.CDATA:
				handleCharacters(event.asCharacters());
				break;
			case XMLStreamConstants.END_DOCUMENT:
				handleEndDocument();
				documentEnded = true;
				break;
			case XMLStreamConstants.NOTATION_DECLARATION:
				handleNotationDeclaration((NotationDeclaration) event);
				break;
			case XMLStreamConstants.ENTITY_DECLARATION:
				handleEntityDeclaration((EntityDeclaration) event);
				break;
			case XMLStreamConstants.COMMENT:
				handleComment((Comment) event);
				break;
			case XMLStreamConstants.DTD:
				handleDtd((DTD) event);
				break;
			case XMLStreamConstants.ENTITY_REFERENCE:
				handleEntityReference((EntityReference) event);
				break;
		}
	}
	if (documentStarted && !documentEnded) {
		handleEndDocument();
	}

}
 
Example 15
Source File: XmlMerger.java    From aion-germany with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Read all {@link javax.xml.stream.events.XMLEvent}'s from specified file and write them onto the {@link javax.xml.stream.XMLEventWriter}
 *
 * @param file
 *            File to import
 * @param skipRoot
 *            Skip-root flag
 * @param writer
 *            Destenation writer
 * @throws XMLStreamException
 *             On event reading/writing error.
 * @throws FileNotFoundException
 *             if the reading file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.
 */
private void importFile(File file, boolean skipRoot, XMLEventWriter writer, Properties metadata) throws XMLStreamException, IOException {
	logger.debug("Appending file " + file);
	metadata.setProperty(file.getPath(), makeHash(file));

	XMLEventReader reader = null;

	try {
		reader = inputFactory.createXMLEventReader(new FileReader(file));

		QName firstTagQName = null;

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

			// skip start and end of document.
			if (event.isStartDocument() || event.isEndDocument()) {
				continue;
			}
			// skip all comments.
			if (event instanceof Comment) {
				continue;
			}
			// skip white-spaces and all ignoreable white-spaces.
			if (event.isCharacters()) {
				if (event.asCharacters().isWhiteSpace() || event.asCharacters().isIgnorableWhiteSpace()) {
					continue;
				}
			}

			// modify root-tag of imported file.
			if (firstTagQName == null && event.isStartElement()) {
				firstTagQName = event.asStartElement().getName();

				if (skipRoot) {
					continue;
				}
				else {
					StartElement old = event.asStartElement();

					event = eventFactory.createStartElement(old.getName(), old.getAttributes(), null);
				}
			}

			// if root was skipped - skip root end too.
			if (event.isEndElement() && skipRoot && event.asEndElement().getName().equals(firstTagQName)) {
				continue;
			}

			// finally - write tag
			writer.add(event);
		}
	}
	finally {
		if (reader != null) {
			try {
				reader.close();
			}
			catch (Exception ignored) {
			}
		}
	}
}
 
Example 16
Source File: StaxEventXMLReader.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
protected void parseInternal() throws SAXException, XMLStreamException {
	boolean documentStarted = false;
	boolean documentEnded = false;
	int elementDepth = 0;
	while (this.reader.hasNext() && elementDepth >= 0) {
		XMLEvent event = this.reader.nextEvent();
		if (!event.isStartDocument() && !event.isEndDocument() && !documentStarted) {
			handleStartDocument(event);
			documentStarted = true;
		}
		switch (event.getEventType()) {
			case XMLStreamConstants.START_DOCUMENT:
				handleStartDocument(event);
				documentStarted = true;
				break;
			case XMLStreamConstants.START_ELEMENT:
				elementDepth++;
				handleStartElement(event.asStartElement());
				break;
			case XMLStreamConstants.END_ELEMENT:
				elementDepth--;
				if (elementDepth >= 0) {
					handleEndElement(event.asEndElement());
				}
				break;
			case XMLStreamConstants.PROCESSING_INSTRUCTION:
				handleProcessingInstruction((ProcessingInstruction) event);
				break;
			case XMLStreamConstants.CHARACTERS:
			case XMLStreamConstants.SPACE:
			case XMLStreamConstants.CDATA:
				handleCharacters(event.asCharacters());
				break;
			case XMLStreamConstants.END_DOCUMENT:
				handleEndDocument();
				documentEnded = true;
				break;
			case XMLStreamConstants.NOTATION_DECLARATION:
				handleNotationDeclaration((NotationDeclaration) event);
				break;
			case XMLStreamConstants.ENTITY_DECLARATION:
				handleEntityDeclaration((EntityDeclaration) event);
				break;
			case XMLStreamConstants.COMMENT:
				handleComment((Comment) event);
				break;
			case XMLStreamConstants.DTD:
				handleDtd((DTD) event);
				break;
			case XMLStreamConstants.ENTITY_REFERENCE:
				handleEntityReference((EntityReference) event);
				break;
		}
	}
	if (documentStarted && !documentEnded) {
		handleEndDocument();
	}

}
 
Example 17
Source File: StaxEventXMLReader.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
protected void parseInternal() throws SAXException, XMLStreamException {
	boolean documentStarted = false;
	boolean documentEnded = false;
	int elementDepth = 0;
	while (this.reader.hasNext() && elementDepth >= 0) {
		XMLEvent event = this.reader.nextEvent();
		if (!event.isStartDocument() && !event.isEndDocument() && !documentStarted) {
			handleStartDocument(event);
			documentStarted = true;
		}
		switch (event.getEventType()) {
			case XMLStreamConstants.START_DOCUMENT:
				handleStartDocument(event);
				documentStarted = true;
				break;
			case XMLStreamConstants.START_ELEMENT:
				elementDepth++;
				handleStartElement(event.asStartElement());
				break;
			case XMLStreamConstants.END_ELEMENT:
				elementDepth--;
				if (elementDepth >= 0) {
					handleEndElement(event.asEndElement());
				}
				break;
			case XMLStreamConstants.PROCESSING_INSTRUCTION:
				handleProcessingInstruction((ProcessingInstruction) event);
				break;
			case XMLStreamConstants.CHARACTERS:
			case XMLStreamConstants.SPACE:
			case XMLStreamConstants.CDATA:
				handleCharacters(event.asCharacters());
				break;
			case XMLStreamConstants.END_DOCUMENT:
				handleEndDocument();
				documentEnded = true;
				break;
			case XMLStreamConstants.NOTATION_DECLARATION:
				handleNotationDeclaration((NotationDeclaration) event);
				break;
			case XMLStreamConstants.ENTITY_DECLARATION:
				handleEntityDeclaration((EntityDeclaration) event);
				break;
			case XMLStreamConstants.COMMENT:
				handleComment((Comment) event);
				break;
			case XMLStreamConstants.DTD:
				handleDtd((DTD) event);
				break;
			case XMLStreamConstants.ENTITY_REFERENCE:
				handleEntityReference((EntityReference) event);
				break;
		}
	}
	if (documentStarted && !documentEnded) {
		handleEndDocument();
	}

}
 
Example 18
Source File: AbstractXMLEventWriter.java    From jettison with Apache License 2.0 4 votes vote down vote up
public void add(XMLEvent event) throws XMLStreamException {
	if (event.isStartDocument()) {
		streamWriter.writeStartDocument();
	} else if (event.isStartElement()) {
		StartElement element = event.asStartElement();
		QName elQName = element.getName();
		if (elQName.getPrefix().length() > 0
				&& elQName.getNamespaceURI().length() > 0)
			streamWriter.writeStartElement(elQName.getPrefix(), elQName
					.getLocalPart(), elQName.getNamespaceURI());
		else if (elQName.getNamespaceURI().length() > 0)
			streamWriter.writeStartElement(elQName.getNamespaceURI(),
					elQName.getLocalPart());
		else
			streamWriter.writeStartElement(elQName.getLocalPart());

		// Add element namespaces
		Iterator namespaces = element.getNamespaces();
		while (namespaces.hasNext()) {
			Namespace ns = (Namespace) namespaces.next();
			String prefix = ns.getPrefix();
			String nsURI = ns.getNamespaceURI();
			streamWriter.writeNamespace(prefix, nsURI);
		}

		// Add element attributes
		Iterator attris = element.getAttributes();
		while (attris.hasNext()) {
			Attribute attr = (Attribute) attris.next();
			QName atQName = attr.getName();
			String value = attr.getValue();
			if (atQName.getPrefix().length() > 0
					&& atQName.getNamespaceURI().length() > 0)
				streamWriter.writeAttribute(atQName.getPrefix(), atQName
						.getNamespaceURI(), atQName.getLocalPart(), value);
			else if (atQName.getNamespaceURI().length() > 0)
				streamWriter.writeAttribute(atQName.getNamespaceURI(),
						atQName.getLocalPart(), value);
			else
				streamWriter.writeAttribute(atQName.getLocalPart(), value);
		}
	} else if (event.isCharacters()) {
		Characters chars = event.asCharacters();
		streamWriter.writeCharacters(chars.getData());
	} else if (event.isEndElement()) {
		streamWriter.writeEndElement();
	} else if (event.isEndDocument()) {
		streamWriter.writeEndDocument();
	} else {
		throw new XMLStreamException("Unsupported event type: " + event);
	}
}
 
Example 19
Source File: StaxEventXMLReader.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
protected void parseInternal() throws SAXException, XMLStreamException {
	boolean documentStarted = false;
	boolean documentEnded = false;
	int elementDepth = 0;
	while (this.reader.hasNext() && elementDepth >= 0) {
		XMLEvent event = this.reader.nextEvent();
		if (!event.isStartDocument() && !event.isEndDocument() && !documentStarted) {
			handleStartDocument(event);
			documentStarted = true;
		}
		switch (event.getEventType()) {
			case XMLStreamConstants.START_DOCUMENT:
				handleStartDocument(event);
				documentStarted = true;
				break;
			case XMLStreamConstants.START_ELEMENT:
				elementDepth++;
				handleStartElement(event.asStartElement());
				break;
			case XMLStreamConstants.END_ELEMENT:
				elementDepth--;
				if (elementDepth >= 0) {
					handleEndElement(event.asEndElement());
				}
				break;
			case XMLStreamConstants.PROCESSING_INSTRUCTION:
				handleProcessingInstruction((ProcessingInstruction) event);
				break;
			case XMLStreamConstants.CHARACTERS:
			case XMLStreamConstants.SPACE:
			case XMLStreamConstants.CDATA:
				handleCharacters(event.asCharacters());
				break;
			case XMLStreamConstants.END_DOCUMENT:
				handleEndDocument();
				documentEnded = true;
				break;
			case XMLStreamConstants.NOTATION_DECLARATION:
				handleNotationDeclaration((NotationDeclaration) event);
				break;
			case XMLStreamConstants.ENTITY_DECLARATION:
				handleEntityDeclaration((EntityDeclaration) event);
				break;
			case XMLStreamConstants.COMMENT:
				handleComment((Comment) event);
				break;
			case XMLStreamConstants.DTD:
				handleDtd((DTD) event);
				break;
			case XMLStreamConstants.ENTITY_REFERENCE:
				handleEntityReference((EntityReference) event);
				break;
		}
	}
	if (documentStarted && !documentEnded) {
		handleEndDocument();
	}

}
 
Example 20
Source File: XmlMerger.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, Object object, List out) throws Exception {
    try {
        if (object instanceof  XMLEvent) {
            final XMLEvent event = (XMLEvent) object;

            if (event.isStartDocument() || event.isEndDocument()) {
                return;
            }

            if (event.isCharacters() && depth <= 1) {
                return;
            }

            if (depth < 1 && event.isStartElement()) {
                out.add(object);
                depth++;
                return;
            }

            if (depth <= 1 && event.isEndElement()) {
                out.add(object);
                depth--;
                return;
            }

            writer.add(event);

            if (event.isStartElement()) {
                depth++;
            } else if (event.isEndElement()) {
                depth--;

                if (depth == 1) {
                    writer.flush();
                    org.dom4j.Element xmlElement = transform().getRootElement();
                    out.add(xmlElement);
                    writer.close();
                    resetWriter();
                }
            }
        }
    } catch (Exception e) {
        logger.info(e.getCause().getMessage());
        throw e;
    }
}