Example usage for javax.xml.stream XMLEventReader nextEvent

List of usage examples for javax.xml.stream XMLEventReader nextEvent

Introduction

In this page you can find the example usage for javax.xml.stream XMLEventReader nextEvent.

Prototype

public XMLEvent nextEvent() throws XMLStreamException;

Source Link

Document

Gets the next XMLEvent.

Usage

From source file:ca.uhn.fhir.parser.XmlParser.java

private <T> T doXmlLoop(XMLEventReader streamReader, ParserState<T> parserState) {
    ourLog.trace("Entering XML parsing loop with state: {}", parserState);

    try {/* w w  w .j av a  2s  . c om*/
        List<String> heldComments = new ArrayList<String>(1);

        while (streamReader.hasNext()) {
            XMLEvent nextEvent = streamReader.nextEvent();
            try {

                switch (nextEvent.getEventType()) {
                case XMLStreamConstants.START_ELEMENT: {
                    StartElement elem = nextEvent.asStartElement();

                    String namespaceURI = elem.getName().getNamespaceURI();

                    if ("extension".equals(elem.getName().getLocalPart())) {
                        Attribute urlAttr = elem.getAttributeByName(new QName("url"));
                        String url;
                        if (urlAttr == null || isBlank(urlAttr.getValue())) {
                            getErrorHandler().missingRequiredElement(new ParseLocation("extension"), "url");
                            url = null;
                        } else {
                            url = urlAttr.getValue();
                        }
                        parserState.enteringNewElementExtension(elem, url, false);
                    } else if ("modifierExtension".equals(elem.getName().getLocalPart())) {
                        Attribute urlAttr = elem.getAttributeByName(new QName("url"));
                        String url;
                        if (urlAttr == null || isBlank(urlAttr.getValue())) {
                            getErrorHandler().missingRequiredElement(new ParseLocation("modifierExtension"),
                                    "url");
                            url = null;
                        } else {
                            url = urlAttr.getValue();
                        }
                        parserState.enteringNewElementExtension(elem, url, true);
                    } else {
                        String elementName = elem.getName().getLocalPart();
                        parserState.enteringNewElement(namespaceURI, elementName);
                    }

                    if (!heldComments.isEmpty()) {
                        for (String next : heldComments) {
                            parserState.commentPre(next);
                        }
                        heldComments.clear();
                    }

                    @SuppressWarnings("unchecked")
                    Iterator<Attribute> attributes = elem.getAttributes();
                    for (Iterator<Attribute> iter = attributes; iter.hasNext();) {
                        Attribute next = iter.next();
                        parserState.attributeValue(next.getName().getLocalPart(), next.getValue());
                    }

                    break;
                }
                case XMLStreamConstants.END_DOCUMENT:
                case XMLStreamConstants.END_ELEMENT: {
                    if (!heldComments.isEmpty()) {
                        for (String next : heldComments) {
                            parserState.commentPost(next);
                        }
                        heldComments.clear();
                    }
                    parserState.endingElement();
                    //                  if (parserState.isComplete()) {
                    //                     return parserState.getObject();
                    //                  }
                    break;
                }
                case XMLStreamConstants.CHARACTERS: {
                    parserState.string(nextEvent.asCharacters().getData());
                    break;
                }
                case XMLStreamConstants.COMMENT: {
                    Comment comment = (Comment) nextEvent;
                    String commentText = comment.getText();
                    heldComments.add(commentText);
                    break;
                }
                }

                parserState.xmlEvent(nextEvent);

            } catch (DataFormatException e) {
                throw new DataFormatException("DataFormatException at [" + nextEvent.getLocation().toString()
                        + "]: " + e.getMessage(), e);
            }
        }
        return parserState.getObject();
    } catch (XMLStreamException e) {
        throw new DataFormatException(e);
    }
}

From source file:edu.unc.lib.dl.util.TripleStoreQueryServiceMulgaraImpl.java

/**
 * @param query//from  ww w .j  a v  a2  s.c o m
 *            an ITQL command
 * @return the message returned by Mulgara
 * @throws RemoteException
 *             for communication failure
 */
