Java Code Examples for javax.xml.stream.events.XMLEvent#getEventType()

The following examples show how to use javax.xml.stream.events.XMLEvent#getEventType() . 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: StaxUnmarshallerContext.java    From ibm-cos-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the text contents of the current element being parsed.
 *
 * @return The text contents of the current element being parsed.
 * @throws XMLStreamException
 */
public String readText() throws XMLStreamException {
    if (isInsideResponseHeader()) {
        return getHeader(currentHeader);
    }
    if (currentEvent.isAttribute()) {
        Attribute attribute = (Attribute)currentEvent;
        return attribute.getValue();
    }

    StringBuilder sb = new StringBuilder();
    while (true) {
        XMLEvent event = eventReader.peek();
        if (event.getEventType() == XMLStreamConstants.CHARACTERS) {
            eventReader.nextEvent();
            sb.append(event.asCharacters().getData());
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT) {
            return sb.toString();
        } else {
            throw new RuntimeException("Encountered unexpected event: " + event.toString());
        }
    }
}
 
Example 2
Source File: FileSourceXML.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Check is an event has an expected type and name.
 *
 * @param e    event to check
 * @param type expected type
 * @param name expected name
 * @return true is type and name are valid
 */
protected boolean isEvent(XMLEvent e, int type, String name) {
    boolean valid = e.getEventType() == type;

    if (valid) {
        switch (type) {
            case START_ELEMENT:
                valid = e.asStartElement().getName().getLocalPart()
                        .equals(name);
                break;
            case END_ELEMENT:
                valid = e.asEndElement().getName().getLocalPart().equals(name);
                break;
            case ATTRIBUTE:
                valid = ((Attribute) e).getName().getLocalPart().equals(name);
                break;
            case CHARACTERS:
            case NAMESPACE:
            case PROCESSING_INSTRUCTION:
            case COMMENT:
            case START_DOCUMENT:
            case END_DOCUMENT:
            case DTD:
        }
    }

    return valid;
}
 
Example 3
Source File: XMLUtilities.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void addAtomElement(
    final InputStream content,
    final XMLEventWriter writer)
    throws Exception {
  final XMLEventReader reader = getEventReader(content);

  final XMLEventFactory eventFactory = XMLEventFactory.newInstance();
  XMLEvent newLine = eventFactory.createSpace("\n");

  try {
    writer.add(newLine);

    while (reader.hasNext()) {
      final XMLEvent event = reader.nextEvent();

      if (event.getEventType() != XMLStreamConstants.START_DOCUMENT
          && event.getEventType() != XMLStreamConstants.END_DOCUMENT
          && event.getEventType() != XMLStreamConstants.COMMENT) {
        writer.add(event);
      }
    }
    writer.add(newLine);
  } finally {
    reader.close();
    IOUtils.closeQuietly(content);
  }
}
 
Example 4
Source File: StreamingWorkbookReader.java    From components with Apache License 2.0 5 votes vote down vote up
void lookupSheetNames(InputStream workBookData) throws IOException, InvalidFormatException, XMLStreamException {
    sheetNames.clear();

    XMLEventReader parser = XMLInputFactory.newInstance().createXMLEventReader(workBookData);
    boolean parsingsSheets = false;
    while (parser.hasNext()) {
        XMLEvent event = parser.nextEvent();
        switch (event.getEventType()) {
        case XMLStreamConstants.START_ELEMENT:
            StartElement startElement = event.asStartElement();
            String tagLocalName = startElement.getName().getLocalPart();
            if ("sheets".equals(tagLocalName)) {
                parsingsSheets = true;
                continue;
            }
            if (parsingsSheets && "sheet".equals(tagLocalName)) {
                Attribute attribute = startElement.getAttributeByName(SHEET_NAME_ATT_QNAME);
                if (attribute != null) {
                    sheetNames.add(attribute.getValue());
                }
            }

            break;
        case XMLStreamConstants.END_ELEMENT:
            if ("sheets".equals(event.asEndElement().getName().getLocalPart())) {
                return;
            }
        }
    }
}
 
Example 5
Source File: XMLEventReaderImpl.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/** Skips any insignificant space events until a START_ELEMENT or
 * END_ELEMENT is reached. If anything 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
 * the DTD is missing or not interpreted.
 * @throws XMLStreamException if anything other than space characters are encountered
 */
