Example usage for javax.xml.stream.events Attribute getValue

List of usage examples for javax.xml.stream.events Attribute getValue

Introduction

In this page you can find the example usage for javax.xml.stream.events Attribute getValue.

Prototype

public String getValue();

Source Link

Document

Gets the normalized value of this attribute

Usage

From source file:org.modeldriven.fuml.xmi.stream.StreamNode.java

public String getXmiId() {
    QName typeAttrib = new QName(context.getXmiNamespace().getNamespaceURI(), XmiConstants.ATTRIBUTE_XMI_ID);
    Attribute attrib = startElementEvent.asStartElement().getAttributeByName(typeAttrib);
    if (attrib != null) {
        String value = attrib.getValue();
        return value;
    }//from   w  w  w. j a va 2 s . c  om

    return null;
}

From source file:org.modeldriven.fuml.xmi.XmiInternalReferenceElement.java

private void construct() {
    String data = this.node.getData();
    if (data != null) {
        StringTokenizer st = new StringTokenizer(data);
        if (!st.hasMoreElements())
            throw new XmiException("one or more id's expected");
        while (st.hasMoreElements()) {
            String ref = st.nextToken();
            ids.add(ref);//  w  w  w  .  j a v a  2s.  c  om
        }
    } else {
        StreamNode eventNode = (StreamNode) node;
        QName name = new QName(eventNode.getContext().getXmiNamespace().getNamespaceURI(),
                XmiConstants.ATTRIBUTE_XMI_IDREF);
        Attribute idref = eventNode.getAttribute(name);
        if (idref != null) {
            ids.add(idref.getValue());
        } else
            throw new XmiException(
                    "expected character data or idref attribute for element, " + eventNode.getLocalName());
    }
}

From source file:org.odftoolkit.odfdom.pkg.rdfa.URIExtractorImpl.java

public String getURI(StartElement element, Attribute attr, EvalContext context) {
    QName attrName = attr.getName();
    if (Util.qNameEquals(attrName, Constants.about)) // Safe CURIE or URI
    {//from   w  w  w . j a  v  a  2s.c  om
        return expandSafeCURIE(element, attr.getValue(), context);
    }
    if (Util.qNameEquals(attrName, Constants.datatype)) // A CURIE
    {
        return expandCURIE(element, attr.getValue(), context);
    }
    throw new RuntimeException("Unexpected attribute: " + attr);
}

From source file:org.odftoolkit.odfdom.pkg.rdfa.URIExtractorImpl.java

public List<String> getURIs(StartElement element, Attribute attr, EvalContext context) {

    List<String> uris = new LinkedList<String>();

    String[] curies = attr.getValue().split("\\s+");
    boolean permitReserved = Util.qNameEquals(Constants.rel, attr.getName())
            || Util.qNameEquals(Constants.rev, attr.getName());
    for (String curie : curies) {
        if (Constants.SpecialRels.contains(curie.toLowerCase())) {
            if (permitReserved)
                uris.add("http://www.w3.org/1999/xhtml/vocab#" + curie.toLowerCase());
        } else {//from   w w  w . ja  v a2 s  . c om
            String uri = expandCURIE(element, curie, context);
            if (uri != null) {
                uris.add(uri);
            }
        }
    }
    return uris;
}

From source file:org.omegat.util.TMXReader2.java

