Example usage for javax.xml.stream.events XMLEvent getLocation

List of usage examples for javax.xml.stream.events XMLEvent getLocation

Introduction

In this page you can find the example usage for javax.xml.stream.events XMLEvent getLocation.

Prototype

javax.xml.stream.Location getLocation();

Source Link

Document

Return the location of this event.

Usage

From source file:Main.java

private static String format(String message, XMLEvent event) {
    Location location = event == null ? null : event.getLocation();
    return location == null ? message : (message + " at line " + location.getLineNumber());
}

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

private int handleLink(final XMLEventReader rdr) throws XMLStreamException {
    // Links have a start element, characters, and end element.
    // Alternatively, they have a start and end element.
    XMLEvent linkContent = rdr.nextEvent();
    if (linkContent.isEndElement())
        return linkContent.getLocation().getCharacterOffset();
    else if (linkContent.isCharacters())
        // Skip end of link.
        return rdr.nextEvent().getLocation().getCharacterOffset();
    else//from w ww .jav  a  2 s.com
        throw new RuntimeException("Characters did not follow link.");
}

From source file:edu.jhu.hlt.concrete.ingesters.webposts.WebPostIngester.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 g = f.create();
    Communication c = new Communication();
    c.setUuid(g.next());/*from www .  ja  v a  2 s.  c om*/
    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 headline end element.
            Section headline = this.handleBeginning(rdr, content, c);
            headline.setUuid(g.next());
            c.addToSectionList(headline);
            TextSpan sts = headline.getTextSpan();
            LOGGER.debug("headline text: {}", c.getText().substring(sts.getStart(), sts.getEnding()));

            int sectNumber = 1;
            int subSect = 0;

            int currOff = -1;
            // Big amounts of characters.
            while (rdr.hasNext()) {
                XMLEvent nextEvent = rdr.nextEvent();
                currOff = nextEvent.getLocation().getCharacterOffset();

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

                // region
                // enables ingestion of quotes inside a usenet webpost.
                // by Tongfei Chen
                if (nextEvent.isStartElement()
                        && nextEvent.asStartElement().getName().equals(QName.valueOf("QUOTE"))) {
                    Attribute attrQuote = nextEvent.asStartElement()
                            .getAttributeByName(QName.valueOf("PREVIOUSPOST"));
                    String quote = StringEscapeUtils.escapeXml(attrQuote.getValue());
                    int location = attrQuote.getLocation().getCharacterOffset()
                            + "<QUOTE PREVIOUSPOST=\"".length();
                    Section quoteSection = new Section(g.next(), "quote")
                            .setTextSpan(new TextSpan(location, location + quote.length()));
                    c.addToSectionList(quoteSection);
                }
                // endregion

                // Check if start element.
                if (nextEvent.isCharacters()) {
                    Characters chars = nextEvent.asCharacters();
                    if (!chars.isWhiteSpace()) {
                        String fpContent = chars.getData();
                        LOGGER.debug("Character offset: {}", currOff);
                        LOGGER.debug("Character based data: {}", fpContent);

                        SimpleImmutableEntry<Integer, Integer> pads = trimSpacing(fpContent);
                        final int tsb = currOff + pads.getKey();

                        final int tse = currOff + fpContent.replace("\"", "&quot;").replace("<", "&lt;")
                                .replace(">", "&gt;").length() - (pads.getValue());
                        // MAINTAIN CORRECT TEXT SPAN
                        // CANNOT USE StringEscapeUtils.escapeXml because it will escape "'", which
                        // is not escaped in the data
                        // @tongfei

                        LOGGER.debug("Section text: {}", content.substring(tsb, tse));
                        TextSpan ts = new TextSpan(tsb, tse);
                        String sk;
                        if (subSect == 0)
                            sk = "poster";
                        else if (subSect == 1)
                            sk = "postdate";
                        else
                            sk = "post";

                        Section s = new Section();
                        s.setKind(sk);
                        s.setTextSpan(ts);
                        s.setUuid(g.next());
                        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)) {
                        LOGGER.debug("Switching to new post.");
                        sectNumber++;
                        subSect = 0;
                    } else if (localName.equalsIgnoreCase(TEXT_LOCAL_NAME)) {
                        // done with document.
                        break;
                    }
                }
            }

            return c;

        } catch (XMLStreamException | ConcreteException | StringIndexOutOfBoundsException
                | ClassCastException 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: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());//from  w  ww . java 2s .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:edu.jhu.hlt.concrete.ingesters.bolt.BoltForumPostIngester.java

