Java Code Examples for javax.xml.stream.events.StartElement

The following are top voted examples for showing how to use javax.xml.stream.events.StartElement. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: powsybl-core   File: CimAnonymizer.java   View source code 6 votes vote down vote up
private XMLEvent anonymizeStartElement(StartElement startElement) {
    if (startElement.getName().getLocalPart().equals("IdentifiedObject.name")) {
        identifiedObjectName = true;
    } else if (startElement.getName().getLocalPart().equals("IdentifiedObject.description")) {
        identifiedObjectDescription = true;
    } else {
        Iterator it = startElement.getAttributes();
        if (it.hasNext()) {
            List<Attribute> newAttributes = new ArrayList<>();
            while (it.hasNext()) {
                Attribute attribute = (Attribute) it.next();
                Attribute newAttribute = anonymizeAttribute(attribute);
                newAttributes.add(newAttribute != null ? newAttribute : attribute);
            }
            return xmlStaxContext.eventFactory.createStartElement(startElement.getName(),
                                                                  newAttributes.iterator(),
                                                                  startElement.getNamespaces());
        }
    }
    return null;
}
 
Example 2
Project: powsybl-core   File: CimAnonymizer.java   View source code 6 votes vote down vote up
private void addRdfIdValues(InputStream is, Set<String> rdfIdValues) throws XMLStreamException {
    // memoize RDF ID values of the document
    XMLEventReader eventReader = xmlStaxContext.inputFactory.createXMLEventReader(is);
    while (eventReader.hasNext()) {
        XMLEvent event = eventReader.nextEvent();
        if (event.isStartElement()) {
            StartElement startElement = event.asStartElement();
            Iterator it = startElement.getAttributes();
            while (it.hasNext()) {
                Attribute attribute = (Attribute) it.next();
                QName name = attribute.getName();
                if (RDF_ID.equals(name)) {
                    rdfIdValues.add(attribute.getValue());
                }
            }
        }
    }
    eventReader.close();
}
 
Example 3
Project: smart-testing   File: JUnitTestResultParser.java   View source code 6 votes vote down vote up
private void setCurrentTestResult(TestResult currentTestResult, StartElement startElement) {
    if ("failure".equalsIgnoreCase(startElement.getName().getLocalPart())) {
        currentTestResult.setResult(TestResult.Result.FAILURE);
    }

    if ("error".equalsIgnoreCase(startElement.getName().getLocalPart())) {
        currentTestResult.setResult(TestResult.Result.ERROR);
    }

    if ("skipped".equalsIgnoreCase(startElement.getName().getLocalPart())) {
        currentTestResult.setResult(TestResult.Result.SKIPPED);
    }

    if ("rerunFailure".equalsIgnoreCase(startElement.getName().getLocalPart())) {
        currentTestResult.setResult(TestResult.Result.RE_RUN_FAILURE);
    }
}
 
Example 4
Project: OpenJSharp   File: ExternalAttachmentsUnmarshaller.java   View source code 6 votes vote down vote up
private void processCharacters(final Characters chars, final StartElement currentElement, final Map<URI, Policy> map)
        throws PolicyException {
    if (chars.isWhiteSpace()) {
        return;
    }
    else {
        final String data = chars.getData();
        if ((currentElement != null) && URI.equals(currentElement.getName())) {
            processUri(chars, map);
            return;
        } else {
            throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0092_CHARACTER_DATA_UNEXPECTED(currentElement, data, chars.getLocation())));
        }

    }
}
 
Example 5
Project: OpenJSharp   File: XmlPolicyModelUnmarshaller.java   View source code 6 votes vote down vote up
private PolicySourceModel initializeNewModel(final StartElement element) throws PolicyException, XMLStreamException {
    PolicySourceModel model;

    final NamespaceVersion nsVersion = NamespaceVersion.resolveVersion(element.getName().getNamespaceURI());

    final Attribute policyName = getAttributeByName(element, nsVersion.asQName(XmlToken.Name));
    final Attribute xmlId = getAttributeByName(element, PolicyConstants.XML_ID);
    Attribute policyId = getAttributeByName(element, PolicyConstants.WSU_ID);

    if (policyId == null) {
        policyId = xmlId;
    } else if (xmlId != null) {
        throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0058_MULTIPLE_POLICY_IDS_NOT_ALLOWED()));
    }

    model = createSourceModel(nsVersion,
            (policyId == null) ? null : policyId.getValue(),
            (policyName == null) ? null : policyName.getValue());

    return model;
}
 
