Example usage for javax.xml.stream XMLStreamReader require

List of usage examples for javax.xml.stream XMLStreamReader require

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamReader require.

Prototype

public void require(int type, String namespaceURI, String localName) throws XMLStreamException;

Source Link

Document

Test if the current event is of the given type and if the namespace and name match the current namespace and name of the current event.

Usage

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.ddi.DDIFileReader.java

private void processDDI(BufferedInputStream ddiStream, SDIOMetadata smd) throws IOException {
    XMLStreamReader xmlr = null;
    try {//from   ww w. j  ava 2  s  .  c  o  m
        xmlr = xmlInputFactory.createXMLStreamReader(ddiStream);
        //processDDI( xmlr, smd );
        xmlr.nextTag();
        xmlr.require(XMLStreamConstants.START_ELEMENT, null, "codeBook");
        processCodeBook(xmlr, smd);
        dbgLog.info("processed DDI.");

    } catch (XMLStreamException ex) {
        Logger.getLogger("global").log(Level.SEVERE, null, ex);
        throw new IOException(ex.getMessage());
    } finally {
        try {
            if (xmlr != null) {
                xmlr.close();
            }
        } catch (XMLStreamException ex) {
            // The message in the exception should contain diagnostics
            // information -- what was wrong with the DDI, etc.
            throw new IOException(ex.getMessage());
        }
        if (ddiStream != null) {
            ddiStream.close();
        }
    }

    // Having processed the entire ddi, we should have obtained all the metadata
    // describing the data set.
    // Configure the SMD metadata object:

    if (getVarQnty() > 0) {
        smd.getFileInformation().put("varQnty", getVarQnty());
        dbgLog.info("var quantity: " + getVarQnty());
        // TODO:
        // Validate the value against the actual number of variable sections
        // found in the DDI.
    } else {
        throw new IOException("Failed to obtain the variable quantity from the DDI supplied.");
    }

    if (getCaseQnty() > 0) {
        smd.getFileInformation().put("caseQnty", getCaseQnty());
    }
    // It's ok if caseQnty was not defined in the DDI, we'll try to read
    // the tab file supplied and assume that the number of lines is the
    // number of observations.

    smd.setVariableName(variableNameList.toArray(new String[variableNameList.size()]));

    // "minimal" variable types: SPSS type binary definition:
    // 0 means numeric, >0 means string.

    smd.setVariableTypeMinimal(
            ArrayUtils.toPrimitive(variableTypeList.toArray(new Integer[variableTypeList.size()])));

    // This is how the "discrete" and "continuous" numeric values are
    // distinguished in the data set metadata:

    smd.setDecimalVariables(decimalVariableSet);

    //TODO: smd.getFileInformation().put("caseWeightVariableName", caseWeightVariableName);

    smd.setVariableFormat(printFormatList);
    smd.setVariableFormatName(printFormatNameTable);
    smd.setVariableFormatCategory(formatCategoryTable); //TODO: verify

    // Store the variable labels, if supplied:

    if (!variableLabelMap.isEmpty()) {
        smd.setVariableLabel(variableLabelMap);
    }

    // Value labels, if supplied:

    if (!valueLabelTable.isEmpty()) {
        smd.setValueLabelTable(valueLabelTable);
        smd.setValueLabelMappingTable(valueVariableMappingTable);
    }

    // And missing values:

    if (!missingValueTable.isEmpty()) {
        smd.setMissingValueTable(missingValueTable);
    }

}

From source file:nl.ordina.bag.etl.util.XMLStreamReaderUtils.java

public static void getTag(XMLStreamReader reader, Tag tag) throws XMLStreamException {
    if (!reader.isStartElement() && !reader.isEndElement())
        reader.nextTag();//from  w  w  w .ja  v a 2 s. c  o  m
    reader.require(tag.getElementType(), null, tag.getLocalName());
}

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();/*w ww  .java 2  s  .com*/

        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();//ww w  .j a v a2 s . co m

    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  v  a2s . c om*/
    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.eclipse.sw360.licenseinfo.parsers.AbstractCLIParser.java

