Example usage for javax.xml.stream Location getLineNumber

List of usage examples for javax.xml.stream Location getLineNumber

Introduction

In this page you can find the example usage for javax.xml.stream Location getLineNumber.

Prototype

int getLineNumber();

Source Link

Document

Return the line number where the current event ends, returns -1 if none is available.

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:Main.java

private void log(String event, Object target) {
    System.out.print(event);//from ww w  .  j a v a2s  . com
    System.out.print(" ");
    System.out.print(target);
    System.out.print(" [");
    Location location = xsr.getLocation();
    System.out.print(location.getLineNumber());
    System.out.print(",");
    System.out.print(location.getColumnNumber());
    System.out.println("]");
}

From source file:com.widowcrawler.exo.parse.Parser.java

private String decorate(String message, Location location) {
    message += " | Line " + location.getLineNumber();
    message += " | Column " + location.getColumnNumber();

    return message;
}

From source file:com.stevpet.sonar.plugins.dotnet.mscover.parser.XmlParserSubject.java

private void updateLocation(SMInputCursor elementCursor) {
    Location location;
    try {//from w  w  w . ja va 2  s .c  om
        location = elementCursor.getCursorLocation();

    } catch (XMLStreamException e) {
        throw new MsCoverParserException("Exception thrown on getting location", e);
    }
    line = location.getLineNumber();
    column = location.getColumnNumber();

}

From source file:com.marklogic.contentpump.AggregateXMLReader.java

private void processStartElement() throws XMLStreamException {
    String name = xmlSR.getLocalName();
    String namespace = xmlSR.getNamespaceURI();
    if (LOG.isTraceEnabled()) {
        LOG.trace("Start-tag: " + xmlSR.getName() + " at depth " + currDepth);
    }//from  ww w  . j  ava  2  s  . co m
    if (namespace == null) {
        String prefix = xmlSR.getPrefix();
        if ("".equals(prefix)) {
            prefix = DEFAULT_NS;
        }
        if (nameSpaces.get(prefix) != null) {
            namespace = nameSpaces.get(prefix).peek();
        }
    }

    String prefix = xmlSR.getPrefix();
    int attrCount = xmlSR.getAttributeCount();
    boolean isNewRootStart = false;
    currDepth++;
    Location loc = xmlSR.getLocation();
    if (recordName == null) {
        recordName = name;
        if (recordNamespace == null) {
            recordNamespace = namespace;
        }
        recordDepth = currDepth;
        isNewRootStart = true;
        newDoc = true;
        newUriId = true;
        if (useAutomaticId) {
            setKey(idGen.incrementAndGet(), loc.getLineNumber(), loc.getColumnNumber(), true);
        }
    } else {
        // record element name may not nest
        if (name.equals(recordName) && ((recordNamespace == null && namespace == null)
                || (recordNamespace != null && recordNamespace.equals(namespace)))) {
            recordDepth = currDepth;
            isNewRootStart = true;
            newDoc = true;
            newUriId = true;
            if (useAutomaticId) {
                setKey(idGen.incrementAndGet(), loc.getLineNumber(), loc.getColumnNumber(), true);
            }
        }
    }
    copyNameSpaceDecl();
    if (!newDoc) {
        return;
    }
    StringBuilder sb = new StringBuilder();
    sb.append("<");
    if (prefix != null && !prefix.equals("")) {
        sb.append(prefix + ":" + name);
    } else {
        sb.append(name);
    }
    // add namespaces declared into the new root element
    if (isNewRootStart) {
        Set<String> keys = nameSpaces.keySet();
        for (String k : keys) {
            String v = nameSpaces.get(k).peek();
            if (DEFAULT_NS == k) {
                sb.append(" xmlns=\"" + v + "\"");
            } else {
                sb.append(" xmlns:" + k + "=\"" + v + "\"");
            }
        }
    } else {
        // add new namespace declaration into current element
        int stop = xmlSR.getNamespaceCount();
        if (stop > 0) {
            String nsDeclPrefix, nsDeclUri;
            if (LOG.isTraceEnabled()) {
                LOG.trace("checking namespace declarations");
            }
            for (int i = 0; i < stop; i++) {
                nsDeclPrefix = xmlSR.getNamespacePrefix(i);
                nsDeclUri = xmlSR.getNamespaceURI(i);
                if (LOG.isTraceEnabled()) {
                    LOG.trace(nsDeclPrefix + ":" + nsDeclUri);
                }
                if (DEFAULT_NS == nsDeclPrefix) {
                    sb.append(" xmlns=\"" + nsDeclUri + "\"");
                } else {
                    sb.append(" xmlns:" + nsDeclPrefix + "=\"" + nsDeclUri + "\"");
                }
            }
        }
    }
    for (int i = 0; i < attrCount; i++) {
        String aPrefix = xmlSR.getAttributePrefix(i);
        String aName = xmlSR.getAttributeLocalName(i);
        String aValue = StringEscapeUtils.escapeXml(xmlSR.getAttributeValue(i));
        sb.append(" " + (null == aPrefix ? "" : (aPrefix + ":")) + aName + "=\"" + aValue + "\"");
        if (!useAutomaticId && newDoc && ("@" + aName).equals(idName) && currentId == null) {
            currentId = aValue;
            setKey(aValue, loc.getLineNumber(), loc.getColumnNumber(), true);
        }
    }
    sb.append(">");

    // allow for repeated idName elements: first one wins
    // NOTE: idName is namespace-insensitive
    if (!useAutomaticId && newDoc && name.equals(idName)) {
        int nextToken = xmlSR.next();
        if (nextToken != XMLStreamConstants.CHARACTERS) {
            throw new XMLStreamException(
                    "badly formed xml or " + idName + " is not a simple node: at" + xmlSR.getLocation());
        }
        do {
            String idStr = StringEscapeUtils.escapeXml(xmlSR.getText());
            if (currentId == null) {
                currentId = "";
            }
            currentId += idStr;
            sb.append(idStr);
        } while ((nextToken = xmlSR.next()) == XMLStreamConstants.CHARACTERS);
        if (newUriId) {
            setKey(currentId, loc.getLineNumber(), loc.getColumnNumber(), true);
            newUriId = false;
        } else if (LOG.isDebugEnabled()) {
            LOG.debug("Duplicate URI_ID match found: key = " + key);
        }
        if (LOG.isTraceEnabled()) {
            LOG.trace("URI_ID: " + currentId);
        }
        // advance to the END_ELEMENT
        if (nextToken != XMLStreamConstants.END_ELEMENT) {
            throw new XMLStreamException("badly formed xml: no END_TAG after id text" + xmlSR.getLocation());
        }
        sb.append("</");
        if (prefix != null && !prefix.equals("")) {
            sb.append(prefix + ":" + name);
        } else {
            sb.append(name);
        }
        sb.append(">");
        currDepth--;
    }
    write(sb.toString());
}

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

