Search in sources :

Example 11 with XMLEvent

use of javax.xml.stream.events.XMLEvent in project camel by apache.

the class ScrHelper method getScrProperties.

public static Map<String, String> getScrProperties(String xmlLocation, String componentName) throws Exception {
    Map<String, String> result = new HashMap<>();
    XMLInputFactory inputFactory = XMLInputFactory.newFactory();
    inputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false);
    XMLEventReader eventReader = inputFactory.createXMLEventReader(new FileReader(xmlLocation));
    boolean collect = false;
    while (eventReader.hasNext()) {
        XMLEvent event = eventReader.nextEvent();
        if (event.getEventType() == XMLStreamConstants.START_ELEMENT && event.asStartElement().getName().toString().equals("scr:component") && event.asStartElement().getAttributeByName(QName.valueOf("name")).getValue().equals(componentName)) {
            collect = true;
        } else if (collect && event.getEventType() == XMLStreamConstants.START_ELEMENT && event.asStartElement().getName().toString().equals("property")) {
            result.put(event.asStartElement().getAttributeByName(QName.valueOf("name")).getValue(), event.asStartElement().getAttributeByName(QName.valueOf("value")).getValue());
        } else if (collect && event.getEventType() == XMLStreamConstants.END_ELEMENT && event.asEndElement().getName().toString().equals("scr:component")) {
            break;
        }
    }
    return result;
}
Also used : HashMap(java.util.HashMap) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) FileReader(java.io.FileReader) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 12 with XMLEvent

use of javax.xml.stream.events.XMLEvent in project hadoop by apache.

the class NodeInfo method parseConf.

private static List<NodeInfo> parseConf(InputStream in) throws XMLStreamException {
    QName configuration = new QName("configuration");
    QName property = new QName("property");
    List<NodeInfo> nodes = new ArrayList<NodeInfo>();
    Stack<NodeInfo> parsed = new Stack<NodeInfo>();
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLEventReader reader = factory.createXMLEventReader(in);
    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();
        if (event.isStartElement()) {
            StartElement currentElement = event.asStartElement();
            NodeInfo currentNode = new NodeInfo(currentElement);
            if (parsed.isEmpty()) {
                if (!currentElement.getName().equals(configuration)) {
                    return null;
                }
            } else {
                NodeInfo parentNode = parsed.peek();
                QName parentName = parentNode.getStartElement().getName();
                if (parentName.equals(configuration) && currentNode.getStartElement().getName().equals(property)) {
                    @SuppressWarnings("unchecked") Iterator<Attribute> it = currentElement.getAttributes();
                    while (it.hasNext()) {
                        currentNode.addAttribute(it.next());
                    }
                } else if (parentName.equals(property)) {
                    parentNode.addElement(currentElement);
                }
            }
            parsed.push(currentNode);
        } else if (event.isEndElement()) {
            NodeInfo node = parsed.pop();
            if (parsed.size() == 1) {
                nodes.add(node);
            }
        } else if (event.isCharacters()) {
            if (2 < parsed.size()) {
                NodeInfo parentNode = parsed.pop();
                StartElement parentElement = parentNode.getStartElement();
                NodeInfo grandparentNode = parsed.peek();
                if (grandparentNode.getElement(parentElement) == null) {
                    grandparentNode.setElement(parentElement, event.asCharacters());
                }
                parsed.push(parentNode);
            }
        }
    }
    return nodes;
}
Also used : Attribute(javax.xml.stream.events.Attribute) QName(javax.xml.namespace.QName) ArrayList(java.util.ArrayList) Stack(java.util.Stack) StartElement(javax.xml.stream.events.StartElement) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 13 with XMLEvent

use of javax.xml.stream.events.XMLEvent in project hadoop by apache.

the class NodeInfo method checkConf.

public static List<String> checkConf(InputStream in) {
    List<NodeInfo> nodes = null;
    List<String> errors = new ArrayList<String>();
    try {
        nodes = parseConf(in);
        if (nodes == null) {
            errors.add("bad conf file: top-level element not <configuration>");
        }
    } catch (XMLStreamException e) {
        errors.add("bad conf file: " + e.getMessage());
    }
    if (!errors.isEmpty()) {
        return errors;
    }
    Map<String, List<Integer>> duplicatedProperties = new HashMap<String, List<Integer>>();
    for (NodeInfo node : nodes) {
        StartElement element = node.getStartElement();
        int line = element.getLocation().getLineNumber();
        if (!element.getName().equals(new QName("property"))) {
            errors.add(String.format("Line %d: element not <property>", line));
            continue;
        }
        List<XMLEvent> events = node.getXMLEventsForQName(new QName("name"));
        if (events == null) {
            errors.add(String.format("Line %d: <property> has no <name>", line));
        } else {
            String v = null;
            for (XMLEvent event : events) {
                if (event.isAttribute()) {
                    v = ((Attribute) event).getValue();
                } else {
                    Characters c = node.getElement(event.asStartElement());
                    if (c != null) {
                        v = c.getData();
                    }
                }
                if (v == null || v.isEmpty()) {
                    errors.add(String.format("Line %d: <property> has an empty <name>", line));
                }
            }
            if (v != null && !v.isEmpty()) {
                List<Integer> lines = duplicatedProperties.get(v);
                if (lines == null) {
                    lines = new ArrayList<Integer>();
                    duplicatedProperties.put(v, lines);
                }
                lines.add(node.getStartElement().getLocation().getLineNumber());
            }
        }
        events = node.getXMLEventsForQName(new QName("value"));
        if (events == null) {
            errors.add(String.format("Line %d: <property> has no <value>", line));
        }
        for (QName qName : node.getDuplicatedQNames()) {
            if (!qName.equals(new QName("source"))) {
                errors.add(String.format("Line %d: <property> has duplicated <%s>s", line, qName));
            }
        }
    }
    for (Entry<String, List<Integer>> e : duplicatedProperties.entrySet()) {
        List<Integer> lines = e.getValue();
        if (1 < lines.size()) {
            errors.add(String.format("Line %s: duplicated <property>s for %s", StringUtils.join(", ", lines), e.getKey()));
        }
    }
    return errors;
}
Also used : HashMap(java.util.HashMap) QName(javax.xml.namespace.QName) Characters(javax.xml.stream.events.Characters) ArrayList(java.util.ArrayList) StartElement(javax.xml.stream.events.StartElement) XMLStreamException(javax.xml.stream.XMLStreamException) XMLEvent(javax.xml.stream.events.XMLEvent) ArrayList(java.util.ArrayList) List(java.util.List)