private int handleQuote(final XMLEventReader rdr) throws XMLStreamException {
    // For quotes, there will be character contents - skip for now...
    XMLEvent quoteContent = rdr.nextEvent();
    if (!quoteContent.isCharacters())
        throw new RuntimeException("Characters did not follow quote.");
    // Skip end of quote.
    XMLEvent next = rdr.nextEvent();
    // Exit loop only when next end quote is hit.
    boolean hitEndQuoteElement = false;
    while (!next.isEndElement() && !hitEndQuoteElement) {
        // Move to next element.
        next = rdr.nextEvent();/*from   w  w w . j  a va2 s. co  m*/
        // If next element is an end element,
        // see if it's an end quote.
        // If so, exit the loop.
        if (next.isEndElement())
            hitEndQuoteElement = next.asEndElement().getName().getLocalPart().equals("quote");
    }

    return next.getLocation().getCharacterOffset();
}

From source file:sapience.injectors.stax.inject.StringBasedStaxStreamInjector.java

/**
 * The actual injection procedure/*from w  ww  . ja  v a  2  s  .co  m*/
 * @param in the input stream where the XML is coming from (will be closed in the end) 
 * @param out the output stream where we write the annotated XML into (remains open)
 * @param refs a list of references
 * @throws IOException
 */
public void inject(InputStream in, OutputStream out, List<Reference> refs) throws IOException {
    StringBuilder pb;
    String characters = null;
    NamespaceContext context = null;
    int marked;

    current_path = new Stack<String>();
    current_path.push("//");

    try {
        XMLEventReader r = inFac.createXMLEventReader(in);
        XMLEventWriter w = outFac.createXMLEventWriter(out);
        XMLStreamWriter ws = outFac.createXMLStreamWriter(System.out);

        while (r.hasNext()) {

            XMLEvent e = r.nextEvent();
            switch (e.getEventType()) {

            case XMLEvent.START_ELEMENT:
                StartElement se = (StartElement) e;
                context = se.getNamespaceContext();
                if (elementReferences == null) {
                    // process the namespaces in the references
                    this.prepareReferences(refs, context);
                }

                // store location
                col = e.getLocation().getColumnNumber();

                // add to current xpath

                current_path.add(generator.asXPathString((StartElement) e));

                //XPathHelper.addCurrentElementToStack(current_path, se);

                // check if the current xpath is in our list of attribute references
                if (attributeReferences.size() > 0) {
                    for (int i = 0; i < refs.size(); i++) {
                        Stack<String> stack = attributeReferences.get(refs.get(i));
                        if (matcher.matches(current_path, stack, true, context)) {
                            // yes, let's inject the reference (only valid for attributes here)
                            this.handleAttribute(w, refs.get(i));
                            attributeReferences.remove(refs.get(i));
                            refs.remove(i);
                        }
                    }
                }

                w.add(e);
                break;
            case XMLEvent.END_ELEMENT:

                // before removing from stack, we check if the current path with added characters is a match (which means we have to add a new element now)
                if (characters != null)
                    this.current_path.push(characters);

                if (elementReferences.size() > 0) {
                    for (int i = 0; i < refs.size(); i++) {

                        Stack<String> stack = elementReferences.get(refs.get(i));

                        if (matcher.matches(current_path, stack, true, context)) {
                            // yes, let's inject the reference (only valid for attributes here)
                            this.interceptingElement = refs.get(i);
                            elementReferences.remove(refs.get(i));
                            refs.remove(i);
                        }
                    }
                }

                if (characters != null) {
                    // clean up
                    this.current_path.pop();
                    characters = null;
                }

                this.current_path.pop();

                w.add(e);

                // if the intercepting is not null, the preceding element was a match, hence we inject some xml before writing a new element
                if (this.interceptingElement != null) {
                    w.add(eventFac.createSpace("\n"));
                    writeElementIntoStream(w, interceptingElement);
                }
                break;
            case XMLEvent.CHARACTERS:
                characters = generator.asXPathString((Characters) e);
                w.add(e);
                break;

            default:
                w.add(e);
                break;
            }
        }
    } catch (XPathExpressionException e) {
        if (logger.isLoggable(Level.SEVERE)) {
            logger.log(Level.SEVERE, "Not a valid XPath", e);
        }
        throw new IOException(e);

    } catch (XMLStreamException e) {
        if (logger.isLoggable(Level.SEVERE)) {
            logger.log(Level.SEVERE, "Failed to inject. Reason: " + e.getLocalizedMessage(), e);
        }
        throw new IOException(e);
    } finally {
        in.close();
    }

}