public String storeCommand(String query) {
    String result = null;
    String response = this.sendTQL(query);
    if (response != null) {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        try (StringReader sr = new StringReader(response)) {
            XMLEventReader r = factory.createXMLEventReader(sr);
            boolean inMessage = false;
            StringBuffer message = new StringBuffer();
            while (r.hasNext()) {
                XMLEvent e = r.nextEvent();
                if (e.isStartElement()) {
                    StartElement s = e.asStartElement();
                    if ("message".equals(s.getName().getLocalPart())) {
                        inMessage = true;
                    }
                } else if (e.isEndElement()) {
                    EndElement end = e.asEndElement();
                    if ("message".equals(end.getName().getLocalPart())) {
                        inMessage = false;
                    }
                } else if (inMessage && e.isCharacters()) {
                    message.append(e.asCharacters().getData());
                }
            }
            r.close();
            result = message.toString();
        } catch (XMLStreamException e) {
            e.printStackTrace();
        }
    }
    return result;
}

From source file:edu.jhu.hlt.concrete.ingesters.bolt.BoltForumPostIngester.java

@Override
public Communication fromCharacterBasedFile(final Path path) throws IngestException {
    if (!Files.exists(path))
        throw new IngestException("No file at: " + path.toString());

    AnalyticUUIDGeneratorFactory f = new AnalyticUUIDGeneratorFactory();
    AnalyticUUIDGenerator gen = f.create();
    Communication c = new Communication();
    c.setUuid(gen.next());/* w ww  . j  a v a  2  s. com*/
    c.setType(this.getKind());
    c.setMetadata(TooledMetadataConverter.convert(this));

    try {
        ExistingNonDirectoryFile ef = new ExistingNonDirectoryFile(path);
        c.setId(ef.getName().split("\\.")[0]);
    } catch (NoSuchFileException | NotFileException e) {
        // might throw if path is a directory.
        throw new IngestException(path.toString() + " is not a file, or is a directory.");
    }

    String content;
    try (InputStream is = Files.newInputStream(path);
            BufferedInputStream bin = new BufferedInputStream(is, 1024 * 8 * 8);) {
        content = IOUtils.toString(bin, StandardCharsets.UTF_8);
        c.setText(content);
    } catch (IOException e) {
        throw new IngestException(e);
    }

    try (InputStream is = Files.newInputStream(path);
            BufferedInputStream bin = new BufferedInputStream(is, 1024 * 8 * 8);
            BufferedReader reader = new BufferedReader(new InputStreamReader(bin, StandardCharsets.UTF_8));) {
        XMLEventReader rdr = null;
        try {
            rdr = inF.createXMLEventReader(reader);

            // Below method moves the reader
            // to the first post element.
            Section headline = handleHeadline(rdr, content);
            headline.setUuid(gen.next());
            c.addToSectionList(headline);
            int start = headline.getTextSpan().getStart();
            int ending = headline.getTextSpan().getEnding();
            if (ending < start)
                ending = start; // @tongfei: handle empty headlines
            String htxt = c.getText().substring(start, ending);
            LOGGER.debug("headline text: {}", htxt);

            // Section indices.
            int sectNumber = 1;
            int subSect = 0;

            // Move iterator to post start element.
            this.iterateToPosts(rdr);

            // Offset pointer.
            int currOff = -1;

            SectionFactory sf = new SectionFactory(gen);

            // First post element.
            while (rdr.hasNext()) {
                XMLEvent nextEvent = rdr.nextEvent();
                currOff = nextEvent.getLocation().getCharacterOffset();
                if (currOff > 0) {
                    int currOffPlus = currOff + 20;
                    int currOffLess = currOff - 20;
                    LOGGER.debug("Offset: {}", currOff);
                    if (currOffPlus < content.length())
                        LOGGER.debug("Surrounding text: {}", content.substring(currOffLess, currOffPlus));
                }

                // First: see if document is going to end.
                // If yes: exit.
                if (nextEvent.isEndDocument())
                    break;

                // XMLEvent peeker = rdr.peek();

                // Check if start element.
                if (nextEvent.isStartElement()) {
                    StartElement se = nextEvent.asStartElement();
                    QName name = se.getName();
                    final String localName = name.getLocalPart();
                    LOGGER.debug("Hit start element: {}", localName);

                    //region
                    // Add sections for authors and datetimes for each bolt post
                    // by Tongfei Chen
                    Attribute attrAuthor = se.getAttributeByName(QName.valueOf("author"));
                    Attribute attrDateTime = se.getAttributeByName(QName.valueOf("datetime"));

                    if (attrAuthor != null && attrDateTime != null) {

                        int loc = attrAuthor.getLocation().getCharacterOffset();

                        int sectAuthorBeginningOffset = loc + "<post author=\"".length();

                        Section sectAuthor = sf.fromTextSpan(new TextSpan(sectAuthorBeginningOffset,
                                sectAuthorBeginningOffset + attrAuthor.getValue().length()), "author");
                        c.addToSectionList(sectAuthor);

                        int sectDateTimeBeginningOffset = sectAuthorBeginningOffset
                                + attrAuthor.getValue().length() + " datetime=".length();

                        Section sectDateTime = sf.fromTextSpan(
                                new TextSpan(sectDateTimeBeginningOffset,
                                        sectDateTimeBeginningOffset + attrDateTime.getValue().length()),
                                "datetime");
                        c.addToSectionList(sectDateTime);
                    }
                    //endregion

                    // Move past quotes, images, and links.
                    if (localName.equals(QUOTE_LOCAL_NAME)) {
                        this.handleQuote(rdr);
                    } else if (localName.equals(IMG_LOCAL_NAME)) {
                        this.handleImg(rdr);
                    } else if (localName.equals(LINK_LOCAL_NAME)) {
                        this.handleLink(rdr);
                    }

                    // not a start element
                } else if (nextEvent.isCharacters()) {
                    Characters chars = nextEvent.asCharacters();
                    int coff = chars.getLocation().getCharacterOffset();
                    if (!chars.isWhiteSpace()) {
                        // content to be captured
                        String fpContent = chars.getData();
                        LOGGER.debug("Character offset: {}", coff);
                        LOGGER.debug("Character based data: {}", fpContent);
                        // LOGGER.debug("Character data via offset diff: {}", content.substring(coff - fpContent.length(), coff));

                        SimpleImmutableEntry<Integer, Integer> pads = trimSpacing(fpContent);
                        final int tsb = currOff + pads.getKey();
                        final int tse = currOff + fpContent.length() - pads.getValue();
                        final String subs = content.substring(tsb, tse);
                        if (subs.replaceAll("\\p{Zs}", "").replaceAll("\\n", "").isEmpty()) {
                            LOGGER.info("Found empty section: skipping.");
                            continue;
                        }

                        LOGGER.debug("Section text: {}", subs);
                        TextSpan ts = new TextSpan(tsb, tse);

                        Section s = sf.fromTextSpan(ts, "post");
                        List<Integer> intList = new ArrayList<>();
                        intList.add(sectNumber);
                        intList.add(subSect);
                        s.setNumberList(intList);
                        c.addToSectionList(s);

                        subSect++;
                    }
                } else if (nextEvent.isEndElement()) {
                    EndElement ee = nextEvent.asEndElement();
                    currOff = ee.getLocation().getCharacterOffset();
                    QName name = ee.getName();
                    String localName = name.getLocalPart();
                    LOGGER.debug("Hit end element: {}", localName);
                    if (localName.equalsIgnoreCase(POST_LOCAL_NAME)) {
                        sectNumber++;
                        subSect = 0;
                    }
                }
            }
            return c;
        } catch (XMLStreamException | ConcreteException | StringIndexOutOfBoundsException x) {
            throw new IngestException(x);
        } finally {
            if (rdr != null)
                try {
                    rdr.close();
                } catch (XMLStreamException e) {
                    // not likely.
                    LOGGER.info("Error closing XMLReader.", e);
                }
        }
    } catch (IOException e) {
        throw new IngestException(e);
    }
}

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

