Java Code Examples for javax.xml.stream.XMLStreamConstants#START_ELEMENT

The following examples show how to use javax.xml.stream.XMLStreamConstants#START_ELEMENT . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConfigXml.java    From galleon with Apache License 2.0 6 votes vote down vote up
private static void readProps(XMLExtendedStreamReader reader, ConfigModel.Builder builder) throws XMLStreamException {
    ParsingUtils.parseNoAttributes(reader);
    while (reader.hasNext()) {
        switch (reader.nextTag()) {
            case XMLStreamConstants.END_ELEMENT: {
                return;
            }
            case XMLStreamConstants.START_ELEMENT: {
                final Element element = Element.of(reader.getName().getLocalPart());
                switch (element) {
                    case PROP:
                        readProp(reader, builder);
                        break;
                    default:
                        throw ParsingUtils.unexpectedContent(reader);
                }
                break;
            }
            default: {
                throw ParsingUtils.unexpectedContent(reader);
            }
        }
    }
    throw ParsingUtils.endOfDocument(reader.getLocation());
}
 
Example 2
Source File: XmlStaxUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
boolean isTarget(FileObject antScript, String targetName) throws IOException, javax.xml.stream.XMLStreamException {
    InputStream is = antScript.getInputStream();
    XMLStreamReader parser = xmlif.createXMLStreamReader(is);
    boolean found = false;
    int inHeader = 0;
    for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
        if (event == XMLStreamConstants.START_ELEMENT) {
            if ("target".equals(parser.getLocalName()) && targetName.equals(parser.getAttributeValue(null,"name"))) { //NOI18N
                found = true;
                break;
            }
        }
    } // end while
    parser.close();
    is.close();
    return found;
}
 
Example 3
Source File: StAXSourceTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @bug 8152530
 * Verifies that StAXSource handles empty namespace properly. NPE was thrown
 * before the fix.
 * @throws Exception if the test fails
 */
@Test
public final void testStAXSourceWEmptyNS() throws Exception {
    String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        + "<EntityList>\n"
        + "  <Entity xmlns=\"\">\n"
        + "  </Entity>\n"
        + "  <Entity xmlns=\"\">\n"
        + "  </Entity>\n"
        + "</EntityList> ";

    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(xml));
    xsr.nextTag();
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    while (xsr.nextTag() == XMLStreamConstants.START_ELEMENT && xsr.getLocalName().equals("Entity")) {
        StringWriter stringResult = new StringWriter();
        t.transform(new StAXSource(xsr), new StreamResult(stringResult));
        System.out.println("result: \n" + stringResult.toString());
    }
}
 
Example 4
Source File: Jsr173MR1Req5Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testAttributeCountNoNS() {
    XMLInputFactory ifac = XMLInputFactory.newInstance();

    try {
        // Turn off NS awareness to count xmlns as attributes
        ifac.setProperty("javax.xml.stream.isNamespaceAware", Boolean.FALSE);

        XMLStreamReader re = ifac.createXMLStreamReader(getClass().getResource(INPUT_FILE1).toExternalForm(),
                this.getClass().getResourceAsStream(INPUT_FILE1));
        while (re.hasNext()) {
            int event = re.next();
            if (event == XMLStreamConstants.START_ELEMENT) {
                // System.out.println("#attrs = " + re.getAttributeCount());
                Assert.assertTrue(re.getAttributeCount() == 3);
            }
        }
        re.close();
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("Exception occured: " + e.getMessage());
    }
}
 
Example 5
Source File: FreeColXMLReader.java    From freecol with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public int nextTag() throws XMLStreamException {
    int tag = super.nextTag();
    if (tracing) {
        switch (tag) {
        case XMLStreamConstants.START_ELEMENT:
            System.err.println("[" + getLocalName());
            break;
        case XMLStreamConstants.END_ELEMENT:
            System.err.println(getLocalName() + "]");
            break;
        default:
            String val = tagStrings.get(tag);
            System.err.println((val == null) ? "Weird tag: " + tag : val);
            break;
        }
    }
    return tag;
}
 