public XMLEvent nextTag() throws XMLStreamException {
    //its really a pain if there is peeked event before calling nextTag()
    if(fPeekedEvent != null){
        //check the peeked event first.
        XMLEvent event = fPeekedEvent;
        fPeekedEvent = null ;
        int eventType = event.getEventType();
        //if peeked event is whitespace move to the next event
        //if peeked event is PI or COMMENT move to the next event
        if( (event.isCharacters() && event.asCharacters().isWhiteSpace())
        || eventType == XMLStreamConstants.PROCESSING_INSTRUCTION
        || eventType == XMLStreamConstants.COMMENT
        || eventType == XMLStreamConstants.START_DOCUMENT){
            event = nextEvent();
            eventType = event.getEventType();
        }

        //we have to have the while loop because there can be many PI or comment event in sucession
        while((event.isCharacters() && event.asCharacters().isWhiteSpace())
        || eventType == XMLStreamConstants.PROCESSING_INSTRUCTION
        || eventType == XMLStreamConstants.COMMENT){

            event = nextEvent();
            eventType = event.getEventType();
        }

        if (eventType != XMLStreamConstants.START_ELEMENT && eventType != XMLStreamConstants.END_ELEMENT) {
            throw new XMLStreamException("expected start or end tag", event.getLocation());
        }
        return event;
    }

    //if there is no peeked event -- delegate the work of getting next event to fXMLReader
    fXMLReader.nextTag();
    return (fLastEvent = fXMLEventAllocator.allocate(fXMLReader));
}
 
Example 6
Source File: StAXSource.java    From openjdk-8 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 7
Source File: XmlPolicyModelUnmarshaller.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * See {@link PolicyModelUnmarshaller#unmarshalModel(Object) base method documentation}.
 */
public PolicySourceModel unmarshalModel(final Object storage) throws PolicyException {
    final XMLEventReader reader = createXMLEventReader(storage);
    PolicySourceModel model = null;

    loop:
    while (reader.hasNext()) {
        try {
            final XMLEvent event = reader.peek();
            switch (event.getEventType()) {
                case XMLStreamConstants.START_DOCUMENT:
                case XMLStreamConstants.COMMENT:
                    reader.nextEvent();
                    break; // skipping the comments and start document events
                case XMLStreamConstants.CHARACTERS:
                    processCharacters(ModelNode.Type.POLICY, event.asCharacters(), null);
                    // we advance the reader only if there is no exception thrown from
                    // the processCharacters(...) call. Otherwise we don't modify the stream
                    reader.nextEvent();
                    break;
                case XMLStreamConstants.START_ELEMENT:
                    if (NamespaceVersion.resolveAsToken(event.asStartElement().getName()) == XmlToken.Policy) {
                        StartElement rootElement = reader.nextEvent().asStartElement();

                        model = initializeNewModel(rootElement);
                        unmarshalNodeContent(model.getNamespaceVersion(), model.getRootNode(), rootElement.getName(), reader);

                        break loop;
                    } else {
                        throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0048_POLICY_ELEMENT_EXPECTED_FIRST()));
                    }
                default:
                    throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0048_POLICY_ELEMENT_EXPECTED_FIRST()));
            }
        } catch (XMLStreamException e) {
            throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0068_FAILED_TO_UNMARSHALL_POLICY_EXPRESSION(), e));
        }
    }
    return model;
}
 