Example 6
Project: OpenJSharp   File: XmlPolicyModelUnmarshaller.java   View source code 6 votes vote down vote up
private Attribute getAttributeByName(final StartElement element,
        final QName attributeName) {
    // call standard API method to retrieve the attribute by name
    Attribute attribute = element.getAttributeByName(attributeName);

    // try to find the attribute without a prefix.
    if (attribute == null) {
        final String localAttributeName = attributeName.getLocalPart();
        final Iterator iterator = element.getAttributes();
        while (iterator.hasNext()) {
            final Attribute nextAttribute = (Attribute) iterator.next();
            final QName aName = nextAttribute.getName();
            final boolean attributeFoundByWorkaround = aName.equals(attributeName) || (aName.getLocalPart().equals(localAttributeName) && (aName.getPrefix() == null || "".equals(aName.getPrefix())));
            if (attributeFoundByWorkaround) {
                attribute = nextAttribute;
                break;
            }

        }
    }

    return attribute;
}
 
Example 7
Project: OpenJSharp   File: TubelineFeatureReader.java   View source code 6 votes vote down vote up
public TubelineFeature parse(XMLEventReader reader) throws WebServiceException {
    try {
        final StartElement element = reader.nextEvent().asStartElement();
        boolean attributeEnabled = true;
        final Iterator iterator = element.getAttributes();
        while (iterator.hasNext()) {
            final Attribute nextAttribute = (Attribute) iterator.next();
            final QName attributeName = nextAttribute.getName();
            if (ENABLED_ATTRIBUTE_NAME.equals(attributeName)) {
                attributeEnabled = ParserUtil.parseBooleanValue(nextAttribute.getValue());
            } else if (NAME_ATTRIBUTE_NAME.equals(attributeName)) {
                // TODO use name attribute
            } else {
                // TODO logging message
                throw LOGGER.logSevereException(new WebServiceException("Unexpected attribute"));
            }
        }
        return parseFactories(attributeEnabled, element, reader);
    } catch (XMLStreamException e) {
        throw LOGGER.logSevereException(new WebServiceException("Failed to unmarshal XML document", e));
    }
}
 
Example 8
Project: OpenJSharp   File: StAXEventConnector.java   View source code 6 votes vote down vote up
private void handleStartElement(StartElement event) throws SAXException {
    // start namespace bindings
    for (Iterator i = event.getNamespaces(); i.hasNext();) {
        Namespace ns = (Namespace)i.next();
        visitor.startPrefixMapping(
            fixNull(ns.getPrefix()),
            fixNull(ns.getNamespaceURI()));
    }

    // fire startElement
    QName qName = event.getName();
    tagName.uri = fixNull(qName.getNamespaceURI());
    String localName = qName.getLocalPart();
    tagName.uri = fixNull(qName.getNamespaceURI());
    tagName.local = localName;
    tagName.atts = getAttributes(event);
    visitor.startElement(tagName);

    seenText = false;
}
 
Example 9
Project: openjdk-jdk10   File: ExternalAttachmentsUnmarshaller.java   View source code 6 votes vote down vote up
private void processCharacters(final Characters chars, final StartElement currentElement, final Map<URI, Policy> map)
        throws PolicyException {
    if (chars.isWhiteSpace()) {
        return;
    }
    else {
        final String data = chars.getData();
        if ((currentElement != null) && URI.equals(currentElement.getName())) {
            processUri(chars, map);
            return;
        } else {
            throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0092_CHARACTER_DATA_UNEXPECTED(currentElement, data, chars.getLocation())));
        }

    }
}
 
Example 10
Project: openjdk-jdk10   File: XmlPolicyModelUnmarshaller.java   View source code 6 votes vote down vote up
private PolicySourceModel initializeNewModel(final StartElement element) throws PolicyException, XMLStreamException {
    PolicySourceModel model;

    final NamespaceVersion nsVersion = NamespaceVersion.resolveVersion(element.getName().getNamespaceURI());

    final Attribute policyName = getAttributeByName(element, nsVersion.asQName(XmlToken.Name));
    final Attribute xmlId = getAttributeByName(element, PolicyConstants.XML_ID);
    Attribute policyId = getAttributeByName(element, PolicyConstants.WSU_ID);

    if (policyId == null) {
        policyId = xmlId;
    } else if (xmlId != null) {
        throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0058_MULTIPLE_POLICY_IDS_NOT_ALLOWED()));
    }

    model = createSourceModel(nsVersion,
            (policyId == null) ? null : policyId.getValue(),
            (policyName == null) ? null : policyName.getValue());

    return model;
}
 
