Search in sources :

Example 41 with XMLEventReader

use of javax.xml.stream.XMLEventReader in project camel by apache.

the class StAXJAXBIteratorExpression method evaluate.

@Override
@SuppressWarnings("unchecked")
public Object evaluate(Exchange exchange) {
    try {
        XMLEventReader reader;
        if (isNamespaceAware) {
            reader = exchange.getIn().getMandatoryBody(XMLEventReader.class);
        } else {
            InputStream inputStream = exchange.getIn().getMandatoryBody(InputStream.class);
            XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
            xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false);
            reader = xmlInputFactory.createXMLEventReader(inputStream);
        }
        Class<T> clazz = handled;
        if (clazz == null && handledName != null) {
            clazz = (Class<T>) exchange.getContext().getClassResolver().resolveMandatoryClass(handledName);
        }
        return createIterator(reader, clazz);
    } catch (InvalidPayloadException e) {
        exchange.setException(e);
        return null;
    } catch (JAXBException e) {
        exchange.setException(e);
        return null;
    } catch (ClassNotFoundException e) {
        exchange.setException(e);
        return null;
    } catch (XMLStreamException e) {
        exchange.setException(e);
        return null;
    }
}
Also used : XMLStreamException(javax.xml.stream.XMLStreamException) InputStream(java.io.InputStream) JAXBException(javax.xml.bind.JAXBException) XMLEventReader(javax.xml.stream.XMLEventReader) InvalidPayloadException(org.apache.camel.InvalidPayloadException) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 42 with XMLEventReader

use of javax.xml.stream.XMLEventReader in project bazel by bazelbuild.

the class DataResourceXml method parse.

/**
   * Parses xml resources from a Path to the provided overwritable and combining collections.
   *
   * <p>This method is a bit tricky in the service of performance -- creating several collections
   * and merging them was more expensive than writing to mutable collections directly.
   *
   * @param xmlInputFactory Used to create an XMLEventReader from the supplied resource path.
   * @param path The path to the xml resource to be parsed.
   * @param fqnFactory Used to create {@link FullyQualifiedName}s from the resource names.
   * @param overwritingConsumer A consumer for overwritable {@link DataResourceXml}s.
   * @param combiningConsumer A consumer for combining {@link DataResourceXml}s.
   * @throws XMLStreamException Thrown with the resource format is invalid.
   * @throws FactoryConfigurationError Thrown with the {@link XMLInputFactory} is misconfigured.
   * @throws IOException Thrown when there is an error reading a file.
   */
public static void parse(XMLInputFactory xmlInputFactory, Path path, Factory fqnFactory, KeyValueConsumer<DataKey, DataResource> overwritingConsumer, KeyValueConsumer<DataKey, DataResource> combiningConsumer) throws XMLStreamException, FactoryConfigurationError, IOException {
    XMLEventReader eventReader = xmlInputFactory.createXMLEventReader(new BufferedInputStream(Files.newInputStream(path)), StandardCharsets.UTF_8.toString());
    try {
        // TODO(corysmith): Make the xml parsing more readable.
        for (StartElement resources = XmlResourceValues.moveToResources(eventReader); resources != null; resources = XmlResourceValues.moveToResources(eventReader)) {
            // Record attributes on the <resources> tag.
            Iterator<Attribute> attributes = XmlResourceValues.iterateAttributesFrom(resources);
            while (attributes.hasNext()) {
                Attribute attribute = attributes.next();
                Namespaces namespaces = Namespaces.from(attribute.getName());
                String attributeName = attribute.getName().getNamespaceURI().isEmpty() ? attribute.getName().getLocalPart() : attribute.getName().getPrefix() + ":" + attribute.getName().getLocalPart();
                overwritingConsumer.consume(fqnFactory.create(VirtualType.RESOURCES_ATTRIBUTE, attributeName), DataResourceXml.createWithNamespaces(path, ResourcesAttribute.of(attributeName, attribute.getValue()), namespaces));
            }
            // Process resource declarations.
            for (StartElement start = XmlResourceValues.findNextStart(eventReader); start != null; start = XmlResourceValues.findNextStart(eventReader)) {
                Namespaces.Collector namespacesCollector = Namespaces.collector();
                if (XmlResourceValues.isEatComment(start) || XmlResourceValues.isSkip(start)) {
                    continue;
                }
                ResourceType resourceType = getResourceType(start);
                if (resourceType == null) {
                    throw new XMLStreamException(path + " contains an unrecognized resource type: " + start, start.getLocation());
                }
                if (resourceType == DECLARE_STYLEABLE) {
                    // Styleables are special, as they produce multiple overwrite and combining values,
                    // so we let the value handle the assignments.
                    XmlResourceValues.parseDeclareStyleable(fqnFactory, path, overwritingConsumer, combiningConsumer, eventReader, start);
                } else {
                    // Of simple resources, only IDs and Public are combining.
                    KeyValueConsumer<DataKey, DataResource> consumer = (resourceType == ID || resourceType == PUBLIC) ? combiningConsumer : overwritingConsumer;
                    String elementName = XmlResourceValues.getElementName(start);
                    if (elementName == null) {
                        throw new XMLStreamException(String.format("resource name is required for %s", resourceType), start.getLocation());
                    }
                    FullyQualifiedName key = fqnFactory.create(resourceType, elementName);
                    XmlResourceValue xmlResourceValue = parseXmlElements(resourceType, eventReader, start, namespacesCollector);
                    consumer.consume(key, DataResourceXml.createWithNamespaces(path, xmlResourceValue, namespacesCollector.toNamespaces()));
                }
            }
        }
    } catch (XMLStreamException e) {
        throw new XMLStreamException(path + ": " + e.getMessage(), e.getLocation(), e);
    } catch (RuntimeException e) {
        throw new RuntimeException("Error parsing " + path, e);
    }
}
Also used : Namespaces(com.google.devtools.build.android.xml.Namespaces) Attribute(javax.xml.stream.events.Attribute) ResourcesAttribute(com.google.devtools.build.android.xml.ResourcesAttribute) ResourceType(com.android.resources.ResourceType) StartElement(javax.xml.stream.events.StartElement) StyleableXmlResourceValue(com.google.devtools.build.android.xml.StyleableXmlResourceValue) PublicXmlResourceValue(com.google.devtools.build.android.xml.PublicXmlResourceValue) SimpleXmlResourceValue(com.google.devtools.build.android.xml.SimpleXmlResourceValue) StyleXmlResourceValue(com.google.devtools.build.android.xml.StyleXmlResourceValue) ArrayXmlResourceValue(com.google.devtools.build.android.xml.ArrayXmlResourceValue) IdXmlResourceValue(com.google.devtools.build.android.xml.IdXmlResourceValue) AttrXmlResourceValue(com.google.devtools.build.android.xml.AttrXmlResourceValue) PluralXmlResourceValue(com.google.devtools.build.android.xml.PluralXmlResourceValue) XMLStreamException(javax.xml.stream.XMLStreamException) BufferedInputStream(java.io.BufferedInputStream) XMLEventReader(javax.xml.stream.XMLEventReader)