public InputStream addAtomInlinecount(final InputStream feed, final int count, final Accept accept)
        throws Exception {
    final XMLEventReader reader = getEventReader(feed);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();
    final XMLEventWriter writer = xof.createXMLEventWriter(bos);

    try {/*from w  ww . j  ava 2 s.c o  m*/

        final XmlElement feedElement = getAtomElement(reader, writer, "feed");

        writer.add(feedElement.getStart());
        addAtomElement(IOUtils.toInputStream(String.format("<m:count>%d</m:count>", count)), writer);
        writer.add(feedElement.getContentReader());
        writer.add(feedElement.getEnd());

        while (reader.hasNext()) {
            writer.add(reader.nextEvent());
        }

    } finally {
        writer.flush();
        writer.close();
        reader.close();
        IOUtils.closeQuietly(feed);
    }

    return new ByteArrayInputStream(bos.toByteArray());
}

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

@Override
public InputStream selectEntity(final InputStream entity, final String[] propertyNames) throws Exception {
    final XMLEventReader reader = getEventReader(entity);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();
    final XMLEventWriter writer = xof.createXMLEventWriter(bos);

    final List<String> found = new ArrayList<String>(Arrays.asList(propertyNames));

    boolean inProperties = false;
    boolean writeCurrent = true;
    Boolean writeNext = null;/*  w  w  w .j  a va 2s . c  om*/
    String currentName = null;

    final List<String> fieldToBeSaved = new ArrayList<String>(Arrays.asList(propertyNames));

    while (reader.hasNext()) {
        final XMLEvent event = reader.nextEvent();
        if (event.getEventType() == XMLStreamConstants.START_ELEMENT
                && LINK.equals(event.asStartElement().getName().getLocalPart())
                && !fieldToBeSaved
                        .contains(event.asStartElement().getAttributeByName(new QName("title")).getValue())
                && !"edit".equals(event.asStartElement().getAttributeByName(new QName("rel")).getValue())) {
            writeCurrent = false;
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                && LINK.equals(event.asEndElement().getName().getLocalPart())) {
            writeNext = true;
        } else if (event.getEventType() == XMLStreamConstants.START_ELEMENT
                && (PROPERTIES).equals(event.asStartElement().getName().getLocalPart())) {
            writeCurrent = true;
            writeNext = false;
            inProperties = true;
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                && (PROPERTIES).equals(event.asEndElement().getName().getLocalPart())) {
            writeCurrent = true;
        } else if (inProperties) {
            if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
                final String elementName = event.asStartElement().getName().getLocalPart();

                for (String propertyName : propertyNames) {
                    if ((ATOM_PROPERTY_PREFIX + propertyName.trim()).equals(elementName)) {
                        writeCurrent = true;
                        found.remove(propertyName);
                        currentName = propertyName;
                    }
                }

            } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                    && StringUtils.isNotBlank(currentName) && (ATOM_PROPERTY_PREFIX + currentName.trim())
                            .equals(event.asEndElement().getName().getLocalPart())) {
                writeNext = false;
                currentName = null;
            }

        }

        if (writeCurrent) {
            writer.add(event);
        }

        if (writeNext != null) {
            writeCurrent = writeNext;
            writeNext = null;
        }
    }

    writer.flush();
    writer.close();
    reader.close();
    IOUtils.closeQuietly(entity);

    // Do not raise any exception in order to support FC properties as well
    // if (!found.isEmpty()) {
    //     throw new Exception(String.format("Could not find a properties '%s'", found));
    // }

    return new ByteArrayInputStream(bos.toByteArray());
}