Example 11
Project: openjdk-jdk10   File: XmlPolicyModelUnmarshaller.java   View source code 6 votes vote down vote up
private Attribute getAttributeByName(final StartElement element,
        final QName attributeName) {
    // call standard API method to retrieve the attribute by name
    Attribute attribute = element.getAttributeByName(attributeName);

    // try to find the attribute without a prefix.
    if (attribute == null) {
        final String localAttributeName = attributeName.getLocalPart();
        final Iterator iterator = element.getAttributes();
        while (iterator.hasNext()) {
            final Attribute nextAttribute = (Attribute) iterator.next();
            final QName aName = nextAttribute.getName();
            final boolean attributeFoundByWorkaround = aName.equals(attributeName) || (aName.getLocalPart().equals(localAttributeName) && (aName.getPrefix() == null || "".equals(aName.getPrefix())));
            if (attributeFoundByWorkaround) {
                attribute = nextAttribute;
                break;
            }

        }
    }

    return attribute;
}
 
Example 12
Project: openjdk-jdk10   File: TubelineFeatureReader.java   View source code 6 votes vote down vote up
public TubelineFeature parse(XMLEventReader reader) throws WebServiceException {
    try {
        final StartElement element = reader.nextEvent().asStartElement();
        boolean attributeEnabled = true;
        final Iterator iterator = element.getAttributes();
        while (iterator.hasNext()) {
            final Attribute nextAttribute = (Attribute) iterator.next();
            final QName attributeName = nextAttribute.getName();
            if (ENABLED_ATTRIBUTE_NAME.equals(attributeName)) {
                attributeEnabled = ParserUtil.parseBooleanValue(nextAttribute.getValue());
            } else if (NAME_ATTRIBUTE_NAME.equals(attributeName)) {
                // TODO use name attribute
            } else {
                // TODO logging message
                throw LOGGER.logSevereException(new WebServiceException("Unexpected attribute"));
            }
        }
        return parseFactories(attributeEnabled, element, reader);
    } catch (XMLStreamException e) {
        throw LOGGER.logSevereException(new WebServiceException("Failed to unmarshal XML document", e));
    }
}
 
Example 13
Project: openjdk-jdk10   File: StAXEventConnector.java   View source code 6 votes vote down vote up
private void handleStartElement(StartElement event) throws SAXException {
    // start namespace bindings
    for (Iterator i = event.getNamespaces(); i.hasNext();) {
        Namespace ns = (Namespace)i.next();
        visitor.startPrefixMapping(
            fixNull(ns.getPrefix()),
            fixNull(ns.getNamespaceURI()));
    }

    // fire startElement
    QName qName = event.getName();
    tagName.uri = fixNull(qName.getNamespaceURI());
    String localName = qName.getLocalPart();
    tagName.uri = fixNull(qName.getNamespaceURI());
    tagName.local = localName;
    tagName.atts = getAttributes(event);
    visitor.startElement(tagName);

    seenText = false;
}
 
Example 14
Project: openjdk9   File: ExternalAttachmentsUnmarshaller.java   View source code 6 votes vote down vote up
private void processCharacters(final Characters chars, final StartElement currentElement, final Map<URI, Policy> map)
        throws PolicyException {
    if (chars.isWhiteSpace()) {
        return;
    }
    else {
        final String data = chars.getData();
        if ((currentElement != null) && URI.equals(currentElement.getName())) {
            processUri(chars, map);
            return;
        } else {
            throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0092_CHARACTER_DATA_UNEXPECTED(currentElement, data, chars.getLocation())));
        }

    }
}
 
Example 15
Project: openjdk9   File: XmlPolicyModelUnmarshaller.java   View source code 6 votes vote down vote up
private PolicySourceModel initializeNewModel(final StartElement element) throws PolicyException, XMLStreamException {
    PolicySourceModel model;

    final NamespaceVersion nsVersion = NamespaceVersion.resolveVersion(element.getName().getNamespaceURI());

    final Attribute policyName = getAttributeByName(element, nsVersion.asQName(XmlToken.Name));
    final Attribute xmlId = getAttributeByName(element, PolicyConstants.XML_ID);
    Attribute policyId = getAttributeByName(element, PolicyConstants.WSU_ID);

    if (policyId == null) {
        policyId = xmlId;
    } else if (xmlId != null) {
        throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0058_MULTIPLE_POLICY_IDS_NOT_ALLOWED()));
    }

    model = createSourceModel(nsVersion,
            (policyId == null) ? null : policyId.getValue(),
            (policyName == null) ? null : policyName.getValue());

    return model;
}
 