Example 43 with XMLEventReader

use of javax.xml.stream.XMLEventReader in project spring-framework by spring-projects.

the class Jaxb2XmlDecoder method unmarshal.

private Object unmarshal(List<XMLEvent> events, Class<?> outputClass) {
    try {
        Unmarshaller unmarshaller = this.jaxbContexts.createUnmarshaller(outputClass);
        XMLEventReader eventReader = StaxUtils.createXMLEventReader(events);
        if (outputClass.isAnnotationPresent(XmlRootElement.class)) {
            return unmarshaller.unmarshal(eventReader);
        } else {
            JAXBElement<?> jaxbElement = unmarshaller.unmarshal(eventReader, outputClass);
            return jaxbElement.getValue();
        }
    } catch (JAXBException ex) {
        throw new CodecException(ex.getMessage(), ex);
    }
}
Also used : JAXBException(javax.xml.bind.JAXBException) XMLEventReader(javax.xml.stream.XMLEventReader) CodecException(org.springframework.core.codec.CodecException) Unmarshaller(javax.xml.bind.Unmarshaller)

Example 44 with XMLEventReader

use of javax.xml.stream.XMLEventReader in project spring-framework by spring-projects.

the class XmlEventDecoder method decode.

@Override
@SuppressWarnings("unchecked")
public Flux<XMLEvent> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType, MimeType mimeType, Map<String, Object> hints) {
    Flux<DataBuffer> flux = Flux.from(inputStream);
    if (useAalto && aaltoPresent) {
        return flux.flatMap(new AaltoDataBufferToXmlEvent());
    } else {
        Mono<DataBuffer> singleBuffer = flux.reduce(DataBuffer::write);
        return singleBuffer.flatMap(dataBuffer -> {
            try {
                InputStream is = dataBuffer.asInputStream();
                XMLEventReader eventReader = inputFactory.createXMLEventReader(is);
                return Flux.fromIterable((Iterable<XMLEvent>) () -> eventReader);
            } catch (XMLStreamException ex) {
                return Mono.error(ex);
            } finally {
                DataBufferUtils.release(dataBuffer);
            }
        });
    }
}
Also used : XMLStreamException(javax.xml.stream.XMLStreamException) InputStream(java.io.InputStream) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) DataBuffer(org.springframework.core.io.buffer.DataBuffer)

Example 45 with XMLEventReader

use of javax.xml.stream.XMLEventReader in project spring-framework by spring-projects.

the class XMLEventStreamReaderTests method createStreamReader.

@Before
public void createStreamReader() throws Exception {
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader(XML));
    streamReader = new XMLEventStreamReader(eventReader);
}
Also used : StringReader(java.io.StringReader) XMLEventReader(javax.xml.stream.XMLEventReader) XMLInputFactory(javax.xml.stream.XMLInputFactory) Before(org.junit.Before)

Aggregations

XMLEventReader (javax.xml.stream.XMLEventReader)71 XMLInputFactory (javax.xml.stream.XMLInputFactory)36 XMLEvent (javax.xml.stream.events.XMLEvent)34 XMLStreamException (javax.xml.stream.XMLStreamException)23 StringReader (java.io.StringReader)18 Test (org.junit.Test)17 InputStream (java.io.InputStream)15 StAXSource (javax.xml.transform.stax.StAXSource)13 StartElement (javax.xml.stream.events.StartElement)12 IOException (java.io.IOException)10 Unmarshaller (javax.xml.bind.Unmarshaller)9 Attribute (javax.xml.stream.events.Attribute)8 ByteArrayInputStream (java.io.ByteArrayInputStream)6 StringWriter (java.io.StringWriter)6 ArrayList (java.util.ArrayList)6 QName (javax.xml.namespace.QName)6 Document (org.w3c.dom.Document)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 InputStreamReader (java.io.InputStreamReader)5 JAXBContext (javax.xml.bind.JAXBContext)5