From source file:sapience.injectors.stax.inject.ModelBasedStaxStreamInjector.java

/**
 * The actual injection procedure/*from   w  w  w .  j  a v  a 2s .co m*/
 * @param in the input stream where the XML is coming from (will be closed in the end) 
 * @param out the output stream where we write the annotated XML into (remains open)
 * @param refs a list of references
 * @throws IOException
 */
public void inject(InputStream in, OutputStream out, List<Reference> refs) throws IOException {
    StringBuilder pb;
    XPathElement characters = null;
    int marked;
    interceptingElements = new ArrayList<Reference>();

    try {
        XMLEventReader r = getXMLInputFactory().createXMLEventReader(in);
        XMLEventWriter w = getXMLOutputFactory().createXMLEventWriter(out);

        while (r.hasNext()) {

            XMLEvent e = r.nextEvent();
            switch (e.getEventType()) {

            case XMLEvent.START_ELEMENT:
                StartElement se = (StartElement) e;
                if (super.getNamespaceContext() == null) {
                    super.updateNamespaceContext(se.getNamespaceContext());
                }

                if (references == null) {
                    // process the namespaces in the references
                    references = this.prepareReferences(refs);
                }
                // store location
                col = e.getLocation().getColumnNumber();

                // add to current xpath            
                updateCurrentPath(getGenerator().asXPathElement((StartElement) e));

                System.out.println(getCurrentPath());
                // check if the current xpath is in our list of attribute references
                for (XPathPattern p : references.keySet()) {
                    if (references.get(p) == null)
                        continue;

                    if (p.isAttribute()) {
                        if (getMatcher().matches(p, getCurrentPath())) {
                            se = this.handleAttribute(w, references.get(p), se);
                            references.put(p, null); // removing it would lead to concurrentmodificationexcpetion
                        }
                    }
                }

                w.add(se);
                break;
            case XMLEvent.END_ELEMENT:
                updateCurrentPath(characters);

                // before removing from stack, we check if the current path with added characters is a match (which means we have to add a new element now)
                XPathStack currentPath = getCurrentPath();

                for (XPathPattern p : references.keySet()) {

                    if (references.get(p) == null)
                        continue;

                    if (getMatcher().matches(p, currentPath)) {
                        if (p.isSiblingElement()) {
                            // injection happens below
                            this.interceptingElements.add(references.get(p));

                        } else if (p.isChildElement()) {
                            // we can add it directly
                            w.add(getXMLEventFactory().createSpace("\n"));
                            writeElementIntoStream(w, references.get(p));
                        } else {
                            throw new IOException("Invalid Reference: " + p);
                        }
                        references.put(p, null); // removing it would lead to concurrentmodificationexcpetion
                        //references.remove(p);
                        //break; //otherwise ConcurrentModificationException

                    }

                }

                // clean up
                if (characters != null) {
                    getCurrentPath().pop();
                    characters = null;
                }

                getCurrentPath().pop();
                w.add(e); // do not change position

                // if the intercepting is not null, the preceding element was a match, hence we inject some xml before writing a new element
                if (this.interceptingElements.size() > 0) {
                    // write all references into stream
                    for (Reference ref : this.interceptingElements) {
                        w.add(getXMLEventFactory().createSpace("\n"));
                        writeElementIntoStream(w, ref);
                    }

                    // reset list
                    this.interceptingElements.clear();
                }

                break;
            case XMLEvent.CHARACTERS:
                characters = getGenerator().asXPathElement((Characters) e);
                w.add(e);
                break;

            default:
                w.add(e);
                break;
            }
        }
    } catch (XPathExpressionException e) {
        if (logger.isLoggable(Level.SEVERE)) {
            logger.log(Level.SEVERE, "Not a valid XPath", e);
        }
        throw new IOException(e);

    } catch (XMLStreamException e) {
        if (logger.isLoggable(Level.SEVERE)) {
            logger.log(Level.SEVERE, "Failed to inject. Reason: " + e.getLocalizedMessage(), e);
        }
        throw new IOException(e);
    } finally {
        in.close();
    }

}

