Example usage for org.xml.sax Attributes getQName

List of usage examples for org.xml.sax Attributes getQName

Introduction

In this page you can find the example usage for org.xml.sax Attributes getQName.

Prototype

public abstract String getQName(int index);

Source Link

Document

Look up an attribute's XML qualified (prefixed) name by index.

Usage

From source file:org.easyxml.parser.EasySAXParser.java

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
        throws SAXException {

    if (easyDocument == null) {
        easyDocument = new Document(qName);
        currentElement = easyDocument;/*www.  j  a v  a  2  s .com*/
        path = qName;
    } else {
        currentElement = new Element(qName, lastContainer);
        path += Element.DefaultElementPathSign + qName;
    }

    innerText.setLength(0);
    lastContainer = currentElement;

    int length = attributes.getLength();
    for (int i = 0; i < length; i++) {
        String name = attributes.getQName(i);
        String value = attributes.getValue(i);
        currentElement.addAttribute(name, value);
    }
}

From source file:org.eclipse.emf.mwe.internal.core.ast.parser.WorkflowParser.java

protected AbstractASTBase handleComp(final String name, final Attributes attributes) {
    if (attributes.getValue(FILE) != null) {
        final boolean inheritAll = attributes.getValue(INHERITALL) != null;
        final InclusionAST c = new InclusionAST(getLocation(), name, attributes.getValue(FILE),
                attributes.getValue(ID), inheritAll);
        if (attributes.getValue(CLASS) != null) {
            issues.addError("Attribute 'class' not allowed for inclusions : " + PROPERTY, c);
        }/*from  w  w  w.j  av a  2s.  c  o m*/
        for (int i = 0; i < attributes.getLength(); i++) {
            final String temp = attributes.getQName(i);
            if (!"".equals(temp) && !(FILE.equals(temp) || ID.equals(temp))) {
                c.addChild(new SimpleParamAST(getLocation(), temp, attributes.getValue(temp)));
            }
        }
        return c;
    } else if (attributes.getValue(IDREF) != null) {
        validateAttributes("reference " + name, attributes, new String[] { IDREF }, new String[0]);
        return new ReferenceAST(getLocation(), name, attributes.getValue(IDREF));
    } else if ((attributes.getValue(VALUE) != null) && (attributes.getValue(NAME) == null)) {
        validateAttributes("simpleparam " + name, attributes, new String[] { VALUE }, new String[] {});
        return new SimpleParamAST(getLocation(), name, attributes.getValue(VALUE));
    } else {
        final ComponentAST result = new ComponentAST(getLocation(), name, attributes.getValue(CLASS),
                attributes.getValue(ID));
        for (int i = 0; i < attributes.getLength(); i++) {
            final String temp = attributes.getQName(i);
            if (!"".equals(temp) && !(CLASS.equals(temp) || ID.equals(temp))) {
                result.addChild(new SimpleParamAST(getLocation(), temp, attributes.getValue(temp)));
            }
        }
        return result;
    }
}

From source file:org.eclipse.emf.mwe.internal.core.ast.parser.WorkflowParser.java

private void validateAttributes(final String eleName, final Attributes attributes, final String[] mandatory,
        final String[] optional) {
    final Set<String> mandatorySet = new HashSet<String>(Arrays.asList(mandatory));
    final Set<String> optionalSet = new HashSet<String>(Arrays.asList(optional));
    final Set<String> mandatoryFound = new HashSet<String>();
    for (int i = 0; i < attributes.getLength(); i++) {
        final String name = attributes.getQName(i);
        if ((name != null) && !name.trim().equals("")) {
            if (!(mandatorySet.contains(name) || optionalSet.contains(name))) {
                issues.addError("Unknown attribute " + name + " for element " + eleName, getLocation());
            }//from   ww w .ja  v  a  2 s  .com
        }
        if (mandatorySet.contains(name)) {
            mandatoryFound.add(name);
        }
    }
    mandatorySet.removeAll(mandatoryFound);
    if (!mandatorySet.isEmpty()) {
        for (final String name : mandatorySet) {
            issues.addError("Attribute " + name + " is mandatory for element " + eleName, getLocation());
        }
    }
}

From source file:org.eclipse.smila.connectivity.framework.crawler.web.parse.html.DOMBuilder.java