From source file:org.javelin.sws.ext.bind.internal.model.ComplexTypePattern.java

@Override
public T consumeValue(XMLEventReader eventReader, UnmarshallingContext context) throws XMLStreamException {
    // first create an object to be filled (using PropertyAccessors - direct or bean) according to the content model
    T object = BeanUtils.instantiate(this.getJavaType());

    // the order is dictated by incoming events, not by the mode
    // TODO: create a property to enable strict unmarshalling - dictated by content model
    // only this (ContentModel) pattern iterates over XML Events
    XMLEvent event = null;//from   ww  w . ja  v  a  2 s.c o m
    PropertyMetadataValue<T, ?> pmv = null;

    // this loop will only handle first level of start elements and only single end element
    // deeper levels will be handled by nested patterns
    while (true) {
        boolean end = false;
        event = eventReader.peek();
        pmv = null;

        switch (event.getEventType()) {
        case XMLStreamConstants.ATTRIBUTE:
            pmv = this.consumeNestedAttribute(eventReader, context);
            break;
        case XMLStreamConstants.CDATA:
        case XMLStreamConstants.CHARACTERS:
            // TODO: XMLEvent.ENTITY_REFERENCE?
            if (this.simpleContent != null) {
                pmv = this.consumeSimpleContent(eventReader, context);
                break;
            }
        case XMLStreamConstants.COMMENT:
        case XMLStreamConstants.DTD:
        case XMLStreamConstants.SPACE:
        case XMLStreamConstants.ENTITY_DECLARATION:
        case XMLStreamConstants.NOTATION_DECLARATION:
        case XMLStreamConstants.PROCESSING_INSTRUCTION:
            eventReader.nextEvent();
            break;
        case XMLStreamConstants.ENTITY_REFERENCE:
            // TODO: XMLEvent.ENTITY_REFERENCE?
            eventReader.nextEvent();
            break;
        case XMLStreamConstants.START_DOCUMENT:
            // strange
            break;
        case XMLStreamConstants.START_ELEMENT:
            pmv = this.consumeNestedElement(eventReader, context);
            break;
        case XMLStreamConstants.END_ELEMENT:
            // TODO: in mixed content there will be more than one end element it this content model's level
        case XMLStreamConstants.END_DOCUMENT:
            end = true;
            break;
        }

        if (end)
            break;

        if (pmv != null)
            pmv.getMetadata().setValue(object, pmv.getValue());
    }

    return (T) object;
}

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