protected void parseTuv(StartElement element) throws Exception {
    ParsedTuv tuv = new ParsedTuv();
    currentTu.tuvs.add(tuv);//from   w w w .ja  va 2s  .c om

    tuv.changeid = getAttributeValue(element, "changeid");
    tuv.changedate = parseISO8601date(getAttributeValue(element, "changedate"));
    tuv.creationid = getAttributeValue(element, "creationid");
    tuv.creationdate = parseISO8601date(getAttributeValue(element, "creationdate"));

    // find 'lang' or 'xml:lang' attribute
    for (Iterator<?> it = element.getAttributes(); it.hasNext();) {
        Attribute a = (Attribute) it.next();
        if ("lang".equals(a.getName().getLocalPart())) {
            tuv.lang = a.getValue();
            break;
        }
    }

    while (true) {
        XMLEvent e = xml.nextEvent();
        switch (e.getEventType()) {
        case XMLEvent.START_ELEMENT:
            StartElement eStart = (StartElement) e;
            if ("seg".equals(eStart.getName().getLocalPart())) {
                if (isOmegaT) {
                    parseSegOmegaT();
                } else if (extTmxLevel2) {
                    parseSegExtLevel2();
                } else {
                    parseSegExtLevel1();
                }
                tuv.text = StringUtil.normalizeUnicode(segContent);
            }
            break;
        case XMLEvent.END_ELEMENT:
            EndElement eEnd = (EndElement) e;
            if ("tuv".equals(eEnd.getName().getLocalPart())) {
                return;
            }
            break;
        }
    }
}

From source file:org.omegat.util.TMXReader2.java

private static String getAttributeValue(StartElement e, String attrName) {
    Attribute a = e.getAttributeByName(new QName(attrName));
    return a != null ? a.getValue() : null;
}

From source file:org.omnaest.utils.xml.XMLNestedMapConverter.java

/**
 * Template method for {@link #newNamespaceAwareMapFromXML(CharSequence)} and {@link #newMapFromXML(CharSequence)} which allows
 * to convert the {@link QName} based key values to other representations.
 * //ww w  .  j  a v  a 2  s. co  m
 * @param xmlContent
 * @return new (nested) {@link Map} instance
 */