Example 8
Source File: XMLEventReaderImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 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 {
    //we have to keep reference to the 'last event' of the stream to be able
    //to make this check - is there another way ? - nb.
    if(fLastEvent.getEventType() != XMLEvent.START_ELEMENT){
        throw new XMLStreamException(
        "parser must be on START_ELEMENT to read next text", fLastEvent.getLocation());
    }

    // STag content ETag
    //[43]   content   ::=   CharData? ((element | Reference | CDSect | PI | Comment) CharData?)*

    //<foo>....some long text say in KB and underlying parser reports multiple character
    // but getElementText() events....</foo>

    String data = null;
    //having a peeked event makes things really worse -- we have to test the first event
    if(fPeekedEvent != null){
        XMLEvent event = fPeekedEvent ;
        fPeekedEvent = null;
        int type = event.getEventType();

        if(  type == XMLEvent.CHARACTERS || type == XMLEvent.SPACE ||
        type == XMLEvent.CDATA){
            data = event.asCharacters().getData();
        }
        else if(type == XMLEvent.ENTITY_REFERENCE){
            data = ((EntityReference)event).getDeclaration().getReplacementText();
        }
        else if(type == XMLEvent.COMMENT || type == XMLEvent.PROCESSING_INSTRUCTION){
            //ignore
        } else if(type == XMLEvent.START_ELEMENT) {
            throw new XMLStreamException(
            "elementGetText() function expects text only elment but START_ELEMENT was encountered.", event.getLocation());
        }else if(type == XMLEvent.END_ELEMENT){
            return "";
        }

        //create the string buffer and add initial data
        StringBuffer buffer = new StringBuffer();
        if(data != null && data.length() > 0 ) {
            buffer.append(data);
        }
        //get the next event -- we should stop at END_ELEMENT but it can be any thing
        //things are worse when implementing this function in XMLEventReader because
        //there isn't any function called getText() which can get values for
        //space, cdata, characters and entity reference
        //nextEvent() would also set the last event.
        event = nextEvent();
        while(event.getEventType() != XMLEvent.END_ELEMENT){
            if(  type == XMLEvent.CHARACTERS || type == XMLEvent.SPACE ||
            type == XMLEvent.CDATA){
                data = event.asCharacters().getData();
            }
            else if(type == XMLEvent.ENTITY_REFERENCE){
                data = ((EntityReference)event).getDeclaration().getReplacementText();
            }
            else if(type == XMLEvent.COMMENT || type == XMLEvent.PROCESSING_INSTRUCTION){
                //ignore
            } else if(type == XMLEvent.END_DOCUMENT) {
                throw new XMLStreamException("unexpected end of document when reading element text content");
            } else if(type == XMLEvent.START_ELEMENT) {
                throw new XMLStreamException(
                "elementGetText() function expects text only elment but START_ELEMENT was encountered.", event.getLocation());
            } else {
                throw new XMLStreamException(
                "Unexpected event type "+ type, event.getLocation());
            }
            //add the data to the buffer
            if(data != null && data.length() > 0 ) {
                buffer.append(data);
            }
            event = nextEvent();
        }
        return buffer.toString();
    }//if (fPeekedEvent != null)

    //if there was no peeked, delegate everything to fXMLReader
    //update the last event before returning the text
    data = fXMLReader.getElementText();
    fLastEvent = fXMLEventAllocator.allocate(fXMLReader);
    return data;
}
 
Example 9
Source File: TubelineFeatureReader.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
private TubelineFeature parseFactories(final boolean enabled, final StartElement element, final XMLEventReader reader)
        throws WebServiceException {
    int elementRead = 0;
    loop:
    while (reader.hasNext()) {
        try {
            final XMLEvent event = reader.nextEvent();
            switch (event.getEventType()) {
                case XMLStreamConstants.COMMENT:
                    break; // skipping the comments and start document events
                case XMLStreamConstants.CHARACTERS:
                    if (event.asCharacters().isWhiteSpace()) {
                        break;
                    }
                    else {
                        // TODO: logging message
                        throw LOGGER.logSevereException(new WebServiceException("No character data allowed, was " + event.asCharacters()));
                    }
                case XMLStreamConstants.START_ELEMENT:
                    // TODO implement
                    elementRead++;
                    break;
                case XMLStreamConstants.END_ELEMENT:
                    elementRead--;
                    if (elementRead < 0) {
                        final EndElement endElement = event.asEndElement();
                        if (!element.getName().equals(endElement.getName())) {
                            // TODO logging message
                            throw LOGGER.logSevereException(new WebServiceException("End element does not match " + endElement));
                        }
                        break loop;
                    }
                    else {
                        break;
                    }
                default:
                    // TODO logging message
                    throw LOGGER.logSevereException(new WebServiceException("Unexpected event, was " + event));
            }
        } catch (XMLStreamException e) {
            // TODO logging message
            throw LOGGER.logSevereException(new WebServiceException("Failed to unmarshal XML document", e));
        }
    }

    // TODO implement
    return new TubelineFeature(enabled);
}
 
Example 10
Source File: StAXEventConnector.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
private boolean isTag(XMLEvent event) {
    int eventType = event.getEventType();
    return eventType==XMLEvent.START_ELEMENT || eventType==XMLEvent.END_ELEMENT;
}
 
