Search in sources :

Example 1 with EventReaderDelegate

use of javax.xml.stream.util.EventReaderDelegate in project keycloak by keycloak.

the class AbstractParser method filterWhitespaces.

/**
 * Creates a derived {@link XMLEventReader} that ignores all events except for: {@link StartElement},
 * {@link EndElement}, and non-empty and non-whitespace-only {@link Characters}.
 *
 * @param xmlEventReader Original {@link XMLEventReader}
 * @return Derived {@link XMLEventReader}
 * @throws XMLStreamException
 */
private static XMLEventReader filterWhitespaces(XMLEventReader xmlEventReader) throws ParsingException {
    XMLInputFactory xmlInputFactory = XML_INPUT_FACTORY.get();
    try {
        xmlEventReader = xmlInputFactory.createFilteredReader(xmlEventReader, new EventFilter() {

            @Override
            public boolean accept(XMLEvent xmlEvent) {
                // We are going to disregard characters that are new line and whitespace
                if (xmlEvent.isCharacters()) {
                    Characters chars = xmlEvent.asCharacters();
                    String data = chars.getData();
                    return data != null && !WHITESPACE_ONLY.matcher(data).matches();
                } else {
                    return xmlEvent.isStartElement() || xmlEvent.isEndElement();
                }
            }
        });
    } catch (XMLStreamException ex) {
        throw logger.parserException(ex);
    }
    // Handle IBM JDK bug with Stax parsing when EventReader presented
    if (Environment.IS_IBM_JAVA) {
        final XMLEventReader origReader = xmlEventReader;
        xmlEventReader = new EventReaderDelegate(origReader) {

            @Override
            public boolean hasNext() {
                boolean hasNext = super.hasNext();
                try {
                    return hasNext && (origReader.peek() != null);
                } catch (XMLStreamException xse) {
                    throw new IllegalStateException(xse);
                }
            }
        };
    }
    return xmlEventReader;
}
Also used : XMLStreamException(javax.xml.stream.XMLStreamException) Characters(javax.xml.stream.events.Characters) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) EventFilter(javax.xml.stream.EventFilter) XMLInputFactory(javax.xml.stream.XMLInputFactory) EventReaderDelegate(javax.xml.stream.util.EventReaderDelegate)

Aggregations

EventFilter (javax.xml.stream.EventFilter)1 XMLEventReader (javax.xml.stream.XMLEventReader)1 XMLInputFactory (javax.xml.stream.XMLInputFactory)1 XMLStreamException (javax.xml.stream.XMLStreamException)1 Characters (javax.xml.stream.events.Characters)1 XMLEvent (javax.xml.stream.events.XMLEvent)1 EventReaderDelegate (javax.xml.stream.util.EventReaderDelegate)1