/**
 * Populate element with data from parser START_ELEMENT event. This is used when the source of
 * data for an element needs to be parsed on demand. The supplied element must already be set to
 * the proper name and namespace.//from   w  w w .j a  v  a 2s. c  o  m
 *
 * @param node element to be populated
 */
private void populateOMElement(OMElement node) {
    // create the namespaces
    processNamespaceData(node);
    // fill in the attributes
    processAttributes(node);
    Location location = parser.getLocation();
    if (location != null) {
        node.setLineNumber(location.getLineNumber());
    }
}

From source file:org.deegree.style.se.parser.GraphicSymbologyParser.java

Pair<Graphic, Continuation<Graphic>> parseGraphic(XMLStreamReader in) throws XMLStreamException {
    in.require(START_ELEMENT, null, "Graphic");

    Graphic base = new Graphic();
    Continuation<Graphic> contn = null;

    while (!(in.isEndElement() && in.getLocalName().equals("Graphic"))) {
        in.nextTag();/*from w ww . ja v a2 s. co m*/

        if (in.getLocalName().equals("Mark")) {
            final Pair<Mark, Continuation<Mark>> pair = parseMark(in);

            if (pair != null) {
                base.mark = pair.first;
                if (pair.second != null) {
                    contn = new Continuation<Graphic>(contn) {
                        @Override
                        public void updateStep(Graphic base, Feature f, XPathEvaluator<Feature> evaluator) {
                            pair.second.evaluate(base.mark, f, evaluator);
                        }
                    };
                }
            }
        } else if (in.getLocalName().equals("ExternalGraphic")) {
            try {
                final Triple<BufferedImage, String, Continuation<List<BufferedImage>>> p = parseExternalGraphic(
                        in);
                if (p.third != null) {
                    contn = new Continuation<Graphic>(contn) {
                        @Override
                        public void updateStep(Graphic base, Feature f, XPathEvaluator<Feature> evaluator) {
                            LinkedList<BufferedImage> list = new LinkedList<BufferedImage>();
                            p.third.evaluate(list, f, evaluator);
                            base.image = list.poll();
                        }
                    };
                } else {
                    base.image = p.first;
                    base.imageURL = p.second;
                }
            } catch (IOException e) {
                LOG.debug("Stack trace", e);
                LOG.warn("External graphic could not be loaded. Location: line '{}' column '{}' of file '{}'.",
                        new Object[] { in.getLocation().getLineNumber(), in.getLocation().getColumnNumber(),
                                in.getLocation().getSystemId() });
            }
        } else if (in.getLocalName().equals("Opacity")) {
            contn = context.parser.updateOrContinue(in, "Opacity", base, new Updater<Graphic>() {
                public void update(Graphic obj, String val) {
                    obj.opacity = Double.parseDouble(val);
                }
            }, contn).second;
        } else if (in.getLocalName().equals("Size")) {
            contn = context.parser.updateOrContinue(in, "Size", base, new Updater<Graphic>() {
                public void update(Graphic obj, String val) {
                    obj.size = Double.parseDouble(val);
                }
            }, contn).second;
        } else if (in.getLocalName().equals("Rotation")) {
            contn = context.parser.updateOrContinue(in, "Rotation", base, new Updater<Graphic>() {
                public void update(Graphic obj, String val) {
                    obj.rotation = Double.parseDouble(val);
                }
            }, contn).second;
        } else if (in.getLocalName().equals("AnchorPoint")) {
            while (!(in.isEndElement() && in.getLocalName().equals("AnchorPoint"))) {
                in.nextTag();

                if (in.getLocalName().equals("AnchorPointX")) {
                    contn = context.parser.updateOrContinue(in, "AnchorPointX", base, new Updater<Graphic>() {
                        public void update(Graphic obj, String val) {
                            obj.anchorPointX = Double.parseDouble(val);
                        }
                    }, contn).second;
                } else if (in.getLocalName().equals("AnchorPointY")) {
                    contn = context.parser.updateOrContinue(in, "AnchorPointY", base, new Updater<Graphic>() {
                        public void update(Graphic obj, String val) {
                            obj.anchorPointY = Double.parseDouble(val);
                        }
                    }, contn).second;
                } else if (in.isStartElement()) {
                    Location loc = in.getLocation();
                    LOG.error("Found unknown element '{}' at line {}, column {}, skipping.",
                            new Object[] { in.getLocalName(), loc.getLineNumber(), loc.getColumnNumber() });
                    skipElement(in);
                }
            }
        } else if (in.getLocalName().equals("Displacement")) {
            while (!(in.isEndElement() && in.getLocalName().equals("Displacement"))) {
                in.nextTag();

                if (in.getLocalName().equals("DisplacementX")) {
                    contn = context.parser.updateOrContinue(in, "DisplacementX", base, new Updater<Graphic>() {
                        public void update(Graphic obj, String val) {
                            obj.displacementX = Double.parseDouble(val);
                        }
                    }, contn).second;
                } else if (in.getLocalName().equals("DisplacementY")) {
                    contn = context.parser.updateOrContinue(in, "DisplacementY", base, new Updater<Graphic>() {
                        public void update(Graphic obj, String val) {
                            obj.displacementY = Double.parseDouble(val);
                        }
                    }, contn).second;
                } else if (in.isStartElement()) {
                    Location loc = in.getLocation();
                    LOG.error("Found unknown element '{}' at line {}, column {}, skipping.",
                            new Object[] { in.getLocalName(), loc.getLineNumber(), loc.getColumnNumber() });
                    skipElement(in);
                }
            }
        } else if (in.isStartElement()) {
            Location loc = in.getLocation();
            LOG.error("Found unknown element '{}' at line {}, column {}, skipping.",
                    new Object[] { in.getLocalName(), loc.getLineNumber(), loc.getColumnNumber() });
            skipElement(in);
        }
    }
    in.require(END_ELEMENT, null, "Graphic");

    return new Pair<Graphic, Continuation<Graphic>>(base, contn);
}