Example 11
Source File: ApplicationPolicyParser.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public List<ApplicationPolicy> parse(XMLEventReader xmlEventReader) throws XMLStreamException
{
   List<ApplicationPolicy> policies = new ArrayList<ApplicationPolicy>();
   while(xmlEventReader.hasNext())
   { 
       XMLEvent xmlEvent = xmlEventReader.nextEvent();
       int eventType = xmlEvent.getEventType();
       switch(eventType)
       {
           case XMLStreamConstants.START_ELEMENT:  
              StartElement appPolicyElement = (StartElement) xmlEvent;
              String elementName = StaxParserUtil.getStartElementName(appPolicyElement);
              if("application-policy".equals(elementName) == false)
                 throw StaxParserUtil.unexpectedElement(elementName, xmlEvent);
              //We got the application-policy element. It just has one attribute "name"
              Iterator<Attribute> attrs = appPolicyElement.getAttributes(); 
              String extendsName = null;
              String appPolicyName = null;
              
              while(attrs.hasNext())
              {
                 Attribute attribute = attrs.next();
                 QName attributeName = attribute.getName();
                 String attributeValue = StaxParserUtil.getAttributeValue(attribute);
                 
                 if("name".equals(attributeName.getLocalPart()))
                    appPolicyName = attributeValue; 
                 else if("extends".equals(attributeName.getLocalPart()))
                    extendsName = attributeValue;  
              }

              ApplicationPolicy applicationPolicy = new ApplicationPolicy(appPolicyName); 
              if(extendsName != null)
                 applicationPolicy.setBaseApplicationPolicyName(extendsName);
               
              route(xmlEventReader, applicationPolicy);
              policies.add(applicationPolicy); 
       } 
   }
   return policies;
}
 
Example 12
Source File: StAXEventConnector.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private boolean isIgnorable(XMLEvent event) {
    int eventType = event.getEventType();
    return eventType==XMLEvent.COMMENT || eventType==XMLEvent.PROCESSING_INSTRUCTION;
}
 
Example 13
Source File: VersionEventWriter.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public void add(XMLEvent event) throws XMLStreamException {
    if (event.getEventType() == XMLStreamConstants.START_DOCUMENT) {
        version = ((StartDocument) event).getVersion();
        encoding = ((StartDocument) event).getCharacterEncodingScheme();
    }
}
 
Example 14
Source File: StAXEventConnector.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
private boolean isIgnorable(XMLEvent event) {
    int eventType = event.getEventType();
    return eventType==XMLEvent.COMMENT || eventType==XMLEvent.PROCESSING_INSTRUCTION;
}
 
Example 15
Source File: StaxParser.java    From tutorials with MIT License 4 votes vote down vote up
public List<Tutorial> getAllTutorial() {
    boolean bTitle = false;
    boolean bDescription = false;
    boolean bDate = false;
    boolean bAuthor = false;
    List<Tutorial> tutorials = new ArrayList<Tutorial>();
    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLEventReader eventReader = factory.createXMLEventReader(new FileReader(this.getFile()));
        Tutorial current = null;
        while (eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();
            switch (event.getEventType()) {
            case XMLStreamConstants.START_ELEMENT:
                StartElement startElement = event.asStartElement();
                String qName = startElement.getName().getLocalPart();
                if (qName.equalsIgnoreCase("tutorial")) {
                    current = new Tutorial();
                    Iterator<Attribute> attributes = startElement.getAttributes();
                    while (attributes.hasNext()) {
                        Attribute currentAt = attributes.next();
                        if (currentAt.getName().toString().equalsIgnoreCase("tutId")) {
                            current.setTutId(currentAt.getValue());
                        } else if (currentAt.getName().toString().equalsIgnoreCase("type")) {
                            current.setType(currentAt.getValue());
                        }
                    }
                } else if (qName.equalsIgnoreCase("title")) {
                    bTitle = true;
                } else if (qName.equalsIgnoreCase("description")) {
                    bDescription = true;
                } else if (qName.equalsIgnoreCase("date")) {
                    bDate = true;
                } else if (qName.equalsIgnoreCase("author")) {
                    bAuthor = true;
                }
                break;
            case XMLStreamConstants.CHARACTERS:
                Characters characters = event.asCharacters();
                if (bTitle) {
                    if (current != null) {
                        current.setTitle(characters.getData());
                    }
                    bTitle = false;
                }
                if (bDescription) {
                    if (current != null) {
                        current.setDescription(characters.getData());
                    }
                    bDescription = false;
                }
                if (bDate) {
                    if (current != null) {
                        current.setDate(characters.getData());
                    }
                    bDate = false;
                }
                if (bAuthor) {
                    if (current != null) {
                        current.setAuthor(characters.getData());
                    }
                    bAuthor = false;
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                EndElement endElement = event.asEndElement();
                if (endElement.getName().getLocalPart().equalsIgnoreCase("tutorial")) {
                    if (current != null) {
                        tutorials.add(current);
                    }
                }
                break;
            }
        }

    } catch (FileNotFoundException | XMLStreamException e) {
        e.printStackTrace();
    }

    return tutorials;
}
 
