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

The following examples show how to use javax.xml.stream.events.XMLEvent#isEndElement() . 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: Metadata.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private Schema getSchema(final StartElement start, final XMLEventReader reader) throws XMLStreamException {
  final Schema schema = new Schema(start.getAttributeByName(new QName("Namespace")).getValue());

  boolean completed = false;

  while (!completed && reader.hasNext()) {
    XMLEvent event = reader.nextEvent();

    if (event.isStartElement() && event.asStartElement().getName().equals(new QName(DEF_NS, "EntityType"))
        || event.isStartElement() && event.asStartElement().getName().equals(new QName(DEF_NS, "ComplexType"))) {
      final EntityType entityType = getEntityType(event.asStartElement(), reader);
      schema.addEntityType(entityType.getName(), entityType);
    } else if (event.isStartElement()
        && event.asStartElement().getName().equals(new QName(DEF_NS, "EntityContainer"))) {
      final org.apache.olingo.fit.metadata.Container container = getContainer(event.asStartElement(), reader);
      schema.addContainer(container.getName(), container);
    } else if (event.isEndElement() && event.asEndElement().getName().equals(start.getName())) {
      completed = true;
    }
  }

  return schema;
}
 
Example 2
Source File: StAXAntPathIterator.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
protected boolean retrieveContent(ContentRetriever retriever) throws XMLStreamException {
    int count = groupBy();

    while (reader.hasNext()) {
        XMLEvent tmp = reader.peek();

        if (tmp.isStartElement() && isTargeted(tmp)) {
            if (count-- > 0) {
                retriever.retrieve();
            } else {
                break;
            }
        } else {
            if (tmp.isStartElement()) {
                parents.add(tmp.asStartElement());
            } else if (tmp.isEndElement()) {
                parents.pop();
            }

            reader.nextEvent();
        }
    }

    return count != groupBy();
}
 
Example 3
Source File: Query.java    From ramus with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Створює новий об'єкт. При створенні даного об'єкту відбувається аналіз
 * XML документа до закриваючого тега query (включно).
 *
 * @throws XMLStreamException
 */

public Query(XMLEventReader eventReader, XMLEvent firstQueryElementEvent)
        throws XMLStreamException {
    XMLEvent element = firstQueryElementEvent;

    while (eventReader.hasNext()) {
        elements.add(new Element(eventReader, element));
        element = eventReader.nextEvent();
        if ((element.isEndElement())
                && (element.asEndElement().getName()
                .equals(ReportGenerator.QUERY)))
            break;
        if (!element.isStartElement()) {
            throw new XMLStreamException(
                    "Error in XML waighted for '<element>' or '</quary>'");
        }
    }
}
 
Example 4
Source File: MetadataParser.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private String elementValue(XMLEventReader reader, StartElement element) throws XMLStreamException {
  while (reader.hasNext()) {
    XMLEvent event = reader.peek();
    if (event.isStartElement() || event.isEndElement()) {
      return null;
    } else if (event.isCharacters()){
      reader.nextEvent();
      String data = event.asCharacters().getData();
      if (data.trim().length() > 0) {
        return data.trim();
      }
    }
  }    
  return null;
}
 
Example 5
Source File: AtomGeoValueDeserializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private List<Point> points(final XMLEventReader reader, final StartElement start,
    final EdmPrimitiveTypeKind type, final SRID srid) throws XMLStreamException {

  final List<Point> result = new ArrayList<>();

  boolean foundEndProperty = false;
  while (reader.hasNext() && !foundEndProperty) {
    final XMLEvent event = reader.nextEvent();

    if (event.isCharacters() && !event.asCharacters().isWhiteSpace()) {
      final String[] pointInfo = event.asCharacters().getData().split(" ");

      final Point point = new Point(GeoUtils.getDimension(type), srid);
      try {
        point.setX(EdmDouble.getInstance().valueOfString(pointInfo[0], null, null,
            Constants.DEFAULT_PRECISION, Constants.DEFAULT_SCALE, null, Double.class));
        point.setY(EdmDouble.getInstance().valueOfString(pointInfo[1], null, null,
            Constants.DEFAULT_PRECISION, Constants.DEFAULT_SCALE, null, Double.class));
      } catch (EdmPrimitiveTypeException e) {
        throw new XMLStreamException("While deserializing point coordinates as double", e);
      }
      result.add(point);
    }

    if (event.isEndElement() && start.getName().equals(event.asEndElement().getName())) {
      foundEndProperty = true;
    }
  }

  // handles bad input, e.g. things like <gml:pos/>
  if (result.isEmpty()) {
    result.add(new Point(GeoUtils.getDimension(type), srid));
  }

  return result;
}
 