/**
 * Receive notification of the beginning of an element.
 * /* w  w  w .j  av a 2s . co  m*/
 * <p>
 * The Parser will invoke this method at the beginning of every element in the XML document; there will be a
 * corresponding endElement() event for every startElement() event (even when the element is empty). All of the
 * element's content will be reported, in order, before the corresponding endElement() event.
 * </p>
 * 
 * <p>
 * If the element name has a namespace prefix, the prefix will still be attached. Note that the attribute list
 * provided will contain only attributes with explicit values (specified or defaulted): #IMPLIED attributes will be
 * omitted.
 * </p>
 * 
 * @param ns
 *          The namespace of the node
 * @param localName
 *          The local part of the qualified name
 * @param name
 *          The element name.
 * @param atts
 *          The attributes attached to the element, if any.
 * 
 * @throws SAXException
 *           the SAX exception
 * 
 * @see #endElement
 * @see org.xml.sax.Attributes
 */
public void startElement(final String ns, final String localName, final String name, final Attributes atts)
        throws org.xml.sax.SAXException {

    Element elem;

    // Note that the namespace-aware call must be used to correctly
    // construct a Level 2 DOM, even for non-namespaced nodes.
    if ((null == ns) || (ns.length() == 0)) {
        elem = m_doc.createElementNS(null, name);
    } else {
        elem = m_doc.createElementNS(ns, name);
    }

    append(elem);

    try {
        final int nAtts = atts.getLength();

        if (0 != nAtts) {
            for (int i = 0; i < nAtts; i++) {

                // First handle a possible ID attribute
                if (atts.getType(i).equalsIgnoreCase("ID")) {
                    setIDAttribute(atts.getValue(i), elem);
                }

                String attrNS = atts.getURI(i);

                if ("".equals(attrNS)) {
                    attrNS = null; // DOM represents no-namespace as null
                }

                // System. out.println("attrNS: "+attrNS+", localName: "+atts.getQName(i)
                // +", qname: "+atts.getQName(i)+", value: "+atts.getValue(i));
                // Crimson won't let us set an xmlns: attribute on the DOM.
                final String attrQName = atts.getQName(i);

                // In SAX, xmlns: attributes have an empty namespace, while in DOM they should have the xmlns namespace
                if (attrQName.startsWith("xmlns:")) {
                    attrNS = "http://www.w3.org/2000/xmlns/";
                }

                // ALWAYS use the DOM Level 2 call!
                elem.setAttributeNS(attrNS, attrQName, atts.getValue(i));
            }
        }

        // append(elem);

        m_elemStack.push(elem);

        m_currentNode = elem;

        // append(elem);
    } catch (final java.lang.Exception de) {
        if (LOG.isErrorEnabled()) {
            LOG.error(de);
        }
        throw new org.xml.sax.SAXException(de);
    }

}

From source file:org.exolab.castor.xml.parsing.AttributeSetBuilder.java

/**
 * Processes the attributes and XML name space declarations found in the given SAX Attributes. The
 * global {@link AttributeSet} is cleared and updated with the attributes. XML name space
 * declarations are added to the set of name spaces in scope.
 * /* w ww .j  a v  a 2s  .c  o m*/
 * @param atts the Attributes to process (can be null).
 **/
private AttributeSet processAttributes(Attributes atts, AttributeSetImpl attributeSet) {
    // -- process attributes

    if (atts == null || atts.getLength() == 0) {
        return attributeSet;
    }

    boolean hasQNameAtts = false;
    // -- look for any potential namespace declarations
    // -- in case namespace processing was disable
    // -- on the parser
    for (int i = 0; i < atts.getLength(); i++) {
        String attName = atts.getQName(i);
        if (StringUtils.isNotEmpty(attName)) {
            if (!attName.equals(XMLNS) && !attName.startsWith(XMLNS_PREFIX)) {
                // -- check for prefix
                if (attName.indexOf(':') < 0) {
                    attributeSet.setAttribute(attName, atts.getValue(i), atts.getURI(i));
                } else
                    hasQNameAtts = true;
            }
        } else {
            // -- if attName is null or empty, just process as a normal
            // -- attribute
            attName = atts.getLocalName(i);
            if (!XMLNS.equals(attName)) {
                attributeSet.setAttribute(attName, atts.getValue(i), atts.getURI(i));
            }
        }
    }

    // return if there are no qualified name attributes
    if (!hasQNameAtts) {
        return attributeSet;
    }
    // -- if we found any qName-only atts, process those
    for (int i = 0; i < atts.getLength(); i++) {
        String attName = atts.getQName(i);
        if (StringUtils.isNotEmpty(attName)) {
            // -- process any non-namespace qName atts
            if ((!attName.equals(XMLNS)) && (!attName.startsWith(XMLNS_PREFIX))) {
                int idx = attName.indexOf(':');
                if (idx >= 0) {
                    String prefix = attName.substring(0, idx);
                    attName = attName.substring(idx + 1);
                    String nsURI = atts.getURI(i);
                    if (StringUtils.isEmpty(nsURI)) {
                        nsURI = _namespaceHandling.getNamespaceURI(prefix);
                    }
                    attributeSet.setAttribute(attName, atts.getValue(i), nsURI);
                }
            }
        }
        // -- else skip already processed in previous loop
    }
    return attributeSet;
}