From source file:com.streamsets.pipeline.lib.xml.StreamingXmlParser.java

@SuppressWarnings("unchecked")
Field parse(XMLEventReader reader, StartElement startE) throws XMLStreamException, ObjectLengthException {
    Map<String, Field> map = this.useFieldAttributesInsteadOfFields ? new LinkedHashMap<>() : toField(startE);
    Map<String, Field> startEMap = map;
    Map<String, Object> contents = new LinkedHashMap<>();
    boolean maybeText = true;
    while (hasNext(reader) && !peek(reader).isEndElement()) {
        XMLEvent next = read(reader);
        if (next.isCharacters()) {
            // If this set of characters is all whitespace, ignore.
            if (next.asCharacters().isWhiteSpace()) {
                continue;
            } else if (peek(reader).isEndElement() && maybeText) {
                contents.put(VALUE_KEY, Field.create(((Characters) next).getData()));
            } else if (peek(reader).isStartElement()) {
                StartElement subStartE = (StartElement) read(reader);
                Field subField = parse(reader, subStartE);
                addContent(contents, getName(subStartE), subField);
                if (hasNext(reader) && peek(reader).isCharacters()) {
                    read(reader);/*w w  w  . ja v a  2 s.  c o  m*/
                }
            } else if (maybeText) {
                throw new XMLStreamException(Utils
                        .format("Unexpected XMLEvent '{}', it should be START_ELEMENT or END_ELEMENT", next),
                        next.getLocation());
            }
        } else if (next.isStartElement()) {
            String name = getName((StartElement) next);
            Field field = parse(reader, (StartElement) next);
            addContent(contents, name, field);
        } else {
            throw new XMLStreamException(
                    Utils.format("Unexpected XMLEvent '{}', it should be START_ELEMENT or CHARACTERS", next),
                    next.getLocation());
        }
        maybeText = false;
    }
    if (hasNext(reader)) {
        EndElement endE = (EndElement) read(reader);
        if (!endE.getName().equals(startE.getName())) {
            throw new XMLStreamException(Utils.format("Unexpected EndElement '{}', it should be '{}'",
                    endE.getName().getLocalPart(), startE.getName().getLocalPart()), endE.getLocation());
        }
        for (Map.Entry<String, Object> entry : contents.entrySet()) {
            if (entry.getValue() instanceof Field) {
                startEMap.put(entry.getKey(), (Field) entry.getValue());
            } else {
                startEMap.put(entry.getKey(), Field.create((List<Field>) entry.getValue()));
            }
        }
    }
    final Field field = Field.create(startEMap);

    if (this.useFieldAttributesInsteadOfFields) {
        Iterator attrs = startE.getAttributes();
        while (attrs.hasNext()) {
            Attribute attr = (Attribute) attrs.next();
            field.setAttribute(getName(XMLATTR_ATTRIBUTE_PREFIX, attr), attr.getValue());
        }
        Iterator nss = startE.getNamespaces();
        while (nss.hasNext()) {
            Namespace ns = (Namespace) nss.next();
            field.setAttribute(getName(null, ns), ns.getNamespaceURI());
        }
    }

    lastParsedFieldXpathPrefix = getXpathPrefix();
    return field;
}

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 {//ww  w . j  av a 2 s.c  o m
        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:org.modeldriven.fuml.xmi.stream.StreamNode.java

public StreamNode(XMLEvent startElement, XmiNode parent, StreamContext context) {
    this.startElementEvent = startElement;
    this.parent = parent;
    this.context = context;
    // The Sun StAX impl "loses" element location info, seemingly 
    // immediately after it's read into an event. We just copy it
    // off here. Tried the default event allocator in both
    // the Sun RI and the associated utilities. 
    this.location = new StreamLocation(startElement.getLocation());
    if (log.isDebugEnabled())
        log.debug("created '" + this.getLocation() + "' node (" + this.getXmiId() + ")");
}