Example 16
Project: openjdk9   File: XmlPolicyModelUnmarshaller.java   View source code 6 votes vote down vote up
private Attribute getAttributeByName(final StartElement element,
        final QName attributeName) {
    // call standard API method to retrieve the attribute by name
    Attribute attribute = element.getAttributeByName(attributeName);

    // try to find the attribute without a prefix.
    if (attribute == null) {
        final String localAttributeName = attributeName.getLocalPart();
        final Iterator iterator = element.getAttributes();
        while (iterator.hasNext()) {
            final Attribute nextAttribute = (Attribute) iterator.next();
            final QName aName = nextAttribute.getName();
            final boolean attributeFoundByWorkaround = aName.equals(attributeName) || (aName.getLocalPart().equals(localAttributeName) && (aName.getPrefix() == null || "".equals(aName.getPrefix())));
            if (attributeFoundByWorkaround) {
                attribute = nextAttribute;
                break;
            }

        }
    }

    return attribute;
}
 
Example 17
Project: openjdk9   File: TubelineFeatureReader.java   View source code 6 votes vote down vote up
public TubelineFeature parse(XMLEventReader reader) throws WebServiceException {
    try {
        final StartElement element = reader.nextEvent().asStartElement();
        boolean attributeEnabled = true;
        final Iterator iterator = element.getAttributes();
        while (iterator.hasNext()) {
            final Attribute nextAttribute = (Attribute) iterator.next();
            final QName attributeName = nextAttribute.getName();
            if (ENABLED_ATTRIBUTE_NAME.equals(attributeName)) {
                attributeEnabled = ParserUtil.parseBooleanValue(nextAttribute.getValue());
            } else if (NAME_ATTRIBUTE_NAME.equals(attributeName)) {
                // TODO use name attribute
            } else {
                // TODO logging message
                throw LOGGER.logSevereException(new WebServiceException("Unexpected attribute"));
            }
        }
        return parseFactories(attributeEnabled, element, reader);
    } catch (XMLStreamException e) {
        throw LOGGER.logSevereException(new WebServiceException("Failed to unmarshal XML document", e));
    }
}
 
Example 18
Project: openjdk9   File: StAXEventConnector.java   View source code 6 votes vote down vote up
private void handleStartElement(StartElement event) throws SAXException {
    // start namespace bindings
    for (Iterator i = event.getNamespaces(); i.hasNext();) {
        Namespace ns = (Namespace)i.next();
        visitor.startPrefixMapping(
            fixNull(ns.getPrefix()),
            fixNull(ns.getNamespaceURI()));
    }

    // fire startElement
    QName qName = event.getName();
    tagName.uri = fixNull(qName.getNamespaceURI());
    String localName = qName.getLocalPart();
    tagName.uri = fixNull(qName.getNamespaceURI());
    tagName.local = localName;
    tagName.atts = getAttributes(event);
    visitor.startElement(tagName);

    seenText = false;
}
 
Example 19
Project: spring4-understanding   File: StaxEventXMLReader.java   View source code 6 votes vote down vote up
private void handleStartElement(StartElement startElement) throws SAXException {
	if (getContentHandler() != null) {
		QName qName = startElement.getName();
		if (hasNamespacesFeature()) {
			for (Iterator i = startElement.getNamespaces(); i.hasNext();) {
				Namespace namespace = (Namespace) i.next();
				startPrefixMapping(namespace.getPrefix(), namespace.getNamespaceURI());
			}
			for (Iterator i = startElement.getAttributes(); i.hasNext();){
				Attribute attribute = (Attribute) i.next();
				QName attributeName = attribute.getName();
				startPrefixMapping(attributeName.getPrefix(), attributeName.getNamespaceURI());
			}

			getContentHandler().startElement(qName.getNamespaceURI(), qName.getLocalPart(), toQualifiedName(qName),
					getAttributes(startElement));
		}
		else {
			getContentHandler().startElement("", "", toQualifiedName(qName), getAttributes(startElement));
		}
	}
}
 
Example 20
Project: svg-stockpile   File: StartElementProcessor.java   View source code 6 votes vote down vote up
/**
 * Modifies a {@link StartElement}, removing attributes that do not have a {@link QName#getNamespaceURI()} that
 * equals {@link SvgDocument#NAMESPACE_URI}.
 * @param element The {@link StartElement} to remove attributes from.
 * @return The modified {@link StartElement}.
 */
@SuppressWarnings("unchecked")
private static XMLEvent removeNonSvgAttributes(StartElement element) {
	Iterator<Attribute> original = element.getAttributes();
	Collection<Attribute> modified = new ArrayList<>();

	while (original.hasNext()) {
		Attribute attribute = original.next();
		QName qName = attribute.getName();
		String namespaceUri = qName.getNamespaceURI();

		if (namespaceUri.isEmpty() || namespaceUri.equals(SvgDocument.NAMESPACE_URI)) {
			modified.add(attribute);
		}
	}

	return events.createStartElement(element.getName(), modified.iterator(), element.getNamespaces());
}
 