Example 6
Source File: StAXFilteredEvent.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public XMLEvent nextTag() throws XMLStreamException {
    while(hasNext()) {
        XMLEvent e = nextEvent();
        if (e.isStartElement() || e.isEndElement())
            return e;
    }
    throw new XMLStreamException(CommonResourceBundle.getInstance().getString("message.startOrEndNotFound"));
}
 
Example 7
Source File: EdfiRecordParserImpl.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
private static String extractTagName(XMLEvent e) {
    String result = "";
    if (e.isEndElement()) {
        result = e.asEndElement().getName().getLocalPart();
    } else if (e.isStartElement()) {
        result = e.asStartElement().getName().getLocalPart();
    }
    return result;
}
 
Example 8
Source File: CheckstyleConfigurationsParser.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Recursively processes parsing of the configuration XML file with StAX parser.
 * Configuration XML has recursive tree structure
 * where module tags are nested into other module tags, also
 * duplicates of the same modules may be present in one configuration,
 * so there are no other option but to parse configuration
 * into the same tree structure.
 *
 * @param reader
 *        StAX parser interface.
 * @param parent
 *        parent module tag.
 * @throws XMLStreamException
 *         on internal StAX parser error.
 */
private static void parseModule(XMLEventReader reader, ConfigurationModule parent)
        throws XMLStreamException {
    while (reader.hasNext()) {
        final XMLEvent event = reader.nextEvent();
        if (event.isStartElement()) {
            final StartElement startElement = event.asStartElement();
            final String startElementName = startElement.getName()
                    .getLocalPart();
            // module tag encounter
            if (startElementName.equals(MODULE_TAG)) {
                processModuleTag(reader, startElement, parent);
            }
            // property tag encounter
            else if (startElementName.equals(PROPERTY_TAG)) {
                processPropertyTag(startElement, parent);
            }
            // message tag encounter
            else if (startElementName.equals(MESSAGE_TAG)) {
                processMessageTag(startElement, parent);
            }
        }
        if (event.isEndElement()) {
            final EndElement endElement = event.asEndElement();
            if (endElement.getName().getLocalPart().equals(MODULE_TAG)) {
                // return from recursive method
                break;
            }
        }
    }
}
 
Example 9
Source File: NotificationConfigurationStaxUnmarshaller.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Id (aka configuration name) isn't modeled on the actual {@link NotificationConfiguration}
 * class but as the key name in the map of configurations in
 * {@link BucketNotificationConfiguration}
 */
@Override
public Entry<String, NotificationConfiguration> unmarshall(StaxUnmarshallerContext context) throws Exception {
    int originalDepth = context.getCurrentDepth();
    int targetDepth = originalDepth + 1;

    if (context.isStartOfDocument()) {
        targetDepth += 1;
    }

    T topicConfig = createConfiguration();
    String id = null;

    while (true) {
        XMLEvent xmlEvent = context.nextEvent();
        if (xmlEvent.isEndDocument()) {
            return new SimpleEntry<String, NotificationConfiguration>(id, topicConfig);
        }

        if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
            if (handleXmlEvent(topicConfig, context, targetDepth)) {
                // Do nothing, subclass has handled it
            } else if (context.testExpression("Id", targetDepth)) {
                id = StringStaxUnmarshaller.getInstance().unmarshall(context);
            } else if (context.testExpression("Event", targetDepth)) {
                topicConfig.addEvent(StringStaxUnmarshaller.getInstance().unmarshall(context));
            } else if (context.testExpression("Filter", targetDepth)) {
                topicConfig.setFilter(FilterStaxUnmarshaller.getInstance().unmarshall(context));
            }
        } else if (xmlEvent.isEndElement()) {
            if (context.getCurrentDepth() < originalDepth) {
                return new SimpleEntry<String, NotificationConfiguration>(id, topicConfig);
            }
        }
    }
}
 
Example 10
Source File: EwsXmlReader.java    From ews-java-api with MIT License 5 votes vote down vote up
/**
 * Check end element.
 *
 * @param startEvent the start event
 * @param endEvent   the end event
 * @return true, if successful
 */
