Search in sources :

Example 6 with StartElement

use of javax.xml.stream.events.StartElement in project bazel by bazelbuild.

the class DataValueFileWithIds method parse.

public static void parse(XMLInputFactory xmlInputFactory, Path source, FullyQualifiedName fileKey, FullyQualifiedName.Factory fqnFactory, KeyValueConsumer<DataKey, DataResource> overwritingConsumer, KeyValueConsumer<DataKey, DataResource> combiningConsumer) throws IOException, XMLStreamException {
    ImmutableSet.Builder<String> newIds = ImmutableSet.builder();
    try (BufferedInputStream inStream = new BufferedInputStream(Files.newInputStream(source))) {
        XMLEventReader eventReader = xmlInputFactory.createXMLEventReader(inStream, StandardCharsets.UTF_8.toString());
        // forgiving and allow even non-android namespaced attributes to define a new ID.
        while (eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();
            if (event.isStartElement()) {
                StartElement start = event.asStartElement();
                Iterator<Attribute> attributes = XmlResourceValues.iterateAttributesFrom(start);
                while (attributes.hasNext()) {
                    Attribute attribute = attributes.next();
                    String value = attribute.getValue();
                    if (value.startsWith(SdkConstants.NEW_ID_PREFIX)) {
                        String idName = value.substring(SdkConstants.NEW_ID_PREFIX.length());
                        newIds.add(idName);
                    }
                }
            }
        }
        eventReader.close();
    } catch (XMLStreamException e) {
        throw new XMLStreamException(source + ": " + e.getMessage(), e.getLocation(), e);
    } catch (RuntimeException e) {
        throw new RuntimeException("Error parsing " + source, e);
    }
    ImmutableSet<String> idResources = newIds.build();
    overwritingConsumer.consume(fileKey, DataValueFile.of(source));
    for (String id : idResources) {
        combiningConsumer.consume(fqnFactory.create(ResourceType.ID, id), DataResourceXml.createWithNoNamespace(source, IdXmlResourceValue.of()));
    }
}
Also used : StartElement(javax.xml.stream.events.StartElement) ImmutableSet(com.google.common.collect.ImmutableSet) XMLStreamException(javax.xml.stream.XMLStreamException) BufferedInputStream(java.io.BufferedInputStream) Attribute(javax.xml.stream.events.Attribute) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader)

Example 7 with StartElement

use of javax.xml.stream.events.StartElement in project bazel by bazelbuild.

the class AndroidManifestProcessor method writeManifestPackage.

/**
   * Overwrite the package attribute of {@code <manifest>} in an AndroidManifest.xml file.
   *
   * @param manifest The input manifest.
   * @param customPackage The package to write to the manifest.
   * @param output The output manifest to generate.
   * @return The output manifest if generated or the input manifest if no overwriting is required.
   */
/* TODO(apell): switch from custom xml parsing to Gradle merger with NO_PLACEHOLDER_REPLACEMENT
   * set when android common is updated to version 2.5.0.
   */
public Path writeManifestPackage(Path manifest, String customPackage, Path output) {
    if (Strings.isNullOrEmpty(customPackage)) {
        return manifest;
    }
    try {
        Files.createDirectories(output.getParent());
        XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(Files.newInputStream(manifest), UTF_8.name());
        XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(Files.newOutputStream(output), UTF_8.name());
        XMLEventFactory eventFactory = XMLEventFactory.newInstance();
        while (reader.hasNext()) {
            XMLEvent event = reader.nextEvent();
            if (event.isStartElement() && event.asStartElement().getName().toString().equalsIgnoreCase("manifest")) {
                StartElement element = event.asStartElement();
                @SuppressWarnings("unchecked") Iterator<Attribute> attributes = element.getAttributes();
                ImmutableList.Builder<Attribute> newAttributes = ImmutableList.builder();
                while (attributes.hasNext()) {
                    Attribute attr = attributes.next();
                    if (attr.getName().toString().equalsIgnoreCase("package")) {
                        newAttributes.add(eventFactory.createAttribute("package", customPackage));
                    } else {
                        newAttributes.add(attr);
                    }
                }
                writer.add(eventFactory.createStartElement(element.getName(), newAttributes.build().iterator(), element.getNamespaces()));
            } else {
                writer.add(event);
            }
        }
        writer.flush();
    } catch (XMLStreamException | FactoryConfigurationError | IOException e) {
        throw new RuntimeException(e);
    }
    return output;
}
Also used : Attribute(javax.xml.stream.events.Attribute) XMLEventFactory(javax.xml.stream.XMLEventFactory) ImmutableList(com.google.common.collect.ImmutableList) IOException(java.io.IOException) StartElement(javax.xml.stream.events.StartElement) XMLStreamException(javax.xml.stream.XMLStreamException) XMLEventWriter(javax.xml.stream.XMLEventWriter) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) FactoryConfigurationError(javax.xml.stream.FactoryConfigurationError)