Example 21
Project: lookaside_java-1.8.0-openjdk   File: ExternalAttachmentsUnmarshaller.java   View source code 6 votes vote down vote up
private void processCharacters(final Characters chars, final StartElement currentElement, final Map<URI, Policy> map)
        throws PolicyException {
    if (chars.isWhiteSpace()) {
        return;
    }
    else {
        final String data = chars.getData();
        if ((currentElement != null) && URI.equals(currentElement.getName())) {
            processUri(chars, map);
            return;
        } else {
            throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0092_CHARACTER_DATA_UNEXPECTED(currentElement, data, chars.getLocation())));
        }

    }
}
 
Example 22
Project: lookaside_java-1.8.0-openjdk   File: XmlPolicyModelUnmarshaller.java   View source code 6 votes vote down vote up
private PolicySourceModel initializeNewModel(final StartElement element) throws PolicyException, XMLStreamException {
    PolicySourceModel model;

    final NamespaceVersion nsVersion = NamespaceVersion.resolveVersion(element.getName().getNamespaceURI());

    final Attribute policyName = getAttributeByName(element, nsVersion.asQName(XmlToken.Name));
    final Attribute xmlId = getAttributeByName(element, PolicyConstants.XML_ID);
    Attribute policyId = getAttributeByName(element, PolicyConstants.WSU_ID);

    if (policyId == null) {
        policyId = xmlId;
    } else if (xmlId != null) {
        throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0058_MULTIPLE_POLICY_IDS_NOT_ALLOWED()));
    }

    model = createSourceModel(nsVersion,
            (policyId == null) ? null : policyId.getValue(),
            (policyName == null) ? null : policyName.getValue());

    return model;
}
 
Example 23
Project: lookaside_java-1.8.0-openjdk   File: XmlPolicyModelUnmarshaller.java   View source code 6 votes vote down vote up
private Attribute getAttributeByName(final StartElement element,
        final QName attributeName) {
    // call standard API method to retrieve the attribute by name
    Attribute attribute = element.getAttributeByName(attributeName);

    // try to find the attribute without a prefix.
    if (attribute == null) {
        final String localAttributeName = attributeName.getLocalPart();
        final Iterator iterator = element.getAttributes();
        while (iterator.hasNext()) {
            final Attribute nextAttribute = (Attribute) iterator.next();
            final QName aName = nextAttribute.getName();
            final boolean attributeFoundByWorkaround = aName.equals(attributeName) || (aName.getLocalPart().equals(localAttributeName) && (aName.getPrefix() == null || "".equals(aName.getPrefix())));
            if (attributeFoundByWorkaround) {
                attribute = nextAttribute;
                break;
            }

        }
    }

    return attribute;
}
 
Example 24
Project: lookaside_java-1.8.0-openjdk   File: TubelineFeatureReader.java   View source code 6 votes vote down vote up
public TubelineFeature parse(XMLEventReader reader) throws WebServiceException {
    try {
        final StartElement element = reader.nextEvent().asStartElement();
        boolean attributeEnabled = true;
        final Iterator iterator = element.getAttributes();
        while (iterator.hasNext()) {
            final Attribute nextAttribute = (Attribute) iterator.next();
            final QName attributeName = nextAttribute.getName();
            if (ENABLED_ATTRIBUTE_NAME.equals(attributeName)) {
                attributeEnabled = ParserUtil.parseBooleanValue(nextAttribute.getValue());
            } else if (NAME_ATTRIBUTE_NAME.equals(attributeName)) {
                // TODO use name attribute
            } else {
                // TODO logging message
                throw LOGGER.logSevereException(new WebServiceException("Unexpected attribute"));
            }
        }
        return parseFactories(attributeEnabled, element, reader);
    } catch (XMLStreamException e) {
        throw LOGGER.logSevereException(new WebServiceException("Failed to unmarshal XML document", e));
    }
}
 
Example 25
Project: lookaside_java-1.8.0-openjdk   File: StAXEventConnector.java   View source code 6 votes vote down vote up
private void handleStartElement(StartElement event) throws SAXException {
    // start namespace bindings
    for (Iterator i = event.getNamespaces(); i.hasNext();) {
        Namespace ns = (Namespace)i.next();
        visitor.startPrefixMapping(
            fixNull(ns.getPrefix()),
            fixNull(ns.getNamespaceURI()));
    }

    // fire startElement
    QName qName = event.getName();
    tagName.uri = fixNull(qName.getNamespaceURI());
    String localName = qName.getLocalPart();
    tagName.uri = fixNull(qName.getNamespaceURI());
    tagName.local = localName;
    tagName.atts = getAttributes(event);
    visitor.startElement(tagName);

    seenText = false;
}
 
