Search in sources :

Example 1 with XMLStreamReader

use of javax.xml.stream.XMLStreamReader in project jvm-serializers by eishay.

the class BaseStaxMediaSerializer method deserialize.

// // Public API
@Override
public MediaContent deserialize(byte[] array) throws XMLStreamException {
    XMLStreamReader parser = createReader(array);
    MediaContent content = _deserializer.readDocument(parser);
    parser.close();
    return content;
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) MediaContent(data.media.MediaContent)

Example 2 with XMLStreamReader

use of javax.xml.stream.XMLStreamReader in project OpenAttestation by OpenAttestation.

the class JAXB method read.

/**
     * Does not allow XML External Entity (XXE) injection CWE-611
     * http://cwe.mitre.org/data/definitions/611.html
     *
     * @param <T>
     * @param document
     * @param valueType
     * @return
     * @throws IOException
     * @throws JAXBException
     */
public <T> T read(String document, Class<T> valueType) throws IOException, JAXBException, XMLStreamException {
    JAXBContext jc = getContextForType(valueType);
    // CWE-611 restrict XML external entity references
    XMLInputFactory xif = XMLInputFactory.newFactory();
    // if true allows sender to include external files via entity declaration in the DTD, which is a security vulnerability
    xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    // if true allows sender to declare a DTD, and the DTD spec has security vulnerabilities so a reference implementation cannot be secure
    xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    // if true allows sender to encode &gt; &lt; &quot; &amp; and &apos;  but not custom-defined entity references because we disable dtd support ; http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Predefined_entities_in_XML
    xif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, true);
    XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource(new StringReader(document)));
    Unmarshaller u = jc.createUnmarshaller();
    JAXBElement<T> doc = u.unmarshal(xsr, valueType);
    return doc.getValue();
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) StreamSource(javax.xml.transform.stream.StreamSource) StringReader(java.io.StringReader) JAXBContext(javax.xml.bind.JAXBContext) Unmarshaller(javax.xml.bind.Unmarshaller) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 3 with XMLStreamReader

use of javax.xml.stream.XMLStreamReader in project che by eclipse.

the class XMLTree method constructTree.

/**
     * Constructs tree based on segments which are supplied by {@link XMLStreamReader}.
     * Before this method is invoked {@link #document} should be initialized first.
     * For START_ELEMENT, END_ELEMENT, CHARACTERS reader provides offset from
     * start of source array bytes, so we can fetch position of elements and text.
     * Each created element associated with related {@link Node} and vise-versa.
     */
private void constructTree() throws XMLStreamException {
    final XMLStreamReader reader = newXMLStreamReader();
    final LinkedList<Element> stack = new LinkedList<>();
    //before element open tag index
    int beforeStart = rootStart(xml) - 1;
    //used to associate each element with document node
    Node node = document.getDocumentElement();
    //used to hold previous reader event
    int prevEvent = START_DOCUMENT;
    while (reader.hasNext()) {
        switch(reader.next()) {
            case START_ELEMENT:
                final Element newElement = new Element(this);
                newElement.start = new Segment(beforeStart + 1, elementRight(beforeStart + 1, reader));
                //if new node is not xml root - set up relationships
                if (!stack.isEmpty()) {
                    node = deepNext(node, true);
                }
                //connect node with element
                node.setUserData("element", newElement, null);
                newElement.delegate = safeCast(node);
                //let next event know about its start
                beforeStart = newElement.start.right;
                //if element has declared namespaces register it
                putNamespaces(reader);
                stack.push(newElement);
                break;
            case END_ELEMENT:
                final Element element = stack.pop();
                element.end = new Segment(beforeStart + 1, elementRight(beforeStart + 1, reader));
                elements.add(element);
                beforeStart = element.end.right;
                break;
            case CHARACTERS:
                //so the only segment should be created for it
                if (prevEvent == CHARACTERS)
                    continue;
                final Element current = stack.peek();
                if (current.text == null) {
                    //TODO replace with array list as we know current node 'text nodes' count
                    current.text = new LinkedList<>();
                }
                final Node nextNode = deepNext(node, true);
                final int left = beforeStart + 1;
                final int right = left + textLength(nextNode) - 1;
                current.text.add(new Segment(left, right));
                beforeStart = right;
                node = skipTextNodes(nextNode);
                break;
            case COMMENT:
            case SPACE:
            case PROCESSING_INSTRUCTION:
                if (!stack.isEmpty()) {
                    node = deepNext(node, true);
                    beforeStart = lastIndexOf(xml, '>', reader.getLocation().getCharacterOffset());
                }
                break;
            default:
        }
        prevEvent = reader.getEventType();
    }
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) XMLTreeUtil.asElement(org.eclipse.che.commons.xml.XMLTreeUtil.asElement) Node(org.w3c.dom.Node) LinkedList(java.util.LinkedList)