public static boolean checkEndElement(XMLEvent startEvent, XMLEvent endEvent) {
  boolean isEndElement = false;
  if (endEvent.isEndElement()) {
    QName qEName = endEvent.asEndElement().getName();
    QName qSName = startEvent.asStartElement().getName();
    isEndElement = qEName.getLocalPart().equals(qSName.getLocalPart())
        && (qEName.getPrefix().equals(qSName.getPrefix()) || qEName
        .getNamespaceURI().equals(qSName.
            getNamespaceURI()));

  }
  return isEndElement;
}
 
Example 11
Source File: ODataXmlDeserializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private StartElement getStartElement(final XMLEventReader reader) throws XMLStreamException {
  while (reader.hasNext()) {
    final XMLEvent innerEvent = reader.peek();
    if (innerEvent.isCharacters() && innerEvent.asCharacters().isWhiteSpace()) {
      reader.nextEvent();
    } else if (innerEvent.isStartElement()) {
      return innerEvent.asStartElement();
    } else if (innerEvent.isEndElement() && inlineQName.equals(innerEvent.asEndElement().getName())) {
      return null;
    }
  }
  return null;
}
 
Example 12
Source File: StaxDemo.java    From JavaCommon with Apache License 2.0 5 votes vote down vote up
public static void readXMLByStAX() throws XMLStreamException, FileNotFoundException {
	XMLInputFactory factory = XMLInputFactory.newInstance();
	XMLEventReader reader = factory.createXMLEventReader(new FileInputStream("test.xml"));//StaxDemo.class.getResourceAsStream("test.xml")
	XMLEvent event;
	StringBuffer parsingResult = new StringBuffer();
	while (reader.hasNext()) {
		event = reader.nextEvent();
		if (event.isStartElement()) {
			StartElement se = event.asStartElement();
			parsingResult.append("<");
			parsingResult.append(se.getName());
			if (se.getName().getLocalPart().equals("catalog")) {
				parsingResult.append("id=");
				parsingResult.append(se.getAttributeByName(new QName("id")).getValue());
				parsingResult.append("");
			}
			parsingResult.append(">");
		} else if (event.isCharacters()) {
			parsingResult.append(event.asCharacters().getData());
		} else if (event.isEndElement()) {
			parsingResult.append("</");
			parsingResult.append(event.asEndElement().getName());
			parsingResult.append(">");
		}
	}
	System.out.println(parsingResult);
}
 
Example 13
Source File: FilterStaxUnmarshaller.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public Filter unmarshall(StaxUnmarshallerContext context) throws Exception {
    int originalDepth = context.getCurrentDepth();
    int targetDepth = originalDepth + 1;

    if (context.isStartOfDocument()) {
        targetDepth += 1;
    }

    Filter filter = new Filter();

    while (true) {
        XMLEvent xmlEvent = context.nextEvent();
        if (xmlEvent.isEndDocument()) {
            return filter;
        }

        if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
            if (context.testExpression("S3Key", targetDepth)) {
                filter.withS3KeyFilter(S3KeyFilterStaxUnmarshaller.getInstance().unmarshall(context));
            }
        } else if (xmlEvent.isEndElement()) {
            if (context.getCurrentDepth() < originalDepth) {
                return filter;
            }
        }
    }
}
 
Example 14
Source File: RSSFeedParser.java    From Java-Snippets with The Unlicense 4 votes vote down vote up
public Feed readFeed() {
	Feed feed = null;
	try {
		boolean isFeedHeader = true;
		String description = "";
		String title = "";
		String link = "";
		String language = "";
		String copyright = "";
		String author = "";
		String pubdate = "";
		String guid = "";
		String imageURL = "";

		XMLInputFactory inputFactory = XMLInputFactory.newInstance();
		InputStream in = read();
		XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
		while (eventReader.hasNext()) {
			XMLEvent event = eventReader.nextEvent();
			if (event.isStartElement()) {
				String localPart = event.asStartElement().getName().getLocalPart();
				switch (localPart) {
				case ITEM:
					if (isFeedHeader) {
						isFeedHeader = false;
						feed = new Feed(title, link, description, language, copyright, pubdate);
					}
					event = eventReader.nextEvent();
					break;
				case TITLE:
					title = getCharacterData(event, eventReader);
					break;
				case DESCRIPTION:
					description = getCharacterData(event, eventReader);
					imageURL = extractImageFromString(description);
					break;
				case LINK:
					link = getCharacterData(event, eventReader);
					break;
				case GUID:
					guid = getCharacterData(event, eventReader);
					break;
				case LANGUAGE:
					language = getCharacterData(event, eventReader);
					break;
				case AUTHOR:
					author = getCharacterData(event, eventReader);
					break;
				case PUB_DATE:
					pubdate = getCharacterData(event, eventReader);
					break;
				case COPYRIGHT:
					copyright = getCharacterData(event, eventReader);
					break;
				}
			} else if (event.isEndElement()) {
				if (event.asEndElement().getName().getLocalPart() == (ITEM)) {
					FeedMessage message = new FeedMessage();
					message.setAuthor(author);
					message.setDescription(description);
					message.setGuid(guid);
					message.setLink(link);
					message.setTitle(title);
					message.setImageURL(imageURL);
					feed.getMessages().add(message);
					event = eventReader.nextEvent();
					continue;
				}
			}
		}
	} catch (XMLStreamException e) {
		throw new RuntimeException(e);
	}
	return feed;
}
 