Example 26
Project: ZombieLib2   File: Fb2FileParser.java   View source code 6 votes vote down vote up
private Author parseAuthor(XMLEventReader reader) throws XMLStreamException {
    String lastName = "";
    String firstName = "";
    String middleName = "";
    Author author = new Author();
    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();
        if (event.isStartElement()) {
            StartElement element = event.asStartElement();
            String localPart = element.getName().getLocalPart();
            if ("first-name".equals(localPart)) {
                firstName = reader.getElementText();
            } else if ("middle-name".equals(localPart)) {
                middleName = reader.getElementText();
            } else if ("last-name".equals(localPart)) {
                lastName = reader.getElementText();
            }
        }
        if (event.isEndElement() && "author".equals(event.asEndElement().getName().getLocalPart())) {
            String name = lastName + " " + firstName + " " + middleName;
            author.setName(name.replaceAll("\\s+", " "));
            return author;
        }
    }
    return null;
}
 
Example 27
Project: ZombieLib2   File: Fb2FileParser.java   View source code 6 votes vote down vote up
private String getImageCoverage(XMLEventReader reader) throws XMLStreamException {
    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();
        if (event.isStartElement()) {
            StartElement element = event.asStartElement();
            String localPart = element.getName().getLocalPart();
            if ("image".equals(localPart)) {
                QName hrefQName = new QName("http://www.w3.org/1999/xlink", "href");
                Attribute href = element.getAttributeByName(hrefQName);
                return href.getValue();
            }
        }
        if (event.isEndElement() && "coverage".equals(event.asEndElement().getName().getLocalPart())) {
            return null;
        }
    }
    return null;
}
 
Example 28
Project: similarity   File: ConceptParser.java   View source code 6 votes vote down vote up
private static void load(InputStream inputStream) throws IOException {
    long start = System.currentTimeMillis();
    int count = 0;
    try {
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        XMLEventReader xmlEventReader = inputFactory.createXMLEventReader(inputStream);
        while (xmlEventReader.hasNext()) {
            XMLEvent event = xmlEventReader.nextEvent();
            if (event.isStartElement()) {
                StartElement startElement = event.asStartElement();
                if (startElement.getName().toString().equals("c")) {
                    String word = startElement.getAttributeByName(QName.valueOf("w")).getValue();
                    String define = startElement.getAttributeByName(QName.valueOf("d")).getValue();
                    String pos = startElement.getAttributeByName(QName.valueOf("p")).getValue();
                    CONCEPTS.put(word, new Concept(word, pos, define));
                    count++;
                }
            }
        }
        inputStream.close();
    } catch (Exception e) {
        throw new IOException(e);
    }
    logger.info("complete! count num:" + count + ",time spend:" + (System.currentTimeMillis() - start) + "ms");
}
 
Example 29
Project: spring   File: StaxEventXMLReader.java   View source code 6 votes vote down vote up
private void handleStartElement(StartElement startElement) throws SAXException {
	if (getContentHandler() != null) {
		QName qName = startElement.getName();
		if (hasNamespacesFeature()) {
			for (Iterator i = startElement.getNamespaces(); i.hasNext();) {
				Namespace namespace = (Namespace) i.next();
				startPrefixMapping(namespace.getPrefix(), namespace.getNamespaceURI());
			}
			for (Iterator i = startElement.getAttributes(); i.hasNext();){
				Attribute attribute = (Attribute) i.next();
				QName attributeName = attribute.getName();
				startPrefixMapping(attributeName.getPrefix(), attributeName.getNamespaceURI());
			}

			getContentHandler().startElement(qName.getNamespaceURI(), qName.getLocalPart(), toQualifiedName(qName),
					getAttributes(startElement));
		}
		else {
			getContentHandler().startElement("", "", toQualifiedName(qName), getAttributes(startElement));
		}
	}
}
 
Example 30
Project: vespa   File: VespaRecordWriter.java   View source code 6 votes vote down vote up
private String findDocIdFromXml(String xml) {
    try {
        XMLEventReader eventReader = XMLInputFactory.newInstance().createXMLEventReader(new StringReader(xml));
        while (eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();
            if (event.getEventType() == XMLEvent.START_ELEMENT) {
                StartElement element = event.asStartElement();
                String elementName = element.getName().getLocalPart();
                if (VespaDocumentOperation.Operation.valid(elementName)) {
                    return element.getAttributeByName(QName.valueOf("documentid")).getValue();
                }
            }
        }
    } catch (XMLStreamException | FactoryConfigurationError e) {
        // as json dude does
        return null;
    }
    return null;
}
 