private InputStream writeFromStartToEndElement(final StartElement element, final XMLEventReader reader,
        final boolean document) throws XMLStreamException {
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();
    final XMLEventWriter writer = xof.createXMLEventWriter(bos);

    final QName name = element.getName();

    if (document) {
        final XMLEventFactory eventFactory = XMLEventFactory.newInstance();
        writer.add(eventFactory.createStartDocument("UTF-8", "1.0"));
        writer.add(element);/*  w w  w  .  j av a  2 s . c  o m*/

        if (element.getAttributeByName(new QName(ATOM_DATASERVICE_NS)) == null) {
            writer.add(eventFactory.createNamespace(ATOM_PROPERTY_PREFIX.substring(0, 1), DATASERVICES_NS));
        }
        if (element.getAttributeByName(new QName(ATOM_METADATA_NS)) == null) {
            writer.add(eventFactory.createNamespace(ATOM_METADATA_PREFIX.substring(0, 1), METADATA_NS));
        }
    } else {
        writer.add(element);
    }

    XMLEvent event = element;

    while (reader.hasNext() && !(event.isEndElement() && name.equals(event.asEndElement().getName()))) {
        event = reader.nextEvent();
        writer.add(event);
    }

    writer.flush();
    writer.close();

    return new ByteArrayInputStream(bos.toByteArray());
}

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 + "]");
        }//from   w  w w.  j  a  v a  2 s  . 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 {/*w w  w .  ja v  a2s  .  c o  m*/
        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.hadoop.util.ConfTest.java

private static List<NodeInfo> parseConf(InputStream in) throws XMLStreamException {
    QName configuration = new QName("configuration");
    QName property = new QName("property");

    List<NodeInfo> nodes = new ArrayList<NodeInfo>();
    Stack<NodeInfo> parsed = new Stack<NodeInfo>();

    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLEventReader reader = factory.createXMLEventReader(in);

    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();
        if (event.isStartElement()) {
            StartElement currentElement = event.asStartElement();
            NodeInfo currentNode = new NodeInfo(currentElement);
            if (parsed.isEmpty()) {
                if (!currentElement.getName().equals(configuration)) {
                    return null;
                }//from   w  w  w .j  a  v a 2 s .c  o  m
            } else {
                NodeInfo parentNode = parsed.peek();
                QName parentName = parentNode.getStartElement().getName();
                if (parentName.equals(configuration)
                        && currentNode.getStartElement().getName().equals(property)) {
                    @SuppressWarnings("unchecked")
                    Iterator<Attribute> it = currentElement.getAttributes();
                    while (it.hasNext()) {
                        currentNode.addAttribute(it.next());
                    }
                } else if (parentName.equals(property)) {
                    parentNode.addElement(currentElement);
                }
            }
            parsed.push(currentNode);
        } else if (event.isEndElement()) {
            NodeInfo node = parsed.pop();
            if (parsed.size() == 1) {
                nodes.add(node);
            }
        } else if (event.isCharacters()) {
            if (2 < parsed.size()) {
                NodeInfo parentNode = parsed.pop();
                StartElement parentElement = parentNode.getStartElement();
                NodeInfo grandparentNode = parsed.peek();
                if (grandparentNode.getElement(parentElement) == null) {
                    grandparentNode.setElement(parentElement, event.asCharacters());
                }
                parsed.push(parentNode);
            }
        }
    }

    return nodes;
}