From source file:org.deegree.style.se.parser.GraphicSymbologyParser.java

private Pair<Mark, Continuation<Mark>> parseMark(XMLStreamReader in) throws XMLStreamException {
    in.require(START_ELEMENT, null, "Mark");

    Mark base = new Mark();
    Continuation<Mark> contn = null;

    in.nextTag();/*from www.j a  v a2 s .  c  om*/

    while (!(in.isEndElement() && in.getLocalName().equals("Mark"))) {
        if (in.isEndElement()) {
            in.nextTag();
        }

        if (in.getLocalName().equals("WellKnownName")) {
            String wkn = in.getElementText();
            try {
                base.wellKnown = SimpleMark.valueOf(wkn.toUpperCase());
            } catch (IllegalArgumentException e) {
                LOG.warn("Specified unsupported WellKnownName of '{}', using square instead.", wkn);
                base.wellKnown = SimpleMark.SQUARE;
            }
        } else
            sym: if (in.getLocalName().equals("OnlineResource") || in.getLocalName().equals("InlineContent")) {
                LOG.debug("Loading mark from external file.");
                Triple<InputStream, String, Continuation<StringBuffer>> pair = getOnlineResourceOrInlineContent(
                        in);
                if (pair == null) {
                    in.nextTag();
                    break sym;
                }
                InputStream is = pair.first;
                in.nextTag();

                in.require(START_ELEMENT, null, "Format");
                String format = in.getElementText();
                in.require(END_ELEMENT, null, "Format");

                in.nextTag();
                if (in.getLocalName().equals("MarkIndex")) {
                    base.markIndex = Integer.parseInt(in.getElementText());
                }

                if (is != null) {
                    try {
                        java.awt.Font font = null;
                        if (format.equalsIgnoreCase("ttf")) {
                            font = createFont(TRUETYPE_FONT, is);
                        }
                        if (format.equalsIgnoreCase("type1")) {
                            font = createFont(TYPE1_FONT, is);
                        }

                        if (format.equalsIgnoreCase("svg")) {
                            base.shape = ShapeHelper.getShapeFromSvg(is, pair.second);
                        }

                        if (font == null && base.shape == null) {
                            LOG.warn("Mark was not loaded, because the format '{}' is not supported.", format);
                            break sym;
                        }

                        if (font != null && base.markIndex >= font.getNumGlyphs() - 1) {
                            LOG.warn("The font only contains {} glyphs, but the index given was {}.",
                                    font.getNumGlyphs(), base.markIndex);
                            break sym;
                        }

                        base.font = font;
                    } catch (FontFormatException e) {
                        LOG.debug("Stack trace:", e);
                        LOG.warn("The file was not a valid '{}' file: '{}'", format, e.getLocalizedMessage());
                    } catch (IOException e) {
                        LOG.debug("Stack trace:", e);
                        LOG.warn("The file could not be read: '{}'.", e.getLocalizedMessage());
                    } finally {
                        closeQuietly(is);
                    }
                }
            } else if (in.getLocalName().equals("Fill")) {
                final Pair<Fill, Continuation<Fill>> fill = context.fillParser.parseFill(in);
                base.fill = fill.first;
                if (fill.second != null) {
                    contn = new Continuation<Mark>(contn) {
                        @Override
                        public void updateStep(Mark base, Feature f, XPathEvaluator<Feature> evaluator) {
                            fill.second.evaluate(base.fill, f, evaluator);
                        }
                    };
                }
            } else if (in.getLocalName().equals("Stroke")) {
                final Pair<Stroke, Continuation<Stroke>> stroke = context.strokeParser.parseStroke(in);
                base.stroke = stroke.first;
                if (stroke.second != null) {
                    contn = new Continuation<Mark>(contn) {
                        @Override
                        public void updateStep(Mark base, Feature f, XPathEvaluator<Feature> evaluator) {
                            stroke.second.evaluate(base.stroke, f, evaluator);
                        }
                    };
                }
            } else if (in.isStartElement()) {
                Location loc = in.getLocation();
                LOG.error("Found unknown element '{}' at line {}, column {}, skipping.",
                        new Object[] { in.getLocalName(), loc.getLineNumber(), loc.getColumnNumber() });
                skipElement(in);
            }
    }

    in.require(END_ELEMENT, null, "Mark");

    return new Pair<Mark, Continuation<Mark>>(base, contn);
}

