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

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

Introduction

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

Prototype

QName getName();

Source Link

Document

Returns the QName for this attribute

Usage

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.
 * //from  w ww.  ja  va  2  s.com
 * @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

/**
 * Returns the qualified name of the attribute
 *
 * @param a//  w w w  .j  a v a  2  s  . c  o  m
 *          an attribute event
 * @param enabledNamespaces
 *          indicates if namespaces should be added or not
 * @return the qualified name of the attribute
 */
private String getAttributeName(Attribute a, boolean enabledNamespaces) {
    if (!enabledNamespaces) {
        return a.getName().getLocalPart();
    } else {
        return getName(a.getName().getPrefix(), a.getName().getLocalPart());
    }
}

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);
                }//from   w ww .  j  av  a 2 s  .  co m
            }
            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.docproxy.url.UrlRepositoryProcessor.java

/**
 * Parse the attributes of an XML 'document' element into a {@link UrlDocumentResult}.
 * /*from  www  . j a v a 2 s .c  om*/
 * @param startEl
 *          The 'document' element to process.
 * @param doc
 *          The document to set attributes into. If null, a new
 *          {@link UrlDocumentResult} is created.
 * @return A {@link UrlDocumentResult} containing values found in {@link startEl}. This
 *         will be the provided doc, if it is not null, or a newly created one.
 * @throws XMLStreamException
 *           If there is a problem processing the element.
 */
private UrlDocumentResult parseDocument(StartElement startEl, UrlDocumentResult doc) throws XMLStreamException {

    UrlDocumentResult _doc = null;
    if (doc != null) {
        _doc = doc;
    } else {
        _doc = new UrlDocumentResult();
    }

    @SuppressWarnings("unchecked")
    Iterator<Attribute> attrs = startEl.getAttributes();

    while (attrs.hasNext()) {
        Attribute attr = attrs.next();
        QName attrName = attr.getName();
        String attrLocalName = attrName.getLocalPart();

        // collect the uri
        if ("uri".equalsIgnoreCase(attrLocalName)) {
            _doc.setUri(attr.getValue());
            continue;
        }

        // collect the content length
        if ("contentLength".equalsIgnoreCase(attrLocalName)) {
            _doc.setContentLength(Long.parseLong(attr.getValue()));
            continue;
        }

        // collect the content length
        if ("contentType".equalsIgnoreCase(attrLocalName)) {
            _doc.setContentType(attr.getValue());
            continue;
        }
    }

    return _doc;
}

From source file:org.slc.sli.ingestion.parser.impl.EdfiRecordParserImpl.java

@SuppressWarnings("unchecked")
private void parseEventAttributes(StartElement startElement) {
    Iterator<Attribute> it = startElement.getAttributes();
    while (it.hasNext()) {
        Attribute a = it.next();
        complexTypeStack.peek().getRight().put("@" + a.getName().getLocalPart(), a.getValue());
    }//from   w  w w .j av a  2s  . co m
}