protected <K> Map<K, Object> newMapFromXML(CharSequence xmlContent,
        final ElementConverter<QName, K> keyElementConverter) {
    //
    final Map<K, Object> retmap = new LinkedHashMap<K, Object>();

    //
    Assert.isNotNull(keyElementConverter, "keyElementConverter must not be null");

    //
    final ExceptionHandler exceptionHandler = this.exceptionHandler;

    //    
    try {
        //
        final XMLInputFactory xmlInputFactory = this.xmlInstanceContextFactory.newXmlInputFactory();
        Assert.isNotNull(xmlInputFactory, "xmlInputFactory must not be null");

        //
        final Reader reader = new CharSequenceReader(xmlContent);
        final XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(reader);

        //
        final class Helper {
            /* ********************************************** Variables ********************************************** */
            private List<TupleTwo<QName, Object>> stackList = new ArrayList<TupleTwo<QName, Object>>();

            /* ********************************************** Methods ********************************************** */

            /**
             * Manifests a single tag node recursively
             * 
             * @return
             * @throws XMLStreamException
             */
            @SuppressWarnings("unchecked")
            public TupleTwo<QName, Object> manifest() throws XMLStreamException {
                //
                TupleTwo<QName, Object> retval = null;

                //          
                while (xmlEventReader.hasNext()) {
                    //
                    final XMLEvent xmlEvent = xmlEventReader.nextEvent();

                    //
                    if (xmlEvent.isStartElement()) {
                        //
                        final StartElement startElement = xmlEvent.asStartElement();
                        final QName name = startElement.getName();

                        //
                        this.addNewStackElement().setValueFirst(name);

                        //
                        final Iterator<Attribute> attributeIterator = startElement.getAttributes();
                        if (attributeIterator.hasNext()) {
                            //
                            final Map<QName, Object> map = new LinkedHashMap<QName, Object>();
                            for (Attribute attribute : IterableUtils.valueOf(attributeIterator)) {
                                map.put(attribute.getName(), attribute.getValue());
                            }

                            //
                            this.updateCurrentStackValue(map);
                        }
                    } else if (xmlEvent.isEndElement()) {
                        //
                        retval = this.removeStackElement();

                        //
                        final Object manifestation = retval.getValueSecond();
                        final QName tagname = retval.getValueFirst();

                        //
                        updateCurrentStackValue(manifestation, tagname);
                    } else if (xmlEvent.isCharacters()) {
                        //
                        final Characters characters = xmlEvent.asCharacters();
                        if (!characters.isWhiteSpace()) {
                            //
                            final TupleTwo<QName, Object> currentStackValue = this.getCurrentStackValue();
                            currentStackValue.setValueSecond(
                                    ObjectUtils.defaultIfNull(currentStackValue.getValueSecond(), "")
                                            + characters.getData());

                        }
                    }

                }

                //
                return retval;
            }

            /**
             * Updates the current stack value
             * 
             * @param manifestation
             * @param tagname
             */
            private void updateCurrentStackValue(Object manifestation, QName tagname) {
                //
                final Map<QName, Object> tagNameToManifestationMap = new LinkedHashMap<QName, Object>();
                tagNameToManifestationMap.put(tagname, manifestation);
                this.updateCurrentStackValue(tagNameToManifestationMap);
            }

            @SuppressWarnings("unchecked")
            private void updateCurrentStackValue(Map<QName, Object> tagNameToManifestationMap) {
                //
                final TupleTwo<QName, Object> currentStackValue = this.getCurrentStackValue();

                //
                if (currentStackValue != null) {
                    //
                    Map<K, Object> map = null;
                    {
                        //
                        final Object valueSecond = currentStackValue.getValueSecond();
                        if (valueSecond instanceof Map) {
                            map = (Map<K, Object>) valueSecond;
                        } else {
                            //
                            map = new LinkedHashMap<K, Object>();
                            if (valueSecond instanceof String) {
                                map.put(keyElementConverter.convert(new QName("")), valueSecond);
                            }
                        }
                    }

                    //
                    for (Entry<QName, Object> tagNameToManifestationEntry : tagNameToManifestationMap
                            .entrySet()) {
                        //
                        final K tagname = keyElementConverter.convert(tagNameToManifestationEntry.getKey());
                        final Object manifestation = tagNameToManifestationEntry.getValue();

                        //
                        if (!map.containsKey(tagname)) {
                            map.put(tagname, manifestation);
                        } else {
                            //
                            final Object object = map.get(tagname);
                            if (object instanceof List) {
                                //
                                final List<Object> list = (List<Object>) object;
                                list.add(manifestation);
                            } else {
                                //
                                final List<Object> list = new ArrayList<Object>();
                                list.add(object);
                                list.add(manifestation);
                                map.put(tagname, list);
                            }
                        }
                    }

                    //
                    currentStackValue.setValueSecond(map);
                }
            }

            private TupleTwo<QName, Object> getCurrentStackValue() {
                return ListUtils.firstElement(this.stackList);
            }

            private TupleTwo<QName, Object> removeStackElement() {
                return ListUtils.removeFirst(this.stackList);
            }

            private TupleTwo<QName, Object> addNewStackElement() {
                //
                final TupleTwo<QName, Object> retval = new TupleTwo<QName, Object>();
                this.stackList.add(0, retval);
                return retval;
            }
        }

        //  
        try {
            final Helper helper = new Helper();
            final TupleTwo<QName, Object> result = helper.manifest();
            retmap.put(keyElementConverter.convert(result.getValueFirst()), result.getValueSecond());
        } catch (Exception e) {
            if (exceptionHandler != null) {
                exceptionHandler.handleException(e);
            }
        }

        //
        xmlEventReader.close();
        reader.close();

    } catch (Exception e) {
        if (exceptionHandler != null) {
            exceptionHandler.handleException(e);
        }
    }

    //
    return retmap;
}

From source file:org.pentaho.di.trans.steps.xmlinputstream.XMLInputStream.java

private void parseAttribute(Object[] outputRowDataAttribute, Attribute a, boolean enabledNamespaces) {
    if (data.pos_xml_data_name != -1) {
        outputRowDataAttribute[data.pos_xml_data_name] = getAttributeName(a, enabledNamespaces);
    }//from   ww  w. j a  v a  2  s . co  m
    if (data.pos_xml_data_value != -1) {
        outputRowDataAttribute[data.pos_xml_data_value] = a.getValue();
    }
}

From source file:org.plasma.sdo.xml.StreamUnmarshaller.java