From source file:org.deegree.style.se.parser.GraphicSymbologyParser.java

private Triple<BufferedImage, String, Continuation<List<BufferedImage>>> parseExternalGraphic(
        final XMLStreamReader in) throws IOException, XMLStreamException {
    // TODO color replacement

    in.require(START_ELEMENT, null, "ExternalGraphic");

    String format = null;//from w ww. j a  va  2 s  . co  m
    BufferedImage img = null;
    String url = null;
    Triple<InputStream, String, Continuation<StringBuffer>> pair = null;
    Continuation<List<BufferedImage>> contn = null; // needs to be list to be updateable by reference...

    while (!(in.isEndElement() && in.getLocalName().equals("ExternalGraphic"))) {
        in.nextTag();

        if (in.getLocalName().equals("Format")) {
            format = in.getElementText();
        } else if (in.getLocalName().equals("OnlineResource") || in.getLocalName().equals("InlineContent")) {
            pair = getOnlineResourceOrInlineContent(in);
        } else if (in.isStartElement()) {
            Location loc = in.getLocation();
            LOG.error("Found unknown element '{}' at line {}, column {}, skipping.",
                    new Object[] { in.getLocalName(), loc.getLineNumber(), loc.getColumnNumber() });
            skipElement(in);
        }
    }

    try {
        if (pair != null) {
            if (pair.first != null && format != null && (format.toLowerCase().indexOf("svg") == -1)) {
                img = ImageIO.read(pair.first);
            }
            url = pair.second;

            final Continuation<StringBuffer> sbcontn = pair.third;

            if (pair.third != null) {
                final LinkedHashMap<String, BufferedImage> cache = new LinkedHashMap<String, BufferedImage>(
                        256) {
                    private static final long serialVersionUID = -6847956873232942891L;

                    @Override
                    protected boolean removeEldestEntry(Map.Entry<String, BufferedImage> eldest) {
                        return size() > 256; // yeah, hardcoded max size... TODO
                    }
                };
                contn = new Continuation<List<BufferedImage>>() {
                    @Override
                    public void updateStep(List<BufferedImage> base, Feature f,
                            XPathEvaluator<Feature> evaluator) {
                        StringBuffer sb = new StringBuffer();
                        sbcontn.evaluate(sb, f, evaluator);
                        String file = sb.toString();
                        if (cache.containsKey(file)) {
                            base.add(cache.get(file));
                            return;
                        }
                        try {
                            BufferedImage i;
                            if (context.location != null) {
                                i = ImageIO.read(context.location.resolve(file));
                            } else {
                                i = ImageIO.read(resolve(file, in));
                            }
                            base.add(i);
                            cache.put(file, i);
                        } catch (MalformedURLException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                };
            }
        }
    } finally {
        if (pair != null) {
            try {
                pair.first.close();
            } catch (Exception e) {
                LOG.trace("Stack trace when closing input stream:", e);
            }
        }
    }

    return new Triple<BufferedImage, String, Continuation<List<BufferedImage>>>(img, url, contn);
}

From source file:org.deegree.style.se.parser.GraphicSymbologyParser.java

private Triple<InputStream, String, Continuation<StringBuffer>> getOnlineResourceOrInlineContent(
        XMLStreamReader in) throws XMLStreamException {
    if (in.getLocalName().equals("OnlineResource")) {
        String str = in.getAttributeValue(XLNNS, "href");

        if (str == null) {
            Continuation<StringBuffer> contn = context.parser.updateOrContinue(in, "OnlineResource",
                    new StringBuffer(), SBUPDATER, null).second;
            return new Triple<InputStream, String, Continuation<StringBuffer>>(null, null, contn);
        }/*  w ww.  java 2  s.co  m*/

        String strUrl = null;
        try {
            URL url;
            if (context.location != null) {
                url = context.location.resolveToUrl(str);
            } else {
                url = resolve(str, in);
            }
            strUrl = url.toExternalForm();
            LOG.debug("Loading from URL '{}'", url);
            in.nextTag();
            return new Triple<InputStream, String, Continuation<StringBuffer>>(url.openStream(), strUrl, null);
        } catch (IOException e) {
            LOG.debug("Stack trace:", e);
            LOG.warn("Could not retrieve content at URL '{}'.", str);
            return null;
        }
    } else if (in.getLocalName().equals("InlineContent")) {
        String format = in.getAttributeValue(null, "encoding");
        if (format.equalsIgnoreCase("base64")) {
            ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decodeBase64(in.getElementText()));
            return new Triple<InputStream, String, Continuation<StringBuffer>>(bis, null, null);
        }
        // if ( format.equalsIgnoreCase( "xml" ) ) {
        // // TODO
        // }
    } else if (in.isStartElement()) {
        Location loc = in.getLocation();
        LOG.error("Found unknown element '{}' at line {}, column {}, skipping.",
                new Object[] { in.getLocalName(), loc.getLineNumber(), loc.getColumnNumber() });
        skipElement(in);
    }

    return null;
}