Example 16
Source File: StaxEventXMLReader.java    From java-technology-stack 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 17
Source File: StAXEventConnector.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
private boolean isIgnorable(XMLEvent event) {
    int eventType = event.getEventType();
    return eventType==XMLEvent.COMMENT || eventType==XMLEvent.PROCESSING_INSTRUCTION;
}
 
Example 18
Source File: StaxUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
public static void writeEvent(XMLEvent event, XMLStreamWriter writer)
    throws XMLStreamException {

    switch (event.getEventType()) {
    case XMLStreamConstants.START_ELEMENT:
        writeStartElementEvent(event, writer);
        break;
    case XMLStreamConstants.END_ELEMENT:
        writer.writeEndElement();
        break;
    case XMLStreamConstants.ATTRIBUTE:
        writeAttributeEvent(event, writer);
        break;
    case XMLStreamConstants.ENTITY_REFERENCE:
        writer.writeEntityRef(((javax.xml.stream.events.EntityReference)event).getName());
        break;
    case XMLStreamConstants.DTD:
        writer.writeDTD(((DTD)event).getDocumentTypeDeclaration());
        break;
    case XMLStreamConstants.PROCESSING_INSTRUCTION:
        if (((javax.xml.stream.events.ProcessingInstruction)event).getData() != null) {
            writer.writeProcessingInstruction(
                ((javax.xml.stream.events.ProcessingInstruction)event).getTarget(),
                ((javax.xml.stream.events.ProcessingInstruction)event).getData());
        } else {
            writer.writeProcessingInstruction(
                ((javax.xml.stream.events.ProcessingInstruction)event).getTarget());
        }
        break;
    case XMLStreamConstants.NAMESPACE:
        if (((Namespace)event).isDefaultNamespaceDeclaration()) {
            writer.writeDefaultNamespace(((Namespace)event).getNamespaceURI());
            writer.setDefaultNamespace(((Namespace)event).getNamespaceURI());
        } else {
            writer.writeNamespace(((Namespace)event).getPrefix(),
                                  ((Namespace)event).getNamespaceURI());
            writer.setPrefix(((Namespace)event).getPrefix(),
                             ((Namespace)event).getNamespaceURI());
        }
        break;
    case XMLStreamConstants.COMMENT:
        writer.writeComment(((javax.xml.stream.events.Comment)event).getText());
        break;
    case XMLStreamConstants.CHARACTERS:
    case XMLStreamConstants.SPACE:
        writer.writeCharacters(event.asCharacters().getData());
        break;
    case XMLStreamConstants.CDATA:
        writer.writeCData(event.asCharacters().getData());
        break;
    case XMLStreamConstants.START_DOCUMENT:
        if (((StartDocument)event).encodingSet()) {
            writer.writeStartDocument(((StartDocument)event).getCharacterEncodingScheme(),
                                      ((StartDocument)event).getVersion());

        } else {
            writer.writeStartDocument(((StartDocument)event).getVersion());
        }
        break;
    case XMLStreamConstants.END_DOCUMENT:
        writer.writeEndDocument();
        break;
    default:
        //shouldn't get here
    }
}
 
Example 19
Source File: StAXSchemaParser.java    From jdk1.8-source-analysis with Apache License 2.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 20
Source File: StAXSchemaParser.java    From openjdk-jdk8u-backup 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);
    }
}