From source file:org.gbif.dwca.model.factory.CallParamNoNSRule.java

@Override
public void begin(Attributes attributes) throws Exception {
    Object param = null;/*from  w w w .j  a va2 s .  com*/
    for (int i = 0; i < attributes.getLength(); i++) {

        // if it has no prefix, or has SOME prefix and ends in the attribute name
        // (___:attributeName)
        if (attributes.getQName(i).equals(attributeName)
                || attributes.getQName(i).endsWith(":" + attributeName)) {
            param = attributes.getValue(i);
            break;
        }
    }
    // add to the params stack
    if (param != null) {
        Object parameters[] = (Object[]) digester.peekParams();
        parameters[paramIndex] = param;
    }
}

From source file:org.gbif.dwca.model.factory.ThesaurusHandlingRule.java

@Override
public void begin(String namespace, String name, Attributes attributes) throws Exception {

    for (int i = 0; i < attributes.getLength(); i++) {
        if (ThesaurusHandlingRule.ATTRIBUTE_THESAURUS.equals(attributes.getQName(i))) {
            Vocabulary tv = null;//from  www.j  ava  2  s .  c  o m
            try {
                URL vocabURL = new URL(attributes.getValue(i));
                tv = vocabManager.get(vocabURL);
            } catch (Exception e) {
                log.error("Could not load vocabulary with location {}: {}",
                        new Object[] { attributes.getValue(i), e.getMessage(), e });
            }

            if (tv != null) {
                Object extensionPropertyAsObject = getDigester().peek();
                if (extensionPropertyAsObject instanceof ExtensionProperty) {
                    ExtensionProperty eProperty = (ExtensionProperty) extensionPropertyAsObject;
                    eProperty.setVocabulary(tv);
                    log.debug("Vocabulary with URI[{}] added to extension property", tv.getUri());
                }
            } else {
                log.warn("No vocabulary exists for the URL[{}]", attributes.getValue(i));
            }

            break; // since we found the attribute
        }
    }
}

From source file:org.infoscoop.request.filter.rss.RssHandler.java

void writeStartElement(String uri, String localName, String qName, Attributes attributes, Writer writer)
        throws SAXException {
    //System.out.println("writeStartElement");
    try {/*from   www .j ava 2 s .  c  o m*/
        writer.write("<" + localName);
        for (int i = 0; i < attributes.getLength(); i++) {
            String qname = attributes.getQName(i);
            String value = attributes.getValue(i);
            writer.write(" " + qname + "=\"" + XmlUtil.escapeXmlEntities(value) + "\"");
        }
        writer.write(">");
    } catch (IOException e) {
        throw new SAXException(e);
    }
}

From source file:org.intermine.pathquery.PathQueryHandler.java