Example 15
Source File: MetadataParser.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
void read(XMLEventReader reader, StartElement parentElement, T t, String... names)
    throws XMLStreamException {
  while (reader.hasNext()) {
    XMLEvent event = reader.peek();

    if (!parseAnnotations) {
      XMLEvent eventBefore = event;
      event = skipAnnotations(reader, event);
      // if annotation is stripped start again
      if (eventBefore != event) {            
        continue;
      }
    }

    if (!event.isStartElement() && !event.isEndElement()) {
      reader.nextEvent();
      continue;
    }

    if (parentElement != null && event.isEndElement()
        && ((EndElement) event).getName().equals(parentElement.getName())) {
      // end reached
      break;
    }

    boolean hit = false;

    for (String name : names) {
      if (event.isStartElement()) {
        StartElement element = event.asStartElement();
        if (element.getName().getLocalPart().equals(name)) {              
          reader.nextEvent(); // advance cursor start which is current
          build(reader, element, t, name);
          hit = true;
          break;
        }
      }
      if (event.isEndElement()) {
        EndElement e = event.asEndElement();
        if (e.getName().getLocalPart().equals(name)) {
          reader.nextEvent(); // advance cursor to end which is current
          hit = true;
          break;
        }
      }
    }
    if (!hit) {
      break;
    }
  }
}
 
Example 16
Source File: RestXMLResponseParser.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private RestActionReport parseReport(XMLEventReader reader) throws XMLStreamException {
    int level = 0;
    RestActionReport report = new RestActionReport();
    while (reader.hasNext() && (level > -1)) {
            XMLEvent event = reader.nextEvent();
            if (event.isStartElement()) {

                if (level++ == 0) {
                    StartElement element = event.asStartElement();
                    String elementName = element.getName().getLocalPart();
                    if (ENTRY.equals(elementName)) {
                        Map<String, String> m = getMapEntry(element);
                        String key = m.get("key");
                        String value = m.get("value");
                        switch (key) {
                            case "message":
                                report.setMessage(value);
                                break;
                            case "exit_code":
                                report.setExitCode(ActionReport.ExitCode.valueOf(value));
                                break;
                            case "command":
                                report.setActionDescription(value);
                                break;
                            case "children":
                                report.topMessagePart.children = parseChildrenMessages(reader);
                                level--;
                                break;
                            case "subReports":
                                report.subActions = parseSubReports(reader);
                                break;
                        }
                    }
                }

            }

            if (event.isEndElement()) {
                level--;
            }
        }
    return report;
}
 
Example 17
Source File: EndElementEventCondition.java    From butterfly with MIT License 4 votes vote down vote up
@Override
public boolean evaluateEvent(XMLEvent xmlEvent) {
    return xmlEvent.isEndElement() && xmlEvent.asEndElement().getName().getLocalPart().equals(tagName);
}
 