Example 6
Source File: XMLStreamReaderImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/** Skips any insignificant events (COMMENT and PROCESSING_INSTRUCTION)
 * until a START_ELEMENT or
 * END_ELEMENT is reached. If other than space characters are
 * encountered, an exception is thrown. This method should
 * be used when processing element-only content because
 * the parser is not able to recognize ignorable whitespace if
 * then DTD is missing or not interpreted.
 * @return the event type of the element read
 * @throws XMLStreamException if the current event is not white space
 */
public int nextTag() throws XMLStreamException {

    int eventType = next();
    while((eventType == XMLStreamConstants.CHARACTERS && isWhiteSpace()) // skip whitespace
    || (eventType == XMLStreamConstants.CDATA && isWhiteSpace())
    // skip whitespace
    || eventType == XMLStreamConstants.SPACE
    || eventType == XMLStreamConstants.PROCESSING_INSTRUCTION
    || eventType == XMLStreamConstants.COMMENT
    ) {
        eventType = next();
    }

    if (eventType != XMLStreamConstants.START_ELEMENT && eventType != XMLStreamConstants.END_ELEMENT) {
        throw new XMLStreamException(
                "found: " + getEventTypeString(eventType)
                + ", expected " + getEventTypeString(XMLStreamConstants.START_ELEMENT)
                + " or " + getEventTypeString(XMLStreamConstants.END_ELEMENT),
                getLocation());
    }

    return eventType;
}
 