Example 8 with StartElement

use of javax.xml.stream.events.StartElement in project hibernate-orm by hibernate.

the class FilteringXMLEventReader method internalNext.

protected final XMLEvent internalNext(boolean peek) throws XMLStreamException {
    XMLEvent event = null;
    if (peekedEvent != null) {
        event = peekedEvent;
        peekedEvent = null;
        return event;
    }
    do {
        event = super.getParent().nextEvent();
        //If there are pruned elements in the queue filtering events is still needed
        if (!prunedElements.isEmpty()) {
            //If another start element add it to the queue
            if (event.isStartElement()) {
                final StartElement startElement = event.asStartElement();
                prunedElements.push(startElement.getName());
            } else //If end element pop the newest name of the queue and double check that the start/end elements match up
            if (event.isEndElement()) {
                final QName startElementName = prunedElements.pop();
                final EndElement endElement = event.asEndElement();
                final QName endElementName = endElement.getName();
                if (!startElementName.equals(endElementName)) {
                    throw new IllegalArgumentException("Malformed XMLEvent stream. Expected end element for " + startElementName + " but found end element for " + endElementName);
                }
            }
            event = null;
        } else {
            final XMLEvent filteredEvent = this.filterEvent(event, peek);
            //end element need to be removed as well
            if (filteredEvent == null && event.isStartElement()) {
                final StartElement startElement = event.asStartElement();
                final QName name = startElement.getName();
                prunedElements.push(name);
            }
            event = filteredEvent;
        }
    } while (event == null);
    return event;
}
Also used : StartElement(javax.xml.stream.events.StartElement) EndElement(javax.xml.stream.events.EndElement) QName(javax.xml.namespace.QName) XMLEvent(javax.xml.stream.events.XMLEvent)

Example 9 with StartElement

use of javax.xml.stream.events.StartElement in project midpoint by Evolveum.

the class MidpointFunctionsImpl method parseXmlToMap.

@Override
public Map<String, String> parseXmlToMap(String xml) {
    Map<String, String> resultingMap = new HashMap<String, String>();
    if (xml != null && !xml.isEmpty()) {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        String value = "";
        String startName = "";
        InputStream stream = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
        boolean isRootElement = true;
        try {
            XMLEventReader eventReader = factory.createXMLEventReader(stream);
            while (eventReader.hasNext()) {
                XMLEvent event = eventReader.nextEvent();
                Integer code = event.getEventType();
                if (code == XMLStreamConstants.START_ELEMENT) {
                    StartElement startElement = event.asStartElement();
                    startName = startElement.getName().getLocalPart();
                    if (!isRootElement) {
                        resultingMap.put(startName, null);
                    } else {
                        isRootElement = false;
                    }
                } else if (code == XMLStreamConstants.CHARACTERS) {
                    Characters characters = event.asCharacters();
                    if (!characters.isWhiteSpace()) {
                        StringBuilder valueBuilder;
                        if (value != null) {
                            valueBuilder = new StringBuilder(value).append(" ").append(characters.getData().toString());
                        } else {
                            valueBuilder = new StringBuilder(characters.getData().toString());
                        }
                        value = valueBuilder.toString();
                    }
                } else if (code == XMLStreamConstants.END_ELEMENT) {
                    EndElement endElement = event.asEndElement();
                    String endName = endElement.getName().getLocalPart();
                    if (endName.equals(startName)) {
                        if (value != null) {
                            resultingMap.put(endName, value);
                            value = null;
                        }
                    } else {
                        LOGGER.trace("No value between xml tags, tag name : {0}", endName);
                    }
                } else if (code == XMLStreamConstants.END_DOCUMENT) {
                    isRootElement = true;
                }
            }
        } catch (XMLStreamException e) {
            StringBuilder error = new StringBuilder("Xml stream exception wile parsing xml string").append(e.getLocalizedMessage());
            throw new SystemException(error.toString());
        }
    } else {
        LOGGER.trace("Input xml string null or empty.");
    }
    return resultingMap;
}
Also used : EndElement(javax.xml.stream.events.EndElement) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Characters(javax.xml.stream.events.Characters) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) StartElement(javax.xml.stream.events.StartElement) XMLStreamException(javax.xml.stream.XMLStreamException) ByteArrayInputStream(java.io.ByteArrayInputStream) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 10 with StartElement