@SuppressWarnings("unchecked")
private void readAttributes(XMLEvent event, StreamObject prototype) throws UnmarshallerException {
    boolean serialIdAttributeFound = false;
    PlasmaType type = prototype.getType();
    Iterator<Attribute> iter = event.asStartElement().getAttributes();
    while (iter.hasNext()) {
        Attribute attrib = (Attribute) iter.next();
        QName attribName = attrib.getName();
        String localPart = attribName.getLocalPart();
        if (XMLConstants.ATTRIB_TARGET_NAMESPACE.equals(localPart)) {
            continue;
        } else if (XMLConstants.XMLSCHEMA_INSTANCE_NAMESPACE_URI.equals(attribName.getNamespaceURI())) {
            // its an XSI attribute we care about
            if ("type".equals(localPart)) {
                String xsiTypeLocalName = attrib.getValue();
                int delim = xsiTypeLocalName.indexOf(":");
                if (delim >= 0)
                    xsiTypeLocalName = xsiTypeLocalName.substring(delim + 1);
                // In order to validate XML graphs with both containment
                // and non containment references with an XML schema,
                // the Schema types must be generated with XSI 'xsi:type'
                // attribute to indicate a subclass. The subclass name will be
                // either 1.) matching the local for the type, wherein we
                // assume a containment reference or 2.) matching a generated
                // synthetic name for the non-containment reference for the
                // type, e.g. 'MyTypeRef'. So for containment references
                // we should find 'xsi:type="prefix:MyType" and for 
                // non-containment references we should find 'xsi:type="prefix:MyTypeRef"
                // or some other generated suffix with no name collisions. 
                if (!xsiTypeLocalName.equals(type.getLocalName())) {
                    if (log.isDebugEnabled())
                        log.debug("type as non-containment reference, " + type.getURI() + "#" + type.getName());
                    prototype.setNonContainmentReference(true);
                }//  w w w  .  j a v a  2s.c  om
            }
            continue;
        }

        PlasmaProperty property = findPropertyByLocalName(type, localPart);
        if (property == null) {
            if (!SchemaUtil.getSerializationAttributeName().equals(localPart)) {
                Location loc = event.getLocation();
                String msg = "line:col[" + loc.getLineNumber() + ":" + loc.getColumnNumber() + "]";
                msg += " - no property '" + localPart + "' found defined for type " + type.getURI() + "#"
                        + type.getName();
                throw new UnmarshallerException(msg);
            } else {
                prototype.setSerialId(attrib.getValue());
                serialIdAttributeFound = true;
                continue;
            }
        }

        if (property.getType().isDataType()) {
            if (property.isMany()) {
                Location loc = event.getLocation();
                String msg = "line:col[" + loc.getLineNumber() + ":" + loc.getColumnNumber() + "]";
                msg += " - unexpected 'many' propery (" + type.getURI() + "#" + type.getName() + "."
                        + property.getName() + ") can only set singular properties from attribute '" + localPart
                        + "'";
                throw new UnmarshallerException(msg);
            }
            Object value = PlasmaDataHelper.INSTANCE.convert(property, attrib.getValue());
            if (!property.isReadOnly()) {
                prototype.set(property, value);
            } else {
                DataFlavor dataFlavor = property.getDataFlavor();
                switch (dataFlavor) {
                case integral:
                    Location loc = event.getLocation();
                    String msg = "line:col[" + loc.getLineNumber() + ":" + loc.getColumnNumber() + "]";
                    msg += " - cannot set integral readonly propery (" + property.getName()
                            + ") - ignoring attribute data '" + attrib.getValue() + "' for readonly propery, "
                            + type.getURI() + "#" + type.getName() + "." + property.getName();
                    log.warn(msg);
                    break;
                default:
                    prototype.set(property, value);
                }
            }
        } else {
            Location loc = event.getLocation();
            String msg = "line:col[" + loc.getLineNumber() + ":" + loc.getColumnNumber() + "]";
            msg += " - expected datatype property - attribute '" + localPart
                    + "' is a reference property as defined in type " + type.getURI() + "#" + type.getName();
            throw new UnmarshallerException(msg);
        }
    }

    if (!serialIdAttributeFound) {
        Location loc = event.getLocation();
        String msg = "line:col[" + loc.getLineNumber() + ":" + loc.getColumnNumber() + "]";
        msg += " - expected serialization attribute '" + SchemaUtil.getSerializationAttributeName()
                + "' for type " + type.getURI() + "#" + type.getName();
        throw new UnmarshallerException(msg);
    }
}