protected <T> boolean hasThisXMLRootElement(AttachmentContent content, String rootElementNamespace,
        String rootElementName, User user, T context) throws TException {
    XMLInputFactory xmlif = XMLInputFactory.newFactory();
    XMLStreamReader xmlStreamReader = null;
    InputStream attachmentStream = null;
    try {/*  w w  w  .  ja v a  2 s  .c  o  m*/
        attachmentStream = attachmentConnector.getAttachmentStream(content, user, context);
        xmlStreamReader = xmlif.createXMLStreamReader(attachmentStream);

        //skip to first element
        while (xmlStreamReader.hasNext() && xmlStreamReader.next() != XMLStreamConstants.START_ELEMENT)
            ;
        xmlStreamReader.require(XMLStreamConstants.START_ELEMENT, rootElementNamespace, rootElementName);
        return true;
    } catch (XMLStreamException | SW360Exception e) {
        return false;
    } finally {
        if (null != xmlStreamReader) {
            try {
                xmlStreamReader.close();
            } catch (XMLStreamException e) {
                // ignore it
            }
        }
        closeQuietly(attachmentStream, log);
    }
}

From source file:org.geowebcache.georss.StaxGeoRSSReader.java

private void parseEntryMember(final XMLStreamReader reader, final QName memberName, final Entry entry)
        throws XMLStreamException {

    reader.require(START_ELEMENT, memberName.getNamespaceURI(), memberName.getLocalPart());
    if (ATOM.id.equals(memberName)) {

        String id = text(reader);
        entry.setId(id);/*  ww  w .j  a  v a 2  s.co  m*/
    } else if (ATOM.link.equals(memberName)) {

        String uri = text(reader);
        URI link;
        try {
            link = new URI(uri);
            entry.setLink(link);
        } catch (URISyntaxException e) {
            logger.info("Feed contains illegal 'link' element content:" + uri);
        }
    } else if (ATOM.title.equals(memberName)) {

        String title = text(reader);
        entry.setTitle(title);
    } else if (ATOM.subtitle.equals(memberName)) {

        String subtitle = text(reader);
        entry.setSubtitle(subtitle);
    } else if (ATOM.updated.equals(memberName)) {

        String upd = text(reader);
        if (upd != null && upd.length() > 0) {
            entry.setUpdated(upd);
        }
    } else if (GEORSS.where.equals(memberName)) {

        QName nextTag = nextTag(reader);
        if (reader.isStartElement() && GML_NS_URI.equals(nextTag.getNamespaceURI())) {
            Geometry where = geometry(reader);
            if (logger.isTraceEnabled()) {
                logger.trace("Got geometry from feed: " + where);
            }
            entry.setWhere(where);
        }
    }

    consume(reader, memberName);

    reader.require(END_ELEMENT, memberName.getNamespaceURI(), memberName.getLocalPart());
}

From source file:org.geowebcache.georss.StaxGeoRSSReader.java

private Geometry geometry(final XMLStreamReader reader) throws XMLStreamException {
    reader.require(START_ELEMENT, GML.GML_NS_URI, null);
    QName name = reader.getName();
    Geometry geometry = gmlParser.parseGeometry(reader);
    reader.require(END_ELEMENT, name.getNamespaceURI(), name.getLocalPart());
    return geometry;
}

From source file:org.xwiki.filter.xar.internal.input.DocumentLocaleReader.java

public void read(XMLStreamReader xmlReader, Object filter, XARInputFilter proxyFilter)
        throws XMLStreamException, FilterException {
    resetDocument();//from w  w  w  . java  2s .  c om

    // <xwikidoc>

    xmlReader.nextTag();

    this.currentSourceType = this.properties.getSourceType();
    if (this.currentSourceType != null && this.currentSourceType != SourceType.DOCUMENT) {
        switch (this.currentSourceType) {
        case ATTACHMENT:
            readAttachment(xmlReader, filter, proxyFilter);
            break;

        case CLASS:
            readClass(xmlReader, filter, proxyFilter);

            break;

        case CLASSPROPERTY:
            readClassProperty(xmlReader, filter, proxyFilter);

            break;

        case OBJECT:
            readObject(xmlReader, filter, proxyFilter);

            break;

        case OBJECTPROPERTY:
            readObjectProperty(xmlReader, filter, proxyFilter);

            break;

        default:
            break;
        }
    } else {
        xmlReader.require(XMLStreamReader.START_ELEMENT, null, XarDocumentModel.ELEMENT_DOCUMENT);

        readDocument(xmlReader, filter, proxyFilter);
    }
}

