Java Code Examples for javax.xml.stream.XMLStreamConstants

The following examples show how to use javax.xml.stream.XMLStreamConstants. These examples are extracted from open source projects. 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 Project: lams   Source File: BaseXMLEventReader.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public final XMLEvent nextTag() throws XMLStreamException {
	XMLEvent event = this.nextEvent();
	while ((event.isCharacters() && event.asCharacters().isWhiteSpace())
			|| event.isProcessingInstruction()
			|| event.getEventType() == XMLStreamConstants.COMMENT) {

		event = this.nextEvent();
	}

	if (!event.isStartElement()  && event.isEndElement()) {
		throw new XMLStreamException("Unexpected event type '" + XMLStreamConstantsUtils.getEventName(event.getEventType()) + "' encountered. Found event: " + event, event.getLocation());
	}

	return event;
}
 
Example 2
Source Project: galleon   Source File: ConfigXml.java    License: 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 3
Source Project: galleon   Source File: FeaturePackXmlParser20.java    License: Apache License 2.0 6 votes vote down vote up
private static void readTransitive(XMLExtendedStreamReader reader, FeaturePackDepsConfigBuilder<?> 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.getLocalName());
                switch (element) {
                    case DEPENDENCY:
                        ProvisioningXmlParser30.readTransitiveFeaturePackDep(reader, builder);
                        break;
                    default:
                        throw ParsingUtils.unexpectedContent(reader);
                }
                break;
            }
            default: {
                throw ParsingUtils.unexpectedContent(reader);
            }
        }
    }
    throw ParsingUtils.endOfDocument(reader.getLocation());
}
 
Example 4
Source Project: openjdk-jdk9   Source File: Bug6481678.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testReadingNamespace() {
    is = new java.io.ByteArrayInputStream(getXML().getBytes());
    try {
        XMLStreamReader sr = factory.createFilteredReader(factory.createXMLStreamReader(is), (StreamFilter) filter);

        while (sr.hasNext()) {
            int eventType = sr.getEventType();
            if (eventType == XMLStreamConstants.START_ELEMENT) {
                if (sr.getLocalName().equals(rootElement)) {
                    Assert.assertTrue(sr.getNamespacePrefix(0).equals(prefixApple) && sr.getNamespaceURI(0).equals(namespaceURIApple));
                }
            }
            eventType = sr.next();
        }
    } catch (Exception ex) {
        Assert.fail("Exception: " + ex.getMessage());
    }
}
 
Example 5
Source Project: staedi   Source File: SchemaReaderBase.java    License: Apache License 2.0 6 votes vote down vote up
List<Integer> readSyntaxPositions(XMLStreamReader reader) {
    final List<Integer> positions = new ArrayList<>(5);
    boolean endOfSyntax = false;

    while (!endOfSyntax) {
        final int event = nextTag(reader, "reading syntax positions");
        final QName element = reader.getName();

        if (event == XMLStreamConstants.START_ELEMENT) {
            if (element.equals(qnPosition)) {
                final String position = getElementText(reader, "syntax position");

                try {
                    positions.add(Integer.parseInt(position));
                } catch (@SuppressWarnings("unused") NumberFormatException e) {
                    throw schemaException("invalid position [" + position + ']', reader);
                }
            }
        } else {
            endOfSyntax = true;
        }
    }

    return positions;
}
 
Example 6
/**
 * Returns the accumulated text of an event type.
 *
 * @param streamReader the XMLStreamReader
 * @param type the type of event requested
 * @return the text of the accumulated text for the request type
 * @throws XMLStreamException
 */
String getText(XMLStreamReader streamReader, int type) throws XMLStreamException {
    StringBuilder text = new StringBuilder();
    StringBuilder entityRef = new StringBuilder();

    while(streamReader.hasNext()){
        int eventType = streamReader.next();
        switch (eventType) {
            case XMLStreamConstants.START_ELEMENT:
                break;
            case XMLStreamConstants.CHARACTERS:
                text.append(streamReader.getText());
                break;
            case XMLStreamConstants.ENTITY_REFERENCE:
                entityRef.append(streamReader.getText());
                break;
        }
    }
    if (type == XMLStreamConstants.CHARACTERS) {
        return text.toString();
    } else {
        return entityRef.toString();
    }
}
 