Example 18
Source File: AssignmentConversionServiceImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
private String adjustXmlForGroups(String xml) {
    if (StringUtils.isBlank(xml)) return null;
    // special processing for assignments in order to deserialize groups correctly
    // see https://stackoverflow.com/questions/47199799/jackson-xml-tag-and-attribute-with-the-same-name
    // see https://github.com/FasterXML/jackson-dataformat-xml/issues/65
    try (InputStream in = new ByteArrayInputStream(xml.getBytes());
         OutputStream out = new ByteArrayOutputStream()) {

        XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(in);
        XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(out);
        XMLEventFactory eventFactory = XMLEventFactory.newInstance();
        List<XMLEvent> groupEvents = new ArrayList<>();

        while (reader.hasNext()) {
            XMLEvent event = reader.nextEvent();
            if (event.isStartElement() && "group".equals(event.asStartElement().getName().getLocalPart())) {
                for (; !event.isEndElement(); event = reader.nextEvent()) {
                    groupEvents.add(event);
                }
                groupEvents.add(event);
            } else if (event.isEndElement() && "assignment".equals(event.asEndElement().getName().getLocalPart())) {
                writer.add(eventFactory.createStartElement("", "", "groups"));
                for (XMLEvent e : groupEvents) {
                    writer.add(e);
                }
                writer.add(eventFactory.createEndElement("", "", "groups"));
                writer.add(event);
            } else {
                writer.add(event);
            }
        }
        writer.flush();
        String adjustedXml = out.toString();
        log.debug("adjusted groups in xml: {}", adjustedXml);
        return adjustedXml;
    } catch (XMLStreamException xse) {
        log.warn("xml parsing error while adjusting for groups, {}\n{}", xse.getMessage(), xml);
    } catch (IOException ioe) {
        log.warn("could not adjust xml for groups, {}\n{}", ioe.getMessage(), xml);
    }
    return null;
}
 
Example 19
Source File: AttributeProtocol.java    From ts-reaktive with MIT License 4 votes vote down vote up
public AttributeProtocol(QName name) {
    super(new Protocol<XMLEvent,String>() {
        Writer<XMLEvent,String> writer = Writer.of(s -> Vector.of(factory.createAttribute(name, s)));
        @Override
        public Class<? extends XMLEvent> getEventType() {
            return Attribute.class;
        }
        
        @Override
        public String toString() {
            return "@" + name;
        }

        @Override
        public Reader<XMLEvent,String> reader() {
            return new Reader<XMLEvent,String>() {
                private int level = 0;

                @Override
                public Try<String> reset() {
                    level = 0;
                    return none();
                }

                @Override
                public Try<String> apply(XMLEvent evt) {
                    if (level == 0 && evt.isAttribute() && matches(Attribute.class.cast(evt))) {
                        return Try.success(Attribute.class.cast(evt).getValue());
                    } else if (evt.isStartElement()) {
                        level++;
                        return none();
                    } else if (evt.isEndElement()) {
                        level--;
                        return none();
                    } else {
                        return none();
                    }
                }

                private boolean matches(Attribute attr) {
                    return name.equals(attr.getName());
                }
                
            };
        }
        
        @Override
        public Writer<XMLEvent,String> writer() {
            return writer;
        }
    }, XMLProtocol.locator);
}
 
Example 20
Source File: BingResultParser.java    From AndroidStringsOneTabTranslation with Apache License 2.0 4 votes vote down vote up
public static List<TranslateArrayResponse> parseTranslateArrayResponse(String xml) {

        InputStream stream = new ByteArrayInputStream(xml.getBytes(Charset.forName("UTF-8")));

        List<TranslateArrayResponse> result = new ArrayList<TranslateArrayResponse>();

        try {
            XMLInputFactory inputFactory = XMLInputFactory.newInstance();
            XMLEventReader eventReader = inputFactory.createXMLEventReader(stream);

            TranslateArrayResponse translateArrayResponse = null;

            while (eventReader.hasNext()) {
                XMLEvent event = eventReader.nextEvent();

                if (event.isStartElement()) {
                    StartElement startElement = event.asStartElement();
                    if (startElement.getName().getLocalPart().equals(TranslateArrayResponse)) {
                        translateArrayResponse = new TranslateArrayResponse();
                    }
                    if (event.isStartElement()) {
                        if (event.asStartElement().getName().getLocalPart().equals(From)) {
                            event = eventReader.nextEvent();
                            translateArrayResponse.setFrom(event.asCharacters().getData());
                            continue;
                        }
                    }
                    if (event.asStartElement().getName().getLocalPart().equals(TranslatedText)) {
                        event = eventReader.nextEvent();
                        translateArrayResponse.setTranslatedText(event.asCharacters().getData());
                        continue;
                    }
                }

                if (event.isEndElement()) {
                    EndElement endElement = event.asEndElement();
                    if (endElement.getName().getLocalPart().equals(TranslateArrayResponse)) {
                        result.add(translateArrayResponse);
                    }
                }
            }
        } catch (XMLStreamException e) {
            e.printStackTrace();
        }

        return result;
    }