From source file:org.xwiki.xar.internal.XarUtils.java

/**
 * Extract {@link LocalDocumentReference} from a XAR document XML stream.
 * //from  www  . jav a 2  s .  c  o  m
 * @param documentStream the stream to parse
 * @return the reference extracted from the stream
 * @throws XarException when failing to parse the document stream
 * @since 5.4M1
 */
public static LocalDocumentReference getReference(InputStream documentStream) throws XarException {
    XMLStreamReader xmlReader;
    try {
        xmlReader = XML_INPUT_FACTORY.createXMLStreamReader(documentStream);
    } catch (XMLStreamException e) {
        throw new XarException("Failed to create a XML read", e);
    }

    EntityReference reference = null;
    Locale locale = null;

    String legacySpace = null;
    String legacyPage = null;

    try {
        // <xwikidoc>

        xmlReader.nextTag();

        xmlReader.require(XMLStreamReader.START_ELEMENT, null, XarDocumentModel.ELEMENT_DOCUMENT);

        // Reference
        String referenceString = xmlReader.getAttributeValue(null,
                XarDocumentModel.ATTRIBUTE_DOCUMENT_REFERENCE);
        if (referenceString != null) {
            reference = RESOLVER.resolve(referenceString, EntityType.DOCUMENT);
        }

        // Locale
        String localeString = xmlReader.getAttributeValue(null, XarDocumentModel.ATTRIBUTE_DOCUMENT_LOCALE);
        if (localeString != null) {
            if (localeString.isEmpty()) {
                locale = Locale.ROOT;
            } else {
                locale = LocaleUtils.toLocale(localeString);
            }
        }

        // Legacy fallback
        if (reference == null || locale == null) {
            for (xmlReader.nextTag(); xmlReader.isStartElement(); xmlReader.nextTag()) {
                String elementName = xmlReader.getLocalName();

                if (XarDocumentModel.ELEMENT_NAME.equals(elementName)) {
                    if (reference == null) {
                        legacyPage = xmlReader.getElementText();

                        if (legacySpace != null && locale != null) {
                            break;
                        }
                    } else if (locale != null) {
                        break;
                    }
                } else if (XarDocumentModel.ELEMENT_SPACE.equals(elementName)) {
                    if (reference == null) {
                        legacySpace = xmlReader.getElementText();

                        if (legacyPage != null && locale != null) {
                            break;
                        }
                    } else if (locale != null) {
                        break;
                    }
                } else if (XarDocumentModel.ELEMENT_LOCALE.equals(elementName)) {
                    if (locale == null) {
                        String value = xmlReader.getElementText();
                        if (value.length() == 0) {
                            locale = Locale.ROOT;
                        } else {
                            locale = LocaleUtils.toLocale(value);
                        }
                    }

                    if (reference != null || (legacySpace != null && legacyPage != null)) {
                        break;
                    }
                } else {
                    StAXUtils.skipElement(xmlReader);
                }
            }
        }
    } catch (XMLStreamException e) {
        throw new XarException("Failed to parse document", e);
    } finally {
        try {
            xmlReader.close();
        } catch (XMLStreamException e) {
            throw new XarException("Failed to close XML reader", e);
        }
    }

    if (reference == null) {
        if (legacySpace == null) {
            throw new XarException("Missing space element");
        }
        if (legacyPage == null) {
            throw new XarException("Missing page element");
        }

        reference = new LocalDocumentReference(legacySpace, legacyPage);
    }

    if (locale == null) {
        throw new XarException("Missing locale element");
    }

    return new LocalDocumentReference(reference, locale);
}