Example 4 with XMLStreamReader

use of javax.xml.stream.XMLStreamReader in project openhab1-addons by openhab.

the class DenonConnector method getDocument.

private <T> T getDocument(String uri, Class<T> response) {
    try {
        String result = doHttpRequest("GET", uri, null);
        logger.trace("result of getDocument for uri '{}':\r\n{}", uri, result);
        if (StringUtils.isNotBlank(result)) {
            JAXBContext jc = JAXBContext.newInstance(response);
            XMLInputFactory xif = XMLInputFactory.newInstance();
            XMLStreamReader xsr = xif.createXMLStreamReader(IOUtils.toInputStream(result));
            xsr = new PropertyRenamerDelegate(xsr);
            @SuppressWarnings("unchecked") T obj = (T) jc.createUnmarshaller().unmarshal(xsr);
            return obj;
        }
    } catch (UnmarshalException e) {
        logger.debug("Failed to unmarshal xml document: {}", e.getMessage());
    } catch (JAXBException e) {
        logger.debug("Unexpected error occurred during unmarshalling of document: {}", e.getMessage());
    } catch (XMLStreamException e) {
        logger.debug("Communication error: {}", e.getMessage());
    }
    return null;
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) XMLStreamException(javax.xml.stream.XMLStreamException) UnmarshalException(javax.xml.bind.UnmarshalException) JAXBException(javax.xml.bind.JAXBException) JAXBContext(javax.xml.bind.JAXBContext) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 5 with XMLStreamReader

use of javax.xml.stream.XMLStreamReader in project midpoint by Evolveum.

the class XmlParser method parse.

public void parse(InputStream is, XmlObjectHandler handler) {
    XMLStreamReader stream;
    try {
        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        stream = xmlInputFactory.createXMLStreamReader(is);
        int serial = 1;
        Map<String, String> nsMap = new HashMap<String, String>();
        int eventType = stream.nextTag();
        if (eventType == XMLStreamConstants.START_ELEMENT) {
            if (!stream.getName().equals(ToolsUtils.C_OBJECTS)) {
                parseObject(stream, handler, serial, nsMap);
                return;
            }
            for (int i = 0; i < stream.getNamespaceCount(); i++) {
                nsMap.put(stream.getNamespacePrefix(i), stream.getNamespaceURI(i));
            }
        } else {
            throw new XMLStreamException("StAX problem, shouldn't happen.");
        }
        while (stream.hasNext()) {
            eventType = stream.next();
            if (eventType == XMLStreamConstants.START_ELEMENT) {
                if (!parseObject(stream, handler, serial, nsMap)) {
                    break;
                }
                serial++;
            }
        }
    } catch (XMLStreamException ex) {
        //todo error handling
        ex.printStackTrace();
    }
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) XMLStreamException(javax.xml.stream.XMLStreamException) HashMap(java.util.HashMap) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Aggregations

XMLStreamReader (javax.xml.stream.XMLStreamReader)1073 Test (org.junit.Test)486 InputStream (java.io.InputStream)451 ByteArrayInputStream (java.io.ByteArrayInputStream)379 ByteArrayOutputStream (java.io.ByteArrayOutputStream)334 Document (org.w3c.dom.Document)311 XMLStreamException (javax.xml.stream.XMLStreamException)287 ArrayList (java.util.ArrayList)270 XMLSecurityProperties (org.apache.xml.security.stax.ext.XMLSecurityProperties)242 XMLInputFactory (javax.xml.stream.XMLInputFactory)210 QName (javax.xml.namespace.QName)208 DOMSource (javax.xml.transform.dom.DOMSource)206 StringReader (java.io.StringReader)196 SecretKey (javax.crypto.SecretKey)188 StreamResult (javax.xml.transform.stream.StreamResult)183 DocumentBuilder (javax.xml.parsers.DocumentBuilder)178 XMLStreamWriter (javax.xml.stream.XMLStreamWriter)160 InboundXMLSec (org.apache.xml.security.stax.ext.InboundXMLSec)155 IOException (java.io.IOException)143 Key (java.security.Key)103