Example 14 with XMLEvent

use of javax.xml.stream.events.XMLEvent 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
        final StringBuilder errorContent = new StringBuilder();
        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)

Example 15 with XMLEvent

use of javax.xml.stream.events.XMLEvent in project S-argo by Expugn.

the class ScoutMasterParser method readConfig.

/**
 * Reads the ScoutMaster file and saves the data found to variables.
 */
@SuppressWarnings("unchecked")
private void readConfig() {
    InputStream in = null;
    XMLEventReader eventReader = null;
    try {
        /* CREATE XMLInputFactory AND XMLEventReader */
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        in = new FileInputStream("data/mods/" + scoutMasterName + ".xml");
        eventReader = inputFactory.createXMLEventReader(in);
        /* READ XML FILE */
        while (eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();
            if (event.isStartElement()) {
                if (event.asStartElement().getName().getLocalPart().equals("BotName")) {
                    Iterator<Attribute> attributes = event.asStartElement().getAttributes();
                    while (attributes.hasNext()) {
                        Attribute attribute = attributes.next();
                        if (attribute.getName().toString().equals("name")) {
                            botName = attribute.getValue();
                        }
                    }
                    continue;
                }
                if (event.asStartElement().getName().getLocalPart().equals("Smile")) {
                    Iterator<Attribute> attributes = event.asStartElement().getAttributes();
                    while (attributes.hasNext()) {
                        Attribute attribute = attributes.next();
                        if (attribute.getName().toString().equals("imageURL")) {
                            image1URL = attribute.getValue();
                        }
                    }
                    continue;
                }
                if (event.asStartElement().getName().getLocalPart().equals("Grin")) {
                    Iterator<Attribute> attributes = event.asStartElement().getAttributes();
                    while (attributes.hasNext()) {
                        Attribute attribute = attributes.next();
                        if (attribute.getName().toString().equals("imageURL")) {
                            image2URL = attribute.getValue();
                        }
                    }
                    continue;
                }
                if (event.asStartElement().getName().getLocalPart().equals("Smug")) {
                    Iterator<Attribute> attributes = event.asStartElement().getAttributes();
                    while (attributes.hasNext()) {
                        Attribute attribute = attributes.next();
                        if (attribute.getName().toString().equals("imageURL")) {
                            image3URL = attribute.getValue();
                        }
                    }
                    continue;
                }
                if (event.asStartElement().getName().getLocalPart().equals("Flowers")) {
                    Iterator<Attribute> attributes = event.asStartElement().getAttributes();
                    while (attributes.hasNext()) {
                        Attribute attribute = attributes.next();
                        if (attribute.getName().toString().equals("imageURL")) {
                            image4URL = attribute.getValue();
                        }
                    }
                    continue;
                }
                if (event.asStartElement().getName().getLocalPart().equals("Quote")) {
                    Iterator<Attribute> attributes = event.asStartElement().getAttributes();
                    while (attributes.hasNext()) {
                        Attribute attribute = attributes.next();
                        if (attribute.getName().toString().equals("say")) {
                            quotes.add("*\"" + attribute.getValue() + "\"*");
                        }
                    }
                }
            }
        }
    } catch (FileNotFoundException e) {
        System.out.println("[ScoutMasterParser] - File Not Found Exception");
        useDefaults = true;
    } catch (XMLStreamException e) {
        System.out.println("[ScoutMasterParser] - XML Stream Exception");
        useDefaults = true;
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
        /* IGNORED */
        }
        try {
            if (eventReader != null) {
                eventReader.close();
            }
        } catch (XMLStreamException e) {
        /* IGNORED */
        }
    }
}
Also used : XMLStreamException(javax.xml.stream.XMLStreamException) Attribute(javax.xml.stream.events.Attribute) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Aggregations

XMLEvent (javax.xml.stream.events.XMLEvent)269 XMLEventReader (javax.xml.stream.XMLEventReader)114 StartElement (javax.xml.stream.events.StartElement)107 XMLStreamException (javax.xml.stream.XMLStreamException)96 XMLInputFactory (javax.xml.stream.XMLInputFactory)65 QName (javax.xml.namespace.QName)60 Attribute (javax.xml.stream.events.Attribute)52 EndElement (javax.xml.stream.events.EndElement)52 IOException (java.io.IOException)39 ArrayList (java.util.ArrayList)32 InputStream (java.io.InputStream)29 XMLEventWriter (javax.xml.stream.XMLEventWriter)24 Characters (javax.xml.stream.events.Characters)22 ByteArrayInputStream (java.io.ByteArrayInputStream)17 StringWriter (java.io.StringWriter)17 Test (org.junit.Test)17 StringReader (java.io.StringReader)14 HashMap (java.util.HashMap)14 XMLOutputFactory (javax.xml.stream.XMLOutputFactory)14 XMLEventFactory (javax.xml.stream.XMLEventFactory)13