/**
 * {@inheritDoc}//from   w w w. j a  va 2  s.c o  m
 */
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
    if (valueBuffer != null) {
        throw new SAXException("Cannot have any tags inside a value tag");
    }
    if ((constraintPath != null) && !("value".equals(qName) || "nullValue".equals(qName))) {
        throw new SAXException("Cannot have anything other than value tag inside a constraint");
    }
    if ("query-list".equals(qName)) {
        // Do nothing
    } else if ("query".equals(qName)) {
        queryName = validateName(attrs.getValue("name"));
        String modelName = attrs.getValue("model");
        if (models.containsKey(modelName)) {
            model = models.get(modelName);
        } else {
            try {
                model = Model.getInstanceByName(attrs.getValue("model"));
            } catch (Exception e) {
                throw new SAXException(e);
            }
        }
        query = new PathQuery(model);

        if (attrs.getValue("title") != null && !attrs.getValue("title").isEmpty()) {
            query.setTitle(attrs.getValue("title"));
        }

        if (attrs.getValue("longDescription") != null) {
            query.setDescription(attrs.getValue("longDescription"));
        }
        if (attrs.getValue("view") != null) {
            String view = attrs.getValue("view");
            if (view.contains(":")) {
                // This is an old style query, and we need to convert the colons into outer
                // joins
                String[] viewPathArray = PathQuery.SPACE_SPLITTER.split(view.trim());
                for (String viewPath : viewPathArray) {
                    setOuterJoins(query, viewPath);
                }
                view = view.replace(':', '.');
            }
            query.addViewSpaceSeparated(view);
        }
        String so = attrs.getValue("sortOrder");
        if (!StringUtils.isBlank(so)) {
            if (so.indexOf(' ') < 0) {
                // be accomodating of input as possible - assume asc.
                so += " asc";
            }
            query.addOrderBySpaceSeparated(so);
        }
        constraintLogic = attrs.getValue("constraintLogic");
        questionableSubclasses = new ArrayList<PathConstraintSubclass>();
    } else if ("node".equals(qName)) {
        // There's a node tag, so all constraints inside must inherit this path. Set it in a
        // variable, and reset the variable to null when we see the end tag.

        currentNodePath = attrs.getValue("path");
        if (currentNodePath.contains(":")) {
            setOuterJoins(query, currentNodePath);
            currentNodePath = currentNodePath.replace(':', '.');
        }
        String type = attrs.getValue("type");
        if ((type != null) && (!ATTRIBUTE_TYPES.contains(type))
                && (currentNodePath.contains(".") || currentNodePath.contains(":"))) {
            PathConstraintSubclass subclass = new PathConstraintSubclass(currentNodePath, type);
            query.addConstraint(subclass);
            questionableSubclasses.add(subclass);
        }
    } else if ("constraint".equals(qName)) {
        String path = attrs.getValue("path");
        if (currentNodePath != null) {
            if (path != null) {
                throw new SAXException("Cannot set path in a constraint inside a node");
            }
            path = currentNodePath;
        }
        String code = attrs.getValue("code");
        String type = attrs.getValue("type");
        if (type != null) {
            query.addConstraint(new PathConstraintSubclass(path, type));
        } else {
            path = path.replace(':', '.');
            constraintPath = path;
            constraintAttributes = new HashMap<String, String>();
            for (int i = 0; i < attrs.getLength(); i++) {
                constraintAttributes.put(attrs.getQName(i), attrs.getValue(i));
            }
            constraintValues = new LinkedHashSet<String>();
            constraintCode = code;
        }
    } else if ("pathDescription".equals(qName)) {
        String pathString = attrs.getValue("pathString");
        String description = attrs.getValue("description");

        // Descriptions should only refer to classes that appear in the view, which we have
        // already read.  This check makes sure the description is for a class that has
        // attributes on the view list before adding it.  We ignore invalid descriptions to
        // cope with legacy bad validation of qyery XML.
        if (pathString.endsWith(".")) {
            throw new SAXException("Invalid path '" + pathString + "' for description: " + description);
        }
        String pathToCheck = pathString + ".";
        for (String viewString : query.getView()) {
            if (viewString.startsWith(pathToCheck)) {
                query.setDescription(pathString, description);
                break;
            }
        }
    } else if ("join".equals(qName)) {
        String pathString = attrs.getValue("path");
        String type = attrs.getValue("style");
        if ("INNER".equals(type.toUpperCase())) {
            query.setOuterJoinStatus(pathString, OuterJoinStatus.INNER);
        } else if ("OUTER".equals(type.toUpperCase())) {
            query.setOuterJoinStatus(pathString, OuterJoinStatus.OUTER);
        } else {
            throw new SAXException("Unknown join style " + type + " for path " + pathString);
        }
    } else if ("value".equals(qName)) {
        valueBuffer = new StringBuilder();
    }
}

From source file:org.intermine.template.xml.TemplateQueryHandler.java

/**
 * {@inheritDoc}/*from w w w  .  j ava 2  s. c  o m*/
 */
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
    if ("template".equals(qName)) {
        templateName = attrs.getValue("name");
        templateTitle = attrs.getValue("title");
        templateComment = attrs.getValue("comment");
    } else if ("constraint".equals(qName)) {
        String path = attrs.getValue("path");
        if (currentNodePath != null) {
            if (path != null) {
                throw new SAXException("Cannot set path in a constraint inside a node");
            }
            path = currentNodePath;
        }
        String code = attrs.getValue("code");
        String type = attrs.getValue("type");
        if (type != null) {
            query.addConstraint(new PathConstraintSubclass(path, type));
        } else {
            path = path.replace(':', '.');
            if (path == null) {
                throw new NullPointerException("Null path while processing template " + templateName);
            }
            constraintPath = path;
            constraintAttributes = new HashMap<String, String>();
            for (int i = 0; i < attrs.getLength(); i++) {
                constraintAttributes.put(attrs.getQName(i), attrs.getValue(i));
            }
            constraintValues = new LinkedHashSet<String>();
            constraintCode = code;

        }
    } else {
        super.startElement(uri, localName, qName, attrs);
    }
}