Example 7
Source Project: ADT_Frontend   Source File: ApackGitManifestDeserializer.java    License: MIT License 6 votes vote down vote up
public IApackManifest deserializeApackManifest(XMLStreamReader xmlReader) throws XMLStreamException {
	ApackManifest apackManifest = new ApackManifest();

	while (xmlReader.hasNext()) {
		int next = xmlReader.next();
		switch (next) {
		case XMLStreamConstants.START_ELEMENT:
			switch (xmlReader.getLocalName()) {
			case "descriptor": //$NON-NLS-1$
				apackManifest.setDescriptor(deserializeDescriptor(xmlReader));
				break;
			default:
				break;
			}
			break;
		default:
			break;
		}
	}

	return apackManifest;
}
 
Example 8
/**
 * CR 6631264 / sjsxp Issue 45:
 * https://sjsxp.dev.java.net/issues/show_bug.cgi?id=45
 * XMLStreamReader.hasName() should return false for ENTITY_REFERENCE
 */
@Test
public void testHasNameOnEntityEvent() throws Exception {
    XMLInputFactory xif = XMLInputFactory.newInstance();
    xif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
    XMLStreamReader r = xif.createXMLStreamReader(
            this.getClass().getResourceAsStream("ExternalDTD.xml"));
    while (r.next() != XMLStreamConstants.ENTITY_REFERENCE) {
        System.out.println("event type: " + r.getEventType());
        continue;
    }
    if (r.hasName()) {
        System.out.println("hasName returned true on ENTITY_REFERENCE event.");
    }
    Assert.assertFalse(r.hasName()); // fails
}
 
