Example usage for javax.xml.stream XMLStreamConstants START_ELEMENT

List of usage examples for javax.xml.stream XMLStreamConstants START_ELEMENT

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamConstants START_ELEMENT.

Prototype

int START_ELEMENT

To view the source code for javax.xml.stream XMLStreamConstants START_ELEMENT.

Click Source Link

Document

Indicates an event is a start element

Usage

From source file:nl.nn.adapterframework.validation.XSD.java

public void init() throws ConfigurationException {
    if (noNamespaceSchemaLocation != null) {
        url = ClassUtils.getResourceURL(classLoader, noNamespaceSchemaLocation);
        if (url == null) {
            throw new ConfigurationException("Cannot find [" + noNamespaceSchemaLocation + "]");
        }//w  w w.j  a  va 2s  . c om
        resourceTarget = noNamespaceSchemaLocation;
        toString = noNamespaceSchemaLocation;
    } else {
        if (resource != null) {
            url = ClassUtils.getResourceURL(classLoader, resource);
            if (url == null) {
                throw new ConfigurationException("Cannot find [" + resource + "]");
            }
            resourceTarget = resource;
            toString = resource;
            if (resourceInternalReference != null) {
                resourceTarget = resourceTarget + "-" + resourceInternalReference + ".xsd";
                toString = toString + "!" + resourceInternalReference;
            }
        } else if (sourceXsds == null) {
            throw new ConfigurationException(
                    "None of noNamespaceSchemaLocation, resource or mergedResources is specified");
        } else {
            resourceTarget = "[";
            toString = "[";
            boolean first = true;
            for (XSD xsd : sourceXsds) {
                if (first) {
                    first = false;
                } else {
                    resourceTarget = resourceTarget + ", ";
                    toString = toString + ", ";
                }
                resourceTarget = resourceTarget + xsd.getResourceTarget().replaceAll("/", "_");
                toString = toString + xsd.toString();
            }
            resourceTarget = resourceTarget + "].xsd";
            toString = toString + "]";
        }
        if (parentLocation == null) {
            this.parentLocation = "";
        }
    }
    try {
        InputStream in = getInputStream();
        XMLEventReader er = XmlUtils.INPUT_FACTORY.createXMLEventReader(in, XmlUtils.STREAM_FACTORY_ENCODING);
        int elementDepth = 0;
        while (er.hasNext()) {
            XMLEvent e = er.nextEvent();
            switch (e.getEventType()) {
            case XMLStreamConstants.START_ELEMENT:
                elementDepth++;
                StartElement el = e.asStartElement();
                if (el.getName().equals(SchemaUtils.SCHEMA)) {
                    Attribute a = el.getAttributeByName(SchemaUtils.TNS);
                    if (a != null) {
                        xsdTargetNamespace = a.getValue();
                    }
                    Iterator<Namespace> nsIterator = el.getNamespaces();
                    while (nsIterator.hasNext() && StringUtils.isEmpty(xsdDefaultNamespace)) {
                        Namespace ns = nsIterator.next();
                        if (StringUtils.isEmpty(ns.getPrefix())) {
                            xsdDefaultNamespace = ns.getNamespaceURI();
                        }
                    }
                } else if (el.getName().equals(SchemaUtils.IMPORT)) {
                    Attribute a = el.getAttributeByName(SchemaUtils.NAMESPACE);
                    if (a != null) {
                        boolean skip = false;
                        ArrayList ans = null;
                        if (StringUtils.isNotEmpty(getImportedNamespacesToIgnore())) {
                            ans = new ArrayList(Arrays.asList(getImportedNamespacesToIgnore().split(",")));
                        }
                        if (StringUtils.isNotEmpty(a.getValue()) && ans != null) {
                            if (ans.contains(a.getValue())) {
                                skip = true;
                            }
                        }
                        if (!skip) {
                            importedNamespaces.add(a.getValue());
                        }
                    }
                } else if (el.getName().equals(SchemaUtils.ELEMENT)) {
                    if (elementDepth == 2) {
                        rootTags.add(el.getAttributeByName(SchemaUtils.NAME).getValue());
                    }
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                elementDepth--;
                break;
            }
        }
        this.targetNamespace = xsdTargetNamespace;
        if (namespace == null) {
            // In case WsdlXmlValidator doesn't have schemaLocation
            namespace = xsdTargetNamespace;
        }
    } catch (IOException e) {
        String message = "IOException reading XSD";
        LOG.error(message, e);
        throw new ConfigurationException(message, e);
    } catch (XMLStreamException e) {
        String message = "XMLStreamException reading XSD";
        LOG.error(message, e);
        throw new ConfigurationException(message, e);
    }
}

From source file:nl.nn.adapterframework.validation.XSD.java

public Set<XSD> getXsdsRecursive(Set<XSD> xsds, boolean ignoreRedefine) throws ConfigurationException {
    try {//from   w  w w  . jav  a 2  s.com
        InputStream in = getInputStream();
        if (in == null)
            return null;
        XMLEventReader er = XmlUtils.INPUT_FACTORY.createXMLEventReader(in, XmlUtils.STREAM_FACTORY_ENCODING);
        while (er.hasNext()) {
            XMLEvent e = er.nextEvent();
            switch (e.getEventType()) {
            case XMLStreamConstants.START_ELEMENT:
                StartElement el = e.asStartElement();
                if (el.getName().equals(SchemaUtils.IMPORT) || el.getName().equals(SchemaUtils.INCLUDE)
                        || (el.getName().equals(SchemaUtils.REDEFINE) && !ignoreRedefine)) {
                    Attribute schemaLocationAttribute = el.getAttributeByName(SchemaUtils.SCHEMALOCATION);
                    Attribute namespaceAttribute = el.getAttributeByName(SchemaUtils.NAMESPACE);
                    String namespace = this.namespace;
                    boolean addNamespaceToSchema = this.addNamespaceToSchema;
                    if (el.getName().equals(SchemaUtils.IMPORT)) {
                        if (namespaceAttribute == null && StringUtils.isEmpty(xsdDefaultNamespace)
                                && StringUtils.isNotEmpty(xsdTargetNamespace)) {
                            //TODO: concerning import without namespace when in head xsd default namespace doesn't exist and targetNamespace does)
                            namespace = null;
                        } else {
                            if (namespaceAttribute != null) {
                                namespace = namespaceAttribute.getValue();
                            } else {
                                namespace = targetNamespace;
                            }
                        }
                    }
                    if (schemaLocationAttribute != null) {
                        boolean skip = false;
                        if (el.getName().equals(SchemaUtils.IMPORT) && namespaceAttribute == null) {
                            if (StringUtils.isNotEmpty(xsdDefaultNamespace)
                                    && StringUtils.isNotEmpty(xsdTargetNamespace)) {
                                //ignore import without namespace when in head xsd default namespace and targetNamespace exists)
                                skip = true;
                            }
                        }
                        if (!skip) {
                            String sl = schemaLocationAttribute.getValue();
                            ArrayList aslti = null;
                            if (StringUtils.isNotEmpty(getImportedSchemaLocationsToIgnore())) {
                                aslti = new ArrayList(
                                        Arrays.asList(getImportedSchemaLocationsToIgnore().split(",")));
                            }
                            if (StringUtils.isNotEmpty(sl) && aslti != null) {
                                if (isUseBaseImportedSchemaLocationsToIgnore()) {
                                    sl = FilenameUtils.getName(sl);
                                }
                                if (aslti.contains(sl)) {
                                    skip = true;
                                }
                            }
                        }
                        if (!skip) {
                            ArrayList ans = null;
                            if (StringUtils.isNotEmpty(getImportedNamespacesToIgnore())) {
                                ans = new ArrayList(Arrays.asList(getImportedNamespacesToIgnore().split(",")));
                            }
                            if (StringUtils.isNotEmpty(namespace) && ans != null) {
                                if (ans.contains(namespace)) {
                                    skip = true;
                                }
                            }
                        }
                        if (!skip) {
                            XSD x = new XSD();
                            x.setClassLoader(classLoader);
                            x.setNamespace(namespace);
                            x.setResource(getResourceBase() + schemaLocationAttribute.getValue());
                            x.setAddNamespaceToSchema(addNamespaceToSchema);
                            x.setImportedSchemaLocationsToIgnore(getImportedSchemaLocationsToIgnore());
                            x.setUseBaseImportedSchemaLocationsToIgnore(
                                    isUseBaseImportedSchemaLocationsToIgnore());
                            x.setImportedNamespacesToIgnore(getImportedNamespacesToIgnore());
                            x.setParentLocation(getResourceBase());
                            x.setRootXsd(false);
                            x.init();
                            if (xsds.add(x)) {
                                x.getXsdsRecursive(xsds, ignoreRedefine);
                            }
                        }
                    }
                }
                break;
            }
        }
    } catch (IOException e) {
        String message = "IOException reading XSD";
        LOG.error(message, e);
        throw new ConfigurationException(message, e);
    } catch (XMLStreamException e) {
        String message = "XMLStreamException reading XSD";
        LOG.error(message, e);
        throw new ConfigurationException(message, e);
    }
    return xsds;
}

From source file:org.apache.axiom.om.impl.builder.StAXOMBuilder.java

/**
 * Method next./*from  w  ww  .j a  v a 2  s  .  com*/
 *
 * @return Returns int.
 * @throws OMException
 */
public int next() throws OMException {
    try {
        // We need a loop here because we may decide to skip an event
        while (true) {
            if (done) {
                throw new OMException();
            }
            int token = parserNext();
            if (!cache) {
                return token;
            }

            // The current token should be the same as the 
            // one just obtained.  This bit of code is used to 
            // detect invalid parser state.
            if (doTrace) {
                int currentParserToken = parser.getEventType();
                if (currentParserToken != token) {

                    log.debug("WARNING: The current state of the parser is not equal to the "
                            + "state just received from the parser. The current state in the paser is "
                            + XMLEventUtils.getEventTypeString(currentParserToken)
                            + " the state just received is " + XMLEventUtils.getEventTypeString(token));

                    /*
                      throw new OMException("The current token " + token + 
                                 " does not match the current event " +
                                 "reported by the parser token.  The parser did not update its state correctly.  " +
                                 "The parser is " + parser);
                     */
                }
            }

            // Now log the current state of the parser
            if (doTrace) {
                logParserState();
            }

            switch (token) {
            case XMLStreamConstants.START_ELEMENT:
                elementLevel++;
                lastNode = createNextOMElement();
                break;
            case XMLStreamConstants.CHARACTERS:
                lastNode = createOMText(XMLStreamConstants.CHARACTERS);
                break;
            case XMLStreamConstants.CDATA:
                lastNode = createOMText(XMLStreamConstants.CDATA);
                break;
            case XMLStreamConstants.END_ELEMENT:
                endElement();
                elementLevel--;
                break;
            case XMLStreamConstants.END_DOCUMENT:
                done = true;
                ((OMContainerEx) this.document).setComplete(true);
                break;
            case XMLStreamConstants.SPACE:
                try {
                    lastNode = createOMText(XMLStreamConstants.SPACE);
                    if (lastNode == null) {
                        continue;
                    }
                } catch (OMHierarchyException ex) {
                    // The OM implementation doesn't allow text nodes at the current
                    // position in the tree. Since it is only whitespace, we can safely
                    // skip this event.
                    continue;
                }
                break;
            case XMLStreamConstants.COMMENT:
                lastNode = createComment();
                break;
            case XMLStreamConstants.DTD:
                createDTD();
                break;
            case XMLStreamConstants.PROCESSING_INSTRUCTION:
                lastNode = createPI();
                break;
            case XMLStreamConstants.ENTITY_REFERENCE:
                lastNode = createOMText(XMLStreamConstants.ENTITY_REFERENCE);
                break;
            default:
                throw new OMException();
            }
            return token;
        }
    } catch (XMLStreamException e) {
        throw new OMException(e);
    }
}

From source file:org.apache.axiom.om.impl.builder.StAXOMBuilder.java

/**
 * Dump the current event of the parser.
 *//*from   w ww  . j a  va 2  s  .  c o m*/
protected void logParserState() {
    if (doTrace) {
        int currentEvent = parser.getEventType();

        switch (currentEvent) {
        case XMLStreamConstants.START_ELEMENT:
            log.trace("START_ELEMENT: ");
            log.trace("  QName: " + parser.getName());
            break;
        case XMLStreamConstants.START_DOCUMENT:
            log.trace("START_DOCUMENT: ");
            break;
        case XMLStreamConstants.CHARACTERS:
            log.trace("CHARACTERS: ");
            // This can bust up a datahandler
            //log.trace(   "[" + parser.getText() + "]");
            break;
        case XMLStreamConstants.CDATA:
            log.trace("CDATA: ");
            // This can but
            //log.trace(   "[" + parser.getText() + "]");
            break;
        case XMLStreamConstants.END_ELEMENT:
            log.trace("END_ELEMENT: ");
            log.trace("  QName: " + parser.getName());
            break;
        case XMLStreamConstants.END_DOCUMENT:
            log.trace("END_DOCUMENT: ");
            break;
        case XMLStreamConstants.SPACE:
            log.trace("SPACE: ");
            //log.trace(   "[" + parser.getText() + "]");
            break;
        case XMLStreamConstants.COMMENT:
            log.trace("COMMENT: ");
            //log.trace(   "[" + parser.getText() + "]");
            break;
        case XMLStreamConstants.DTD:
            log.trace("DTD: ");
            log.trace("[" + parser.getText() + "]");
            break;
        case XMLStreamConstants.PROCESSING_INSTRUCTION:
            log.trace("PROCESSING_INSTRUCTION: ");
            log.trace("   [" + parser.getPITarget() + "][" + parser.getPIData() + "]");
            break;
        case XMLStreamConstants.ENTITY_REFERENCE:
            log.trace("ENTITY_REFERENCE: ");
            log.trace("    " + parser.getLocalName() + "[" + parser.getText() + "]");
            break;
        default:
            log.trace("UNKNOWN_STATE: " + currentEvent);

        }
    }
}

From source file:org.apache.axiom.om.impl.builder.StAXOMBuilder.java

/**
 * This method looks ahead to the next start element.
 * @return true if successful/* w w w  .  j ava 2 s  . com*/
 */
public boolean lookahead() {
    try {
        while (true) {
            if (lookAheadToken < 0) {
                lookAheadToken = parserNext();
            }
            if (lookAheadToken == XMLStreamConstants.START_ELEMENT) {
                return true;
            } else if (lookAheadToken == XMLStreamConstants.END_ELEMENT
                    || lookAheadToken == XMLStreamConstants.START_DOCUMENT
                    || lookAheadToken == XMLStreamConstants.END_DOCUMENT) {
                next();
                return false; // leaving scope...start element not found
            } else {
                next(); // continue looking past whitespace etc.
            }
        }
    } catch (XMLStreamException e) {
        throw new OMException(e);
    }
}

From source file:org.apache.axiom.om.impl.llom.OMSourcedElementImpl.java

/**
 * Set parser for OM, if not previously set. Since the builder is what actually constructs the
 * tree on demand, this first creates a builder
 *///from w  ww .  j  a va2  s.  c  o  m
private void forceExpand() {
    if (!isExpanded) {

        if (isDebugEnabled) {
            log.debug("forceExpand: expanding element " + getPrintableName());
            if (forceExpandLog.isDebugEnabled()) {
                // When using an OMSourcedElement, it can be particularly difficult to
                // determine why an expand occurs... a stack trace should help debugging this
                Exception e = new Exception("Debug Stack Trace");
                forceExpandLog.debug("forceExpand stack", e);
            }
        }

        // Get the XMLStreamReader
        readerFromDS = getDirectReader();

        // Advance past the START_DOCUMENT to the start tag.
        // Remember the character encoding.
        String characterEncoding = readerFromDS.getCharacterEncodingScheme();
        if (characterEncoding != null) {
            characterEncoding = readerFromDS.getEncoding();
        }
        try {
            if (readerFromDS.getEventType() != XMLStreamConstants.START_ELEMENT) {
                while (readerFromDS.next() != XMLStreamConstants.START_ELEMENT)
                    ;
            }
        } catch (XMLStreamException e) {
            log.error("forceExpand: error parsing data soruce document for element " + getLocalName(), e);
            throw new RuntimeException("Error parsing data source document:" + e.getMessage());
        }

        // Make sure element local name and namespace matches what was expected
        if (!readerFromDS.getLocalName().equals(getLocalName())) {
            log.error("forceExpand: expected element name " + getLocalName() + ", found "
                    + readerFromDS.getLocalName());
            throw new RuntimeException("Element name from data source is " + readerFromDS.getLocalName()
                    + ", not the expected " + getLocalName());
        }
        String readerURI = readerFromDS.getNamespaceURI();
        readerURI = (readerURI == null) ? "" : readerURI;
        String uri = (getNamespace() == null) ? ""
                : ((getNamespace().getNamespaceURI() == null) ? "" : getNamespace().getNamespaceURI());
        if (!readerURI.equals(uri)) {
            log.error("forceExpand: expected element namespace " + getLocalName() + ", found " + uri);
            throw new RuntimeException(
                    "Element namespace from data source is " + readerURI + ", not the expected " + uri);
        }

        // Get the current prefix and the reader's prefix
        String readerPrefix = readerFromDS.getPrefix();
        readerPrefix = (readerPrefix == null) ? "" : readerPrefix;
        String prefix = null;

        OMNamespace ns = getNamespace();
        if (ns == null || ns instanceof DeferredNamespace) {
            // prefix is not available until after expansion
        } else {
            prefix = ns.getPrefix();
        }

        // Set the builder for this element
        isExpanded = true;
        super.setBuilder(new StAXOMBuilder(getOMFactory(), readerFromDS, this, characterEncoding));
        setComplete(false);

        // Update the prefix if necessary.  This must be done after
        // isParserSet to avoid a recursive call
        if (!readerPrefix.equals(prefix) || getNamespace() == null || ns instanceof DeferredNamespace) {
            if (log.isDebugEnabled()) {
                log.debug("forceExpand: changing prefix from " + prefix + " to " + readerPrefix);
            }
            setNamespace(new OMNamespaceImpl(readerURI, readerPrefix));
        }

    }
}

From source file:org.apache.axiom.om.impl.llom.OMStAXWrapper.java

/**
 * Returns the next tag.//from w  w  w .java 2s  .  co  m
 *
 * @return Returns int.
 * @throws org.apache.axiom.om.impl.exception.OMStreamingException
 *
 * @throws XMLStreamException
 */
public int nextTag() throws XMLStreamException {
    int eventType = next();
    while ((eventType == XMLStreamConstants.CHARACTERS && isWhiteSpace()) // skip whitespace
            || (eventType == XMLStreamConstants.CDATA && isWhiteSpace()) // skip whitespace
            || eventType == XMLStreamConstants.SPACE || eventType == XMLStreamConstants.PROCESSING_INSTRUCTION
            || eventType == XMLStreamConstants.COMMENT) {
        eventType = next();
    }
    if (eventType != XMLStreamConstants.START_ELEMENT && eventType != XMLStreamConstants.END_ELEMENT) {
        throw new XMLStreamException("expected start or end tag", getLocation());
    }
    return eventType;
}

From source file:org.apache.axiom.om.impl.llom.OMStAXWrapper.java

/**
 * @return Returns String./*from   w  w w . j a  v a 2s .  c o  m*/
 * @throws XMLStreamException
 * @see javax.xml.stream.XMLStreamReader#getElementText()
 */
public String getElementText() throws XMLStreamException {
    if (parser != null) {
        try {
            return parser.getElementText();
        } catch (XMLStreamException e) {
            throw new OMStreamingException(e);
        }
    } else {
        ///////////////////////////////////////////////////////
        //// Code block directly from the API documentation ///
        if (getEventType() != XMLStreamConstants.START_ELEMENT) {
            throw new XMLStreamException("parser must be on START_ELEMENT to read next text", getLocation());
        }
        int eventType = next();
        StringBuffer content = new StringBuffer();
        while (eventType != XMLStreamConstants.END_ELEMENT) {
            if (eventType == XMLStreamConstants.CHARACTERS || eventType == XMLStreamConstants.CDATA
                    || eventType == XMLStreamConstants.SPACE
                    || eventType == XMLStreamConstants.ENTITY_REFERENCE) {
                content.append(getText());
            } else if (eventType == XMLStreamConstants.PROCESSING_INSTRUCTION
                    || eventType == XMLStreamConstants.COMMENT) {
                // skipping
            } else if (eventType == XMLStreamConstants.END_DOCUMENT) {
                throw new XMLStreamException("unexpected end of document when reading element text content");
            } else if (eventType == XMLStreamConstants.START_ELEMENT) {
                throw new XMLStreamException("element text content may not contain START_ELEMENT");
            } else {
                throw new XMLStreamException("Unexpected event type " + eventType, getLocation());
            }
            eventType = next();
        }
        return content.toString();
        ///////////////////////////////////////////////////////////////
    }

}

From source file:org.apache.axiom.om.impl.SwitchingWrapper.java

/**
 * @return Returns String./*from  ww w  . j  a  v  a  2s  . c om*/
 * @throws XMLStreamException
 * @see javax.xml.stream.XMLStreamReader#getElementText()
 */
public String getElementText() throws XMLStreamException {
    if (parser != null) {
        try {
            String elementText = parser.getElementText();
            currentEvent = END_ELEMENT;
            return elementText;
        } catch (XMLStreamException e) {
            throw new OMStreamingException(e);
        }
    } else {
        ///////////////////////////////////////////////////////
        //// Code block directly from the API documentation ///
        if (getEventType() != XMLStreamConstants.START_ELEMENT) {
            throw new XMLStreamException("parser must be on START_ELEMENT to read next text", getLocation());
        }
        int eventType = next();
        StringBuffer content = new StringBuffer();
        while (eventType != XMLStreamConstants.END_ELEMENT) {
            if (eventType == XMLStreamConstants.CHARACTERS || eventType == XMLStreamConstants.CDATA
                    || eventType == XMLStreamConstants.SPACE
                    || eventType == XMLStreamConstants.ENTITY_REFERENCE) {
                content.append(getText());
            } else if (eventType == XMLStreamConstants.PROCESSING_INSTRUCTION
                    || eventType == XMLStreamConstants.COMMENT) {
                // skipping
            } else if (eventType == XMLStreamConstants.END_DOCUMENT) {
                throw new XMLStreamException("unexpected end of document when reading element text content");
            } else if (eventType == XMLStreamConstants.START_ELEMENT) {
                throw new XMLStreamException("element text content may not contain START_ELEMENT");
            } else {
                throw new XMLStreamException("Unexpected event type " + eventType, getLocation());
            }
            eventType = next();
        }
        return content.toString();
        ///////////////////////////////////////////////////////////////
    }

}

From source file:org.apache.axiom.om.util.OMXMLStreamReaderValidator.java

public int next() throws XMLStreamException {
    int event = delegate.next();
    logParserState();//from  w  w  w .  j a  v  a  2 s .  c  om

    // Make sure that the start element and end element events match.
    // Mismatched events are a key indication that the delegate stream reader is 
    // broken or corrupted.
    switch (event) {
    case XMLStreamConstants.START_ELEMENT:
        stack.push(delegate.getName());
        break;
    case XMLStreamConstants.END_ELEMENT:
        QName delegateQName = delegate.getName();
        if (stack.isEmpty()) {
            reportMismatchedEndElement(null, delegateQName);
        } else {
            QName expectedQName = (QName) stack.pop();

            if (!expectedQName.equals(delegateQName)) {
                reportMismatchedEndElement(expectedQName, delegateQName);
            }
        }
        break;

    default:

    }

    return event;
}