Example 7
Source File: SurrogatesTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private void readXML(byte[] xmlData, String expectedContent)
        throws Exception {
    InputStream stream = new ByteArrayInputStream(xmlData);
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader xmlReader
            = factory.createXMLStreamReader(stream);
    boolean inTestElement = false;
    StringBuilder sb = new StringBuilder();
    while (xmlReader.hasNext()) {
        String ename;
        switch (xmlReader.getEventType()) {
            case XMLStreamConstants.START_ELEMENT:
                ename = xmlReader.getLocalName();
                if (ename.equals("writeCharactersWithString")
                        || ename.equals("writeCharactersWithArray")) {
                    inTestElement = true;
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                ename = xmlReader.getLocalName();
                if (ename.equals("writeCharactersWithString")
                        || ename.equals("writeCharactersWithArray")) {
                    inTestElement = false;
                    String content = sb.toString();
                    System.out.println(ename + " text:'" + content + "' expected:'" + expectedContent+"'");
                    Assert.assertEquals(content, expectedContent);
                    sb.setLength(0);
                }
                break;
            case XMLStreamConstants.CHARACTERS:
                if (inTestElement) {
                    sb.append(xmlReader.getText());
                }
                break;
        }
        xmlReader.next();
    }
}
 
Example 8
Source File: Util.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public final static String getEventTypeString(int eventType) {
    switch (eventType){
        case XMLStreamConstants.START_ELEMENT:
            return "START_ELEMENT";
        case XMLStreamConstants.END_ELEMENT:
            return "END_ELEMENT";
        case XMLStreamConstants.PROCESSING_INSTRUCTION:
            return "PROCESSING_INSTRUCTION";
        case XMLStreamConstants.CHARACTERS:
            return "CHARACTERS";
        case XMLStreamConstants.COMMENT:
            return "COMMENT";
        case XMLStreamConstants.START_DOCUMENT:
            return "START_DOCUMENT";
        case XMLStreamConstants.END_DOCUMENT:
            return "END_DOCUMENT";
        case XMLStreamConstants.ENTITY_REFERENCE:
            return "ENTITY_REFERENCE";
        case XMLStreamConstants.ATTRIBUTE:
            return "ATTRIBUTE";
        case XMLStreamConstants.DTD:
            return "DTD";
        case XMLStreamConstants.CDATA:
            return "CDATA";
    }
    return "UNKNOWN_EVENT_TYPE";
}
 
Example 9
Source File: StAXSource.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Creates a new instance of a <code>StAXSource</code>
 * by supplying an {@link XMLEventReader}.</p>
 *
 * <p><code>XMLEventReader</code> must be a
 * non-<code>null</code> reference.</p>
 *
 * <p><code>XMLEventReader</code> must be in
 * {@link XMLStreamConstants#START_DOCUMENT} or
 * {@link XMLStreamConstants#START_ELEMENT} state.</p>
 *
 * @param xmlEventReader <code>XMLEventReader</code> used to create
 *   this <code>StAXSource</code>.
 *
 * @throws XMLStreamException If <code>xmlEventReader</code> access
 *   throws an <code>Exception</code>.
 * @throws IllegalArgumentException If <code>xmlEventReader</code> ==
 *   <code>null</code>.
 * @throws IllegalStateException If <code>xmlEventReader</code>
 *   is not in <code>XMLStreamConstants.START_DOCUMENT</code> or
 *   <code>XMLStreamConstants.START_ELEMENT</code> state.
 */
public StAXSource(final XMLEventReader xmlEventReader)
    throws XMLStreamException {

    if (xmlEventReader == null) {
        throw new IllegalArgumentException(
                "StAXSource(XMLEventReader) with XMLEventReader == null");
    }

    // TODO: This is ugly ...
    // there is no way to know the current position(event) of
    // XMLEventReader.  peek() is the only way to know the next event.
    // The next event on the input stream should be
    // XMLStreamConstants.START_DOCUMENT or
    // XMLStreamConstants.START_ELEMENT.
    XMLEvent event = xmlEventReader.peek();
    int eventType = event.getEventType();
    if (eventType != XMLStreamConstants.START_DOCUMENT
            && eventType != XMLStreamConstants.START_ELEMENT) {
        throw new IllegalStateException(
            "StAXSource(XMLEventReader) with XMLEventReader "
            + "not in XMLStreamConstants.START_DOCUMENT or "
            + "XMLStreamConstants.START_ELEMENT state");
    }

    this.xmlEventReader = xmlEventReader;
    systemId = event.getLocation().getSystemId();
}
 
Example 10
Source File: XMLStreamReaderToContentHandler.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the attributes associated with the given START_ELEMENT or ATTRIBUTE
 * StAXevent.
 *
 * @return the StAX attributes converted to an org.xml.sax.Attributes
 */
private Attributes getAttributes() {
    AttributesImpl attrs = new AttributesImpl();

    int eventType = staxStreamReader.getEventType();
    if (eventType != XMLStreamConstants.ATTRIBUTE
        && eventType != XMLStreamConstants.START_ELEMENT) {
        throw new InternalError(
            "getAttributes() attempting to process: " + eventType);
    }

    // in SAX, namespace declarations are not part of attributes by default.
    // (there's a property to control that, but as far as we are concerned
    // we don't use it.) So don't add xmlns:* to attributes.

    // gather non-namespace attrs
    for (int i = 0; i < staxStreamReader.getAttributeCount(); i++) {
        String uri = staxStreamReader.getAttributeNamespace(i);
        if(uri==null)   uri="";
        String localName = staxStreamReader.getAttributeLocalName(i);
        String prefix = staxStreamReader.getAttributePrefix(i);
        String qName;
        if(prefix==null || prefix.length()==0)
            qName = localName;
        else
            qName = prefix + ':' + localName;
        String type = staxStreamReader.getAttributeType(i);
        String value = staxStreamReader.getAttributeValue(i);

        attrs.addAttribute(uri, localName, qName, type, value);
    }

    return attrs;
}
 
Example 11
Source File: AbstractXMLStreamReader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String getPrefix() {
	int eventType = getEventType();
	if (eventType == XMLStreamConstants.START_ELEMENT || eventType == XMLStreamConstants.END_ELEMENT) {
		return getName().getPrefix();
	}
	else {
		throw new IllegalStateException("parser must be on START_ELEMENT or END_ELEMENT state");
	}
}
 
Example 12
Source File: StreamSOAPCodec.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static final Message decode(SOAPVersion soapVersion, XMLStreamReader reader, @NotNull AttachmentSet attachmentSet) {
    // Move to soap:Envelope and verify
    if(reader.getEventType()!=XMLStreamConstants.START_ELEMENT)
        XMLStreamReaderUtil.nextElementContent(reader);
    XMLStreamReaderUtil.verifyReaderState(reader,XMLStreamConstants.START_ELEMENT);
    if (SOAP_ENVELOPE.equals(reader.getLocalName()) && !soapVersion.nsUri.equals(reader.getNamespaceURI())) {
        throw new VersionMismatchException(soapVersion, soapVersion.nsUri, reader.getNamespaceURI());
    }
    XMLStreamReaderUtil.verifyTag(reader, soapVersion.nsUri, SOAP_ENVELOPE);
    return new StreamMessage(soapVersion, reader, attachmentSet);
}
 
Example 13
Source File: XMLStreamReaderImpl.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/** Reads the content of a text-only element. Precondition:
 * the current event is START_ELEMENT. Postcondition:
 * The current event is the corresponding END_ELEMENT.
 * @throws XMLStreamException if the current event is not a START_ELEMENT or if
 * a non text element is encountered
 */
public String getElementText() throws XMLStreamException {

    if(getEventType() != XMLStreamConstants.START_ELEMENT) {
        throw new XMLStreamException(
        "parser must be on START_ELEMENT to read next text", getLocation());
    }
    int eventType = next();
    StringBuffer content = new StringBuffer();
    while(eventType != XMLStreamConstants.END_ELEMENT ) {
        if(eventType == XMLStreamConstants.CHARACTERS
        || eventType == XMLStreamConstants.CDATA
        || eventType == XMLStreamConstants.SPACE
        || eventType == XMLStreamConstants.ENTITY_REFERENCE) {
            content.append(getText());
        } else if(eventType == XMLStreamConstants.PROCESSING_INSTRUCTION
        || eventType == XMLStreamConstants.COMMENT) {
            // skipping
        } else if(eventType == XMLStreamConstants.END_DOCUMENT) {
            throw new XMLStreamException("unexpected end of document when reading element text content");
        } else if(eventType == XMLStreamConstants.START_ELEMENT) {
            throw new XMLStreamException(
            "elementGetText() function expects text only elment but START_ELEMENT was encountered.", getLocation());
        } else {
            throw new XMLStreamException(
            "Unexpected event type "+ eventType, getLocation());
        }
        eventType = next();
    }
    return content.toString();
}
 
Example 14
Source File: UnmarshallerImpl.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public Object unmarshal0(XMLStreamReader reader, JaxBeanInfo expectedType) throws JAXBException {
    if (reader == null) {
        throw new IllegalArgumentException(
            Messages.format(Messages.NULL_READER));
    }

    int eventType = reader.getEventType();
    if (eventType != XMLStreamConstants.START_ELEMENT
        && eventType != XMLStreamConstants.START_DOCUMENT) {
        // TODO: convert eventType into event name
        throw new IllegalStateException(
            Messages.format(Messages.ILLEGAL_READER_STATE,eventType));
    }

    XmlVisitor h = createUnmarshallerHandler(null,false,expectedType);
    StAXConnector connector=StAXStreamConnector.create(reader,h);

    try {
        connector.bridge();
    } catch (XMLStreamException e) {
        throw handleStreamException(e);
    }

    Object retVal = h.getContext().getResult();
    h.getContext().clearResult();
    return retVal;
}
 
Example 15
Source File: StAXSchemaParser.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public void parse(XMLEventReader input) throws XMLStreamException, XNIException {
    XMLEvent currentEvent = input.peek();
    if (currentEvent != null) {
        int eventType = currentEvent.getEventType();
        if (eventType != XMLStreamConstants.START_DOCUMENT &&
            eventType != XMLStreamConstants.START_ELEMENT) {
            throw new XMLStreamException();
        }
        fLocationWrapper.setLocation(currentEvent.getLocation());
        fSchemaDOMParser.startDocument(fLocationWrapper, null, fNamespaceContext, null);
        loop: while (input.hasNext()) {
            currentEvent = input.nextEvent();
            eventType = currentEvent.getEventType();
            switch (eventType) {
            case XMLStreamConstants.START_ELEMENT:
                ++fDepth;
                StartElement start = currentEvent.asStartElement();
                fillQName(fElementQName, start.getName());
                fLocationWrapper.setLocation(start.getLocation());
                fNamespaceContext.setNamespaceContext(start.getNamespaceContext());
                fillXMLAttributes(start);
                fillDeclaredPrefixes(start);
                addNamespaceDeclarations();
                fNamespaceContext.pushContext();
                fSchemaDOMParser.startElement(fElementQName, fAttributes, null);
                break;
            case XMLStreamConstants.END_ELEMENT:
                EndElement end = currentEvent.asEndElement();
                fillQName(fElementQName, end.getName());
                fillDeclaredPrefixes(end);
                fLocationWrapper.setLocation(end.getLocation());
                fSchemaDOMParser.endElement(fElementQName, null);
                fNamespaceContext.popContext();
                --fDepth;
                if (fDepth <= 0) {
                    break loop;
                }
                break;
            case XMLStreamConstants.CHARACTERS:
                sendCharactersToSchemaParser(currentEvent.asCharacters().getData(), false);
                break;
            case XMLStreamConstants.SPACE:
                sendCharactersToSchemaParser(currentEvent.asCharacters().getData(), true);
                break;
            case XMLStreamConstants.CDATA:
                fSchemaDOMParser.startCDATA(null);
                sendCharactersToSchemaParser(currentEvent.asCharacters().getData(), false);
                fSchemaDOMParser.endCDATA(null);
                break;
            case XMLStreamConstants.PROCESSING_INSTRUCTION:
                ProcessingInstruction pi = (ProcessingInstruction)currentEvent;
                fillProcessingInstruction(pi.getData());
                fSchemaDOMParser.processingInstruction(pi.getTarget(), fTempString, null);
                break;
            case XMLStreamConstants.DTD:
                /* There shouldn't be a DTD in the schema */
                break;
            case XMLStreamConstants.ENTITY_REFERENCE:
                /* Not needed for schemas */
                break;
            case XMLStreamConstants.COMMENT:
                /* No point in sending comments */
                break;
            case XMLStreamConstants.START_DOCUMENT:
                fDepth++;
                /* We automatically call startDocument before the loop */
                break;
            case XMLStreamConstants.END_DOCUMENT:
                /* We automatically call endDocument after the loop */
                break;
            }
        }
        fLocationWrapper.setLocation(null);
        fNamespaceContext.setNamespaceContext(null);
        fSchemaDOMParser.endDocument(null);
    }
}
 
Example 16
Source File: XMLStreamWriterImpl.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
/**
 *
 * @param uri
 * @return
 */
private void correctPrefix(QName attr, int type) {
    String tmpPrefix;
    String prefix;
    String uri;
    prefix = attr.prefix;
    uri = attr.uri;
    boolean isSpecialCaseURI = false;

    if (prefix == null || prefix.equals(XMLConstants.DEFAULT_NS_PREFIX)) {
        if (uri == null) {
            return;
        }

        if (XMLConstants.DEFAULT_NS_PREFIX.equals(prefix) && uri.equals(XMLConstants.DEFAULT_NS_PREFIX))
            return;

        uri = fSymbolTable.addSymbol(uri);

        QName decl;

        for (int i = 0; i < fNamespaceDecls.size(); i++) {
            decl = fNamespaceDecls.get(i);

            if ((decl != null) && (decl.uri.equals(attr.uri))) {
                attr.prefix = decl.prefix;

                return;
            }
        }

        tmpPrefix = fNamespaceContext.getPrefix(uri);

        if (XMLConstants.DEFAULT_NS_PREFIX.equals(tmpPrefix)) {
            if (type == XMLStreamConstants.START_ELEMENT) {
                return;
            }
            else if (type == XMLStreamConstants.ATTRIBUTE) {
                //the uri happens to be the same as that of the default namespace
                tmpPrefix = getAttrPrefix(uri);
                isSpecialCaseURI = true;
            }
        }

        if (tmpPrefix == null) {
            StringBuilder genPrefix = new StringBuilder("zdef");

            for (int i = 0; i < 1; i++) {
                genPrefix.append(fPrefixGen.nextInt());
            }

            prefix = genPrefix.toString();
            prefix = fSymbolTable.addSymbol(prefix);
        } else {
            prefix = fSymbolTable.addSymbol(tmpPrefix);
        }

        if (tmpPrefix == null) {
            if (isSpecialCaseURI) {
                addAttrNamespace(prefix, uri);
            } else {
                QName qname = new QName();
                qname.setValues(prefix, XMLConstants.XMLNS_ATTRIBUTE, null, uri);
                fNamespaceDecls.add(qname);
                fInternalNamespaceContext.declarePrefix(fSymbolTable.addSymbol(
                    prefix), uri);
            }
        }
    }

    attr.prefix = prefix;
}
 
Example 17
Source File: StAXStreamConnector.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public void bridge() throws XMLStreamException {

        try {
            // remembers the nest level of elements to know when we are done.
            int depth=0;

            // if the parser is at the start tag, proceed to the first element
            int event = staxStreamReader.getEventType();
            if(event == XMLStreamConstants.START_DOCUMENT) {
                // nextTag doesn't correctly handle DTDs
                while( !staxStreamReader.isStartElement() )
                    event = staxStreamReader.next();
            }


            if( event!=XMLStreamConstants.START_ELEMENT)
                throw new IllegalStateException("The current event is not START_ELEMENT\n but " + event);

            handleStartDocument(staxStreamReader.getNamespaceContext());

            OUTER:
            while(true) {
                // These are all of the events listed in the javadoc for
                // XMLEvent.
                // The spec only really describes 11 of them.
                switch (event) {
                    case XMLStreamConstants.START_ELEMENT :
                        handleStartElement();
                        depth++;
                        break;
                    case XMLStreamConstants.END_ELEMENT :
                        depth--;
                        handleEndElement();
                        if(depth==0)    break OUTER;
                        break;
                    case XMLStreamConstants.CHARACTERS :
                    case XMLStreamConstants.CDATA :
                    case XMLStreamConstants.SPACE :
                        handleCharacters();
                        break;
                    // otherwise simply ignore
                }

                event=staxStreamReader.next();
            }

            staxStreamReader.next();    // move beyond the end tag.

            handleEndDocument();
        } catch (SAXException e) {
            throw new XMLStreamException(e);
        }
    }
 
Example 18
Source File: StaxEventXMLReader.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
protected void parseInternal() throws SAXException, XMLStreamException {
	boolean documentStarted = false;
	boolean documentEnded = false;
	int elementDepth = 0;
	while (this.reader.hasNext() && elementDepth >= 0) {
		XMLEvent event = this.reader.nextEvent();
		if (!event.isStartDocument() && !event.isEndDocument() && !documentStarted) {
			handleStartDocument(event);
			documentStarted = true;
		}
		switch (event.getEventType()) {
			case XMLStreamConstants.START_DOCUMENT:
				handleStartDocument(event);
				documentStarted = true;
				break;
			case XMLStreamConstants.START_ELEMENT:
				elementDepth++;
				handleStartElement(event.asStartElement());
				break;
			case XMLStreamConstants.END_ELEMENT:
				elementDepth--;
				if (elementDepth >= 0) {
					handleEndElement(event.asEndElement());
				}
				break;
			case XMLStreamConstants.PROCESSING_INSTRUCTION:
				handleProcessingInstruction((ProcessingInstruction) event);
				break;
			case XMLStreamConstants.CHARACTERS:
			case XMLStreamConstants.SPACE:
			case XMLStreamConstants.CDATA:
				handleCharacters(event.asCharacters());
				break;
			case XMLStreamConstants.END_DOCUMENT:
				handleEndDocument();
				documentEnded = true;
				break;
			case XMLStreamConstants.NOTATION_DECLARATION:
				handleNotationDeclaration((NotationDeclaration) event);
				break;
			case XMLStreamConstants.ENTITY_DECLARATION:
				handleEntityDeclaration((EntityDeclaration) event);
				break;
			case XMLStreamConstants.COMMENT:
				handleComment((Comment) event);
				break;
			case XMLStreamConstants.DTD:
				handleDtd((DTD) event);
				break;
			case XMLStreamConstants.ENTITY_REFERENCE:
				handleEntityReference((EntityReference) event);
				break;
		}
	}
	if (documentStarted && !documentEnded) {
		handleEndDocument();
	}

}
 
Example 19
Source File: FastInfosetConnector.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public void bridge() throws XMLStreamException {
    try {
        // remembers the nest level of elements to know when we are done.
        int depth=0;

        // if the parser is at the start tag, proceed to the first element
        int event = fastInfosetStreamReader.getEventType();
        if(event == XMLStreamConstants.START_DOCUMENT) {
            // nextTag doesn't correctly handle DTDs
            while( !fastInfosetStreamReader.isStartElement() )
                event = fastInfosetStreamReader.next();
        }


        if( event!=XMLStreamConstants.START_ELEMENT)
            throw new IllegalStateException("The current event is not START_ELEMENT\n but " + event);

        // TODO: we don't have to rely on this hack --- we can just emulate
        // start/end prefix mappings. But for now, I'll rely on this hack.
        handleStartDocument(fastInfosetStreamReader.getNamespaceContext());

        OUTER:
        while(true) {
            // These are all of the events listed in the javadoc for
            // XMLEvent.
            // The spec only really describes 11 of them.
            switch (event) {
                case XMLStreamConstants.START_ELEMENT :
                    handleStartElement();
                    depth++;
                    break;
                case XMLStreamConstants.END_ELEMENT :
                    depth--;
                    handleEndElement();
                    if(depth==0)    break OUTER;
                    break;
                case XMLStreamConstants.CHARACTERS :
                case XMLStreamConstants.CDATA :
                case XMLStreamConstants.SPACE :
                    if (predictor.expectText()) {
                        // Peek at the next event to see if there are
                        // fragmented characters
                        event = fastInfosetStreamReader.peekNext();
                        if (event == XMLStreamConstants.END_ELEMENT)
                            processNonIgnorableText();
                        else if (event == XMLStreamConstants.START_ELEMENT)
                            processIgnorableText();
                        else
                            handleFragmentedCharacters();
                    }
                    break;
                // otherwise simply ignore
            }

            event=fastInfosetStreamReader.next();
        }

        fastInfosetStreamReader.next();    // move beyond the end tag.

        handleEndDocument();
    } catch (SAXException e) {
        throw new XMLStreamException(e);
    }
}
 
Example 20
Source File: StAXSource.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * <p>Creates a new instance of a <code>StAXSource</code>
 * by supplying an {@link XMLStreamReader}.</p>
 *
 * <p><code>XMLStreamReader</code> must be a
 * non-<code>null</code> reference.</p>
 *
 * <p><code>XMLStreamReader</code> must be in
 * {@link XMLStreamConstants#START_DOCUMENT} or
 * {@link XMLStreamConstants#START_ELEMENT} state.</p>
 *
 * @param xmlStreamReader <code>XMLStreamReader</code> used to create
 *   this <code>StAXSource</code>.
 *
 * @throws IllegalArgumentException If <code>xmlStreamReader</code> ==
 *   <code>null</code>.
 * @throws IllegalStateException If <code>xmlStreamReader</code>
 *   is not in <code>XMLStreamConstants.START_DOCUMENT</code> or
 *   <code>XMLStreamConstants.START_ELEMENT</code> state.
 */
public StAXSource(final XMLStreamReader xmlStreamReader) {

    if (xmlStreamReader == null) {
        throw new IllegalArgumentException(
                "StAXSource(XMLStreamReader) with XMLStreamReader == null");
    }

    int eventType = xmlStreamReader.getEventType();
    if (eventType != XMLStreamConstants.START_DOCUMENT
            && eventType != XMLStreamConstants.START_ELEMENT) {
        throw new IllegalStateException(
                "StAXSource(XMLStreamReader) with XMLStreamReader"
                + "not in XMLStreamConstants.START_DOCUMENT or "
                + "XMLStreamConstants.START_ELEMENT state");
    }

    this.xmlStreamReader = xmlStreamReader;
    systemId = xmlStreamReader.getLocation().getSystemId();
}