Example 9
@Test
public void testPITargetAndData() {
    try {
        XMLInputFactory xif = XMLInputFactory.newInstance();
        String PITarget = "soffice";
        String PIData = "WebservicesArchitecture";
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<?" + PITarget + " " + PIData + "?>" + "<foo></foo>";
        // System.out.println("XML = " + xml) ;
        InputStream is = new java.io.ByteArrayInputStream(xml.getBytes());
        XMLStreamReader sr = xif.createXMLStreamReader(is);
        while (sr.hasNext()) {
            int eventType = sr.next();
            if (eventType == XMLStreamConstants.PROCESSING_INSTRUCTION) {
                String target = sr.getPITarget();
                String data = sr.getPIData();
                Assert.assertTrue(target.equals(PITarget) && data.equals(PIData));
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
Example 10
Source Project: jdk8u60   Source File: StAXSource.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a new {@link javax.xml.transform.Source} for the given
 * {@link XMLStreamReader}.
 *
 * The XMLStreamReader must be pointing at either a
 * {@link javax.xml.stream.XMLStreamConstants#START_DOCUMENT} or
 * {@link javax.xml.stream.XMLStreamConstants#START_ELEMENT} event.
 *
 * @param reader XMLStreamReader that will be exposed as a Source
 * @param eagerQuit if true, when the conversion is completed, leave the cursor to the last
 *                  event that was fired (such as end element)
 * @param inscope inscope Namespaces
 *                array of the even length of the form { prefix0, uri0, prefix1, uri1, ... }
 * @throws IllegalArgumentException iff the reader is null
 * @throws IllegalStateException iff the reader is not pointing at either a
 * START_DOCUMENT or START_ELEMENT event
 */
public StAXSource(XMLStreamReader reader, boolean eagerQuit, @NotNull String[] inscope) {
    if( reader == null )
        throw new IllegalArgumentException();
    this.staxReader = reader;

    int eventType = reader.getEventType();
    if (!(eventType == XMLStreamConstants.START_DOCUMENT)
        && !(eventType == XMLStreamConstants.START_ELEMENT)) {
        throw new IllegalStateException();
    }

    this.reader = new XMLStreamReaderToContentHandler(reader,repeater,eagerQuit,false,inscope);

    super.setXMLReader(pseudoParser);
    // pass a dummy InputSource. We don't care
    super.setInputSource(new InputSource());
}
 
Example 11
Source Project: galleon   Source File: MavenProducerXmlParser10.java    License: Apache License 2.0 6 votes vote down vote up
private void readFrequencies(XMLExtendedStreamReader reader, MavenParsedProducerCallbackHandler 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());
                switch (element) {
                    case FREQUENCY:
                        readFrequency(reader, builder);
                        break;
                    default:
                        throw ParsingUtils.unexpectedContent(reader);
                }
                break;
            }
            default: {
                throw ParsingUtils.unexpectedContent(reader);
            }
        }
    }
    throw ParsingUtils.endOfDocument(reader.getLocation());
}
 
Example 12
protected List<NotationDeclaration> getNotationDecls() {
    if (fEventType == XMLStreamConstants.DTD) {
        if (fScanner.fDTDScanner == null) {
            return null;
        }
        DTDGrammar grammar = ((XMLDTDScannerImpl) (fScanner.fDTDScanner)).getGrammar();
        if (grammar == null) {
            return null;
        }
        List<XMLNotationDecl> notations = grammar.getNotationDecls();
        ArrayList<NotationDeclaration> list = new ArrayList<>();
        for (XMLNotationDecl notation : notations) {
            if (notation != null) {
                list.add(new NotationDeclarationImpl(notation));
            }
        }
        return list;
    }
    return null;
}
 
Example 13
/**
 * 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 14
Source Project: jdk8u60   Source File: XMLStreamReaderImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected List getNotationDecls(){
    if(fEventType == XMLStreamConstants.DTD){
        if(fScanner.fDTDScanner == null) return null;
        DTDGrammar grammar = ((XMLDTDScannerImpl)(fScanner.fDTDScanner)).getGrammar();
        if(grammar == null) return null;
        List notations = grammar.getNotationDecls();

        Iterator it = notations.iterator();
        ArrayList list = new ArrayList();
        while(it.hasNext()){
            XMLNotationDecl ni = (XMLNotationDecl)it.next();
            if(ni!= null){
                list.add(new NotationDeclarationImpl(ni));
            }
        }
        return list;
    }
    return null;
}
 
Example 15
/** 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 16
Source Project: galleon   Source File: FeaturePackXmlParser20.java    License: Apache License 2.0 6 votes vote down vote up
private static void parsePlugins(XMLExtendedStreamReader reader, FeaturePackSpec.Builder fpBuilder) 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 PLUGIN:
                        parsePlugin(reader, fpBuilder);
                        break;
                    default:
                        throw ParsingUtils.unexpectedContent(reader);
                }
                break;
            }
            default: {
                throw ParsingUtils.unexpectedContent(reader);
            }
        }
    }
    throw ParsingUtils.endOfDocument(reader.getLocation());
}
 
Example 17
Source Project: openjdk-jdk9   Source File: NamespaceTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testRootElementNamespace() {
    try {
        XMLInputFactory xif = XMLInputFactory.newInstance();
        xif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        InputStream is = new java.io.ByteArrayInputStream(getXML().getBytes());
        XMLStreamReader sr = xif.createXMLStreamReader(is);
        while (sr.hasNext()) {
            int eventType = sr.next();
            if (eventType == XMLStreamConstants.START_ELEMENT) {
                if (sr.getLocalName().equals(rootElement)) {
                    Assert.assertTrue(sr.getNamespacePrefix(0).equals(prefix) && sr.getNamespaceURI(0).equals(namespaceURI));
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
Example 18
Source Project: openjdk-jdk9   Source File: Bug6481678.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testNamespaceContext() {
    is = new java.io.ByteArrayInputStream(getXML().getBytes());
    try {
        XMLStreamReader sr = factory.createFilteredReader(factory.createXMLStreamReader(is), (StreamFilter) filter);
        while (sr.hasNext()) {
            int eventType = sr.next();
            if (eventType == XMLStreamConstants.START_ELEMENT) {
                if (sr.getLocalName().equals(childElement)) {
                    NamespaceContext context = sr.getNamespaceContext();
                    Assert.assertTrue(context.getPrefix(namespaceURIApple).equals(prefixApple));
                }
            }
        }
    } catch (Exception ex) {
        Assert.fail("Exception: " + ex.getMessage());
    }
}
 
Example 19
Source Project: spring-analysis-note   Source File: AbstractXMLStreamReader.java    License: MIT License 5 votes vote down vote up
@Override
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();
	StringBuilder builder = new StringBuilder();
	while (eventType != XMLStreamConstants.END_ELEMENT) {
		if (eventType == XMLStreamConstants.CHARACTERS || eventType == XMLStreamConstants.CDATA ||
				eventType == XMLStreamConstants.SPACE || eventType == XMLStreamConstants.ENTITY_REFERENCE) {
			builder.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",
					getLocation());
		}
		else if (eventType == XMLStreamConstants.START_ELEMENT) {
			throw new XMLStreamException("Element text content may not contain START_ELEMENT", getLocation());
		}
		else {
			throw new XMLStreamException("Unexpected event type " + eventType, getLocation());
		}
		eventType = next();
	}
	return builder.toString();
}
 
Example 20
Source Project: jdk8u60   Source File: XMLStreamReaderImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 *  Returns true if the cursor points to a character data event that consists of all whitespace
 *  Application calling this method needs to cache the value and avoid calling this method again
 *  for the same event.
 * @return
 */
public boolean isWhiteSpace() {
    if(isCharacters() || (fEventType == XMLStreamConstants.CDATA)){
        char [] ch = this.getTextCharacters();
        final int start = this.getTextStart();
        final int end = start + this.getTextLength();
        for (int i = start; i < end; i++){
            if(!XMLChar.isSpace(ch[i])){
                return false;
            }
        }
        return true;
    }
    return false;
}
 
Example 21
Source Project: spring-analysis-note   Source File: AbstractXMLStreamReader.java    License: MIT License 5 votes vote down vote up
@Override
public boolean hasText() {
	int eventType = getEventType();
	return (eventType == XMLStreamConstants.SPACE || eventType == XMLStreamConstants.CHARACTERS ||
			eventType == XMLStreamConstants.COMMENT || eventType == XMLStreamConstants.CDATA ||
			eventType == XMLStreamConstants.ENTITY_REFERENCE);
}
 
Example 22
Source Project: java-technology-stack   Source File: AbstractXMLStreamReader.java    License: MIT License 5 votes vote down vote up
@Override
public int nextTag() throws XMLStreamException {
	int eventType = next();
	while (eventType == XMLStreamConstants.CHARACTERS && isWhiteSpace() ||
			eventType == XMLStreamConstants.CDATA && isWhiteSpace() || eventType == XMLStreamConstants.SPACE ||
			eventType == XMLStreamConstants.PROCESSING_INSTRUCTION || eventType == XMLStreamConstants.COMMENT) {
		eventType = next();
	}
	if (eventType != XMLStreamConstants.START_ELEMENT && eventType != XMLStreamConstants.END_ELEMENT) {
		throw new XMLStreamException("expected start or end tag", getLocation());
	}
	return eventType;
}
 
Example 23
Source Project: lams   Source File: XMLStreamConstantsUtils.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the human readable event name for the numeric event id
 */
public static String getEventName(int eventId) {
	switch (eventId) {
		case XMLStreamConstants.START_ELEMENT:
			return "StartElementEvent";
		case XMLStreamConstants.END_ELEMENT:
			return "EndElementEvent";
		case XMLStreamConstants.PROCESSING_INSTRUCTION:
			return "ProcessingInstructionEvent";
		case XMLStreamConstants.CHARACTERS:
			return "CharacterEvent";
		case XMLStreamConstants.COMMENT:
			return "CommentEvent";
		case XMLStreamConstants.START_DOCUMENT:
			return "StartDocumentEvent";
		case XMLStreamConstants.END_DOCUMENT:
			return "EndDocumentEvent";
		case XMLStreamConstants.ENTITY_REFERENCE:
			return "EntityReferenceEvent";
		case XMLStreamConstants.ATTRIBUTE:
			return "AttributeBase";
		case XMLStreamConstants.DTD:
			return "DTDEvent";
		case XMLStreamConstants.CDATA:
			return "CDATA";
	}
	return "UNKNOWN_EVENT_TYPE";
}
 
Example 24
Source Project: spring-analysis-note   Source File: AbstractXMLStreamReader.java    License: MIT License 5 votes vote down vote up
@Override
public int nextTag() throws XMLStreamException {
	int eventType = next();
	while (eventType == XMLStreamConstants.CHARACTERS && isWhiteSpace() ||
			eventType == XMLStreamConstants.CDATA && isWhiteSpace() || eventType == XMLStreamConstants.SPACE ||
			eventType == XMLStreamConstants.PROCESSING_INSTRUCTION || eventType == XMLStreamConstants.COMMENT) {
		eventType = next();
	}
	if (eventType != XMLStreamConstants.START_ELEMENT && eventType != XMLStreamConstants.END_ELEMENT) {
		throw new XMLStreamException("expected start or end tag", getLocation());
	}
	return eventType;
}
 
Example 25
/**
 *  Returns true if the cursor points to a character data event that consists of all whitespace
 *  Application calling this method needs to cache the value and avoid calling this method again
 *  for the same event.
 * @return
 */
public boolean isWhiteSpace() {
    if(isCharacters() || (fEventType == XMLStreamConstants.CDATA)){
        char [] ch = this.getTextCharacters();
        final int start = this.getTextStart();
        final int end = start + this.getTextLength();
        for (int i = start; i < end; i++){
            if(!XMLChar.isSpace(ch[i])){
                return false;
            }
        }
        return true;
    }
    return false;
}
 
Example 26
Source Project: Bytecoder   Source File: StAXSource.java    License: Apache License 2.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 27
@Override
public String getPayloadAttributeValue(QName attName) {
    if (lazySource.isPayloadStreamReader()) {
        XMLStreamReader reader = lazySource.readPayload();
        if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) {
            return reader.getAttributeValue(attName.getNamespaceURI(), attName.getLocalPart());
        }
    }
    return null;
}
 
Example 28
Source Project: powsybl-core   Source File: XmlUtil.java    License: Mozilla Public License 2.0 5 votes vote down vote up
public static String readUntilEndElementWithDepth(String endElementName, XMLStreamReader reader, XmlEventHandlerWithDepth eventHandler) throws XMLStreamException {
    Objects.requireNonNull(endElementName);
    Objects.requireNonNull(reader);

    String text = null;
    int event;
    int depth = 0;
    while (!((event = reader.next()) == XMLStreamConstants.END_ELEMENT
            && reader.getLocalName().equals(endElementName))) {
        text = null;
        switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                if (eventHandler != null) {
                    String startLocalName = reader.getLocalName();
                    eventHandler.onStartElement(depth);
                    // if handler has already consumed end element we must decrease the depth
                    if (reader.getEventType() == XMLStreamConstants.END_ELEMENT && reader.getLocalName().equals(startLocalName)) {
                        depth--;
                    }
                }
                depth++;
                break;

            case XMLStreamConstants.END_ELEMENT:
                depth--;
                break;

            case XMLStreamConstants.CHARACTERS:
                text = reader.getText();
                break;

            default:
                break;
        }
    }
    return text;
}
 
Example 29
Source Project: jdk1.8-source-analysis   Source File: StAXStream2SAX.java    License: Apache License 2.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 30
Source Project: jdk8u60   Source File: EPRHeader.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Nullable
public String getAttribute(@NotNull String nsUri, @NotNull String localName) {
    try {
        XMLStreamReader sr = epr.read("EndpointReference"/*doesn't matter*/);
        while(sr.getEventType()!= XMLStreamConstants.START_ELEMENT)
            sr.next();

        return sr.getAttributeValue(nsUri,localName);
    } catch (XMLStreamException e) {
        // since we are reading from buffer, this can't happen.
        throw new AssertionError(e);
    }
}