From source file:org.sakaiproject.nakamura.auth.cas.CasAuthenticationHandler.java

private String retrieveCredentials(String responseBody) {
    String username = null;//ww w.j  a v  a 2s . co m
    String pgtIou = null;
    String failureCode = null;
    String failureMessage = null;

    try {
        XMLInputFactory xmlInputFactory = new WstxInputFactory();
        xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
        xmlInputFactory.setProperty(XMLInputFactory.IS_VALIDATING, false);
        xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
        XMLEventReader eventReader = xmlInputFactory.createXMLEventReader(new StringReader(responseBody));

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

            // process the event if we're starting an element
            if (event.isStartElement()) {
                StartElement startEl = event.asStartElement();
                QName startElName = startEl.getName();
                String startElLocalName = startElName.getLocalPart();
                LOGGER.debug(responseBody);

                /*
                 * Example of failure XML
                <cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
                  <cas:authenticationFailure code='INVALID_REQUEST'>
                    &#039;service&#039; and &#039;ticket&#039; parameters are both required
                  </cas:authenticationFailure>
                </cas:serviceResponse>
                */
                if ("authenticationFailure".equalsIgnoreCase(startElLocalName)) {
                    // get code of the failure
                    Attribute code = startEl.getAttributeByName(QName.valueOf("code"));
                    failureCode = code.getValue();

                    // get the message of the failure
                    event = eventReader.nextEvent();
                    assert event.isCharacters();
                    Characters chars = event.asCharacters();
                    failureMessage = chars.getData();
                    break;
                }

                /*
                 * Example of success XML
                <cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
                  <cas:authenticationSuccess>
                    <cas:user>NetID</cas:user>
                  </cas:authenticationSuccess>
                </cas:serviceResponse>
                */
                if ("authenticationSuccess".equalsIgnoreCase(startElLocalName)) {
                    // skip to the user tag start
                    while (eventReader.hasNext()) {
                        event = eventReader.nextTag();
                        if (event.isEndElement()) {
                            if (eventReader.hasNext()) {
                                event = eventReader.nextTag();
                            } else {
                                break;
                            }
                        }
                        assert event.isStartElement();
                        startEl = event.asStartElement();
                        startElName = startEl.getName();
                        startElLocalName = startElName.getLocalPart();
                        if (proxy && "proxyGrantingTicket".equals(startElLocalName)) {
                            event = eventReader.nextEvent();
                            assert event.isCharacters();
                            Characters chars = event.asCharacters();
                            pgtIou = chars.getData();
                            LOGGER.debug("XML parser found pgt: {}", pgtIou);
                        } else if ("user".equals(startElLocalName)) {
                            // move on to the body of the user tag
                            event = eventReader.nextEvent();
                            assert event.isCharacters();
                            Characters chars = event.asCharacters();
                            username = chars.getData();
                            LOGGER.debug("XML parser found user: {}", username);
                        } else {
                            LOGGER.error("Found unexpected element [{}] while inside 'authenticationSuccess'",
                                    startElName);
                            break;
                        }
                        if (username != null && (!proxy || pgtIou != null)) {
                            break;
                        }
                    }
                }
            }
        }
    } catch (XMLStreamException e) {
        LOGGER.error(e.getMessage(), e);
    }

    if (failureCode != null || failureMessage != null) {
        LOGGER.error("Error response from server code={} message={}", failureCode, failureMessage);
    }
    String pgt = pgts.get(pgtIou);
    if (pgt != null) {
        savePgt(username, pgt, pgtIou);
    } else {
        LOGGER.debug("Caching '{}' as the IOU for '{}'", pgtIou, username);
        pgtIOUs.put(pgtIou, username);
    }
    return username;
}