use of javax.xml.stream.events.StartElement in project opennms by OpenNMS.

the class HypericAckProcessor method parseHypericAlerts.

/**
     * <p>parseHypericAlerts</p>
     *
     * @param reader a {@link java.io.Reader} object.
     * @return a {@link java.util.List} object.
     * @throws javax.xml.bind.JAXBException if any.
     * @throws javax.xml.stream.XMLStreamException if any.
     */
public static List<HypericAlertStatus> parseHypericAlerts(Reader reader) throws JAXBException, XMLStreamException {
    List<HypericAlertStatus> retval = new ArrayList<HypericAlertStatus>();
    // Instantiate a JAXB context to parse the alert status
    JAXBContext context = JAXBContext.newInstance(new Class[] { HypericAlertStatuses.class, HypericAlertStatus.class });
    XMLInputFactory xmlif = XMLInputFactory.newInstance();
    XMLEventReader xmler = xmlif.createXMLEventReader(reader);
    EventFilter filter = new EventFilter() {

        @Override
        public boolean accept(XMLEvent event) {
            return event.isStartElement();
        }
    };
    XMLEventReader xmlfer = xmlif.createFilteredReader(xmler, filter);
    // Read up until the beginning of the root element
    StartElement startElement = (StartElement) xmlfer.nextEvent();
    // Fetch the root element name for {@link HypericAlertStatus} objects
    String rootElementName = context.createJAXBIntrospector().getElementName(new HypericAlertStatuses()).getLocalPart();
    if (rootElementName.equals(startElement.getName().getLocalPart())) {
        Unmarshaller unmarshaller = context.createUnmarshaller();
        // Use StAX to pull parse the incoming alert statuses
        while (xmlfer.peek() != null) {
            Object object = unmarshaller.unmarshal(xmler);
            if (object instanceof HypericAlertStatus) {
                HypericAlertStatus alertStatus = (HypericAlertStatus) object;
                retval.add(alertStatus);
            }
        }
    } else {
        // Try to pull in the HTTP response to give the user a better idea of what went wrong
        StringBuffer errorContent = new StringBuffer();
        LineNumberReader lineReader = new LineNumberReader(reader);
        try {
            String line;
            while (true) {
                line = lineReader.readLine();
                if (line == null) {
                    break;
                } else {
                    errorContent.append(line.trim());
                }
            }
        } catch (IOException e) {
            errorContent.append("Exception while trying to print out message content: " + e.getMessage());
        }
        // Throw an exception and include the erroneous HTTP response in the exception text
        throw new JAXBException("Found wrong root element in Hyperic XML document, expected: \"" + rootElementName + "\", found \"" + startElement.getName().getLocalPart() + "\"\n" + errorContent.toString());
    }
    return retval;
}
Also used : JAXBException(javax.xml.bind.JAXBException) ArrayList(java.util.ArrayList) JAXBContext(javax.xml.bind.JAXBContext) IOException(java.io.IOException) EventFilter(javax.xml.stream.EventFilter) LineNumberReader(java.io.LineNumberReader) StartElement(javax.xml.stream.events.StartElement) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) Unmarshaller(javax.xml.bind.Unmarshaller) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Aggregations

StartElement (javax.xml.stream.events.StartElement)30 XMLEvent (javax.xml.stream.events.XMLEvent)20 QName (javax.xml.namespace.QName)11 XMLEventReader (javax.xml.stream.XMLEventReader)10 XMLStreamException (javax.xml.stream.XMLStreamException)9 Attribute (javax.xml.stream.events.Attribute)8 EndElement (javax.xml.stream.events.EndElement)8 XMLInputFactory (javax.xml.stream.XMLInputFactory)7 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 InputStream (java.io.InputStream)3 LinkedList (java.util.LinkedList)3 JAXBContext (javax.xml.bind.JAXBContext)3 Unmarshaller (javax.xml.bind.Unmarshaller)3 EventFilter (javax.xml.stream.EventFilter)3 Characters (javax.xml.stream.events.Characters)3 IPortletWindow (org.apereo.portal.portlet.om.IPortletWindow)3 AbstractGCEvent (com.tagtraum.perf.gcviewer.model.AbstractGCEvent)2 GCEvent (com.tagtraum.perf.gcviewer.model.GCEvent)2 BufferedInputStream (java.io.BufferedInputStream)2