Example 31
Project: iem4j   File: ResultParser.java   View source code 6 votes vote down vote up
private Map<String,Object> processElement(SessionRelevanceQuery srq,StartElement el,XMLEventReader reader) throws JAXBException{
	ResultList row = null;
	
	JAXBElement element = null;
	String localName = el.getName().getLocalPart();
	if(localName.equals("String"))
		element = unmarshaller.unmarshal(reader,String.class);
	else if(localName.equals("Boolean"))
		element = unmarshaller.unmarshal(reader,Boolean.class);
	else if(localName.equals("Integer"))
		element = unmarshaller.unmarshal(reader,Integer.class);
	else if(localName.equals("DateTime"))
		element = unmarshaller.unmarshal(reader,XMLGregorianCalendar.class);
	else if(localName.equals("FloatingPoint"))
		element = unmarshaller.unmarshal(reader,Double.class);
	else if(localName.equals("Tuple")){
		JAXBElement<ResultList> jb = unmarshaller.unmarshal(reader, ResultList.class);
		row = jb.getValue();
	}
	if(row==null){
		row = new ResultList();
		row.getBooleanOrIntegerOrString().add(element.getValue());
	}
	return processResultList(row,srq);
}
 
Example 32
Project: iem4j   File: RESTResultParser.java   View source code 6 votes vote down vote up
private Map<String,Object> processElement(SessionRelevanceQuery srq,StartElement el,XMLEventReader reader) throws Exception{
	ResultTuple row = null;
	
	JAXBElement element = null;
	String localName = el.getName().getLocalPart();
	if(localName.equals("Answer")){
		Answer answer = (Answer)unmarshaller.unmarshal(reader);
		row = new ResultTuple();
		row.setAnswers(Arrays.asList(adapter.unmarshal(answer)));
	}
	else if(localName.equals("Tuple")){
		row = (ResultTuple)unmarshaller.unmarshal(reader);
	}
	if(columns==null){
		columns = buildColumns(row.getAnswers(),srq);
	}
	List<Object> rowData = row.getAnswers();
	HashMap<String,Object> sampleRowValues = new LinkedHashMap<String,Object>();
   	for(int colNum=0; colNum<columns.size(); colNum++){
   		QueryResultColumn column = columns.get(colNum);
		sampleRowValues.put(column.getName(),rowData.get(colNum));
   	}
   	return sampleRowValues;
}
 
Example 33
Project: FinanceAnalytics   File: SchemaVersionParser.java   View source code 6 votes vote down vote up
private StartElement findRootElement() throws XMLStreamException {

    s_logger.debug("Attempting to find root element for document");

    // Work through the elements in the document until we hit a start element
    for (XMLEventReader eventReader = createXmlEventReader(); eventReader.hasNext(); ) {
      XMLEvent event = eventReader.nextEvent();
      if (event.isStartElement()) {

        // We've found the first proper element in the document, it may be
        // what we're looking for or it may be incorrect but either way we
        // don't need to read any more of the file
        s_logger.debug("Found root element: [{}]", event);
        return (StartElement) event;
      }
    }
    throw new OpenGammaRuntimeException("No root element was found - unable to parse file");
  }
 
Example 34
Project: jcode   File: StaxEventParser.java   View source code 6 votes vote down vote up
private void printUsers(XMLEventReader reader) throws XMLStreamException {
	XMLEvent event = reader.nextEvent();
	while (true) {
		if (event.isStartElement()) {
			StartElement e = event.asStartElement();
			if ("user".equalsIgnoreCase(e.getName().toString())) {
				System.out.println("Name:" + getAttributeValue(e, "name")
						+ ";age=" + getAttributeValue(e, "age")
						+ ";gender=" + getAttributeValue(e, "gender"));
			}
		} else if (event.isEndDocument()) {
			break;
		}
		event = reader.nextEvent();
	}
}
 
Example 35
Project: datasource   File: XmlFileRecordReader.java   View source code 6 votes vote down vote up
/**
 * @param dataFile
 * @throws FileNotFoundException
 * @throws XMLStreamException
 * @throws JAXBException
 */
private void initialize(InputStream is) throws FileNotFoundException, XMLStreamException, JAXBException {
	this.is = is;
	ctx = JAXBContext.newInstance(entryClass);
	um = ctx.createUnmarshaller();
	XMLInputFactory xmlif = XMLInputFactory.newInstance();
	xmler = xmlif.createXMLEventReader(is);
	EventFilter filter = new EventFilter() {
		public boolean accept(XMLEvent event) {
			return event.isStartElement();
		}
	};
	xmlfer = xmlif.createFilteredReader(xmler, filter);
	// Jump to the first element in the document, the enclosing Uniprot in
	// the case of uniprot
	// xml
	StartElement e = (StartElement) xmlfer.nextEvent();
	advanceToRecordWithTaxonOfInterest();
}
 
Example 36
Project: JavaMainRepo   File: EntityRepository.java   View source code 6 votes vote down vote up
public static void createNode(XMLEventWriter eventWriter, String name, String value) throws XMLStreamException {
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
XMLEvent end = eventFactory.createDTD("\n");
XMLEvent tab = eventFactory.createDTD("\t");
// Create Start node
StartElement sElement = eventFactory.createStartElement("", "", name);
eventWriter.add(tab);
eventWriter.add(sElement);
// Create Content
Characters characters = eventFactory.createCharacters(value);
eventWriter.add(characters);
// Create End node
EndElement eElement = eventFactory.createEndElement("", "", name);
eventWriter.add(eElement);
eventWriter.add(end);
}
 
Example 37
Project: JavaMainRepo   File: EntityRepository.java   View source code 6 votes vote down vote up
public static void createNode(XMLEventWriter eventWriter, String name, String value) throws XMLStreamException {
	XMLEventFactory eventFactory = XMLEventFactory.newInstance();
	XMLEvent end = eventFactory.createDTD("\n");
	XMLEvent tab = eventFactory.createDTD("\t");
	// Create Start node
	StartElement sElement = eventFactory.createStartElement("", "", name);
	eventWriter.add(tab);
	eventWriter.add(sElement);
	// Create Content
	Characters characters = eventFactory.createCharacters(value);
	eventWriter.add(characters);
	// Create End node
	EndElement eElement = eventFactory.createEndElement("", "", name);
	eventWriter.add(eElement);
	eventWriter.add(end);
}
 
Example 38
Project: JavaMainRepo   File: EntityRepository.java   View source code 6 votes vote down vote up
public void save(ArrayList<T> entities) throws FileNotFoundException, XMLStreamException {
	XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
	XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(new FileOutputStream(this.xmlFilename));
	XMLEventFactory eventFactory = XMLEventFactory.newInstance();
	XMLEvent end = eventFactory.createDTD("\n");
	StartDocument startDocument = eventFactory.createStartDocument();
	eventWriter.add(startDocument);
	StartElement configStartElement = eventFactory.createStartElement("", "", "content");
	eventWriter.add(configStartElement);
	eventWriter.add(end);

	for (XML_Parsable entity : entities) {
		StartElement sElement = eventFactory.createStartElement("", "", this.entityTag);
		eventWriter.add(sElement);
		eventWriter.add(end);
		entity.encodeToXml(eventWriter);

		EndElement eElement = eventFactory.createEndElement("", "", this.entityTag);
		eventWriter.add(eElement);
		eventWriter.add(end);
	}

	eventWriter.add(eventFactory.createEndElement("", "", "content"));
	eventWriter.add(eventFactory.createEndDocument());
	eventWriter.close();
}
 
Example 39
Project: JavaMainRepo   File: AnimalRepository.java   View source code 6 votes vote down vote up
public static void createNode(XMLEventWriter eventWriter, String name, String value) throws XMLStreamException {
	XMLEventFactory eventFactory = XMLEventFactory.newInstance();
	XMLEvent end = eventFactory.createDTD("\n");
	XMLEvent tab = eventFactory.createDTD("\t");
	// Create Start node
	StartElement sElement = eventFactory.createStartElement("", "", name);
	eventWriter.add(tab);
	eventWriter.add(sElement);
	// Create Content
	Characters characters = eventFactory.createCharacters(value);
	eventWriter.add(characters);
	// Create End node
	EndElement eElement = eventFactory.createEndElement("", "", name);
	eventWriter.add(eElement);
	eventWriter.add(end);
}
 
Example 40
Project: JavaMainRepo   File: EmployeeRepository.java   View source code 6 votes vote down vote up
public static void createNode(XMLEventWriter eventWriter, String name, String value) throws XMLStreamException {
	XMLEventFactory eventFactory = XMLEventFactory.newInstance();
	XMLEvent end = eventFactory.createDTD("\n");
	XMLEvent tab = eventFactory.createDTD("\t");
	// Create Start node
	StartElement sElement = eventFactory.createStartElement("", "", name);
	eventWriter.add(tab);
	eventWriter.add(sElement);
	// Create Content
	Characters characters = eventFactory.createCharacters(value);
	eventWriter.add(characters);
	// Create End node
	EndElement eElement = eventFactory.createEndElement("", "", name);
	eventWriter.add(eElement);
	eventWriter.add(end);
}