Example usage for javax.xml.stream XMLStreamConstants START_ELEMENT

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

Introduction

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

Prototype

int START_ELEMENT

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

Click Source Link

Document

Indicates an event is a start element

Usage

From source file:de.huxhorn.sulky.plist.impl.PropertyListReader.java

private Map<String, ?> readDict(XMLStreamReader reader) throws XMLStreamException {
    reader.require(XMLStreamConstants.START_ELEMENT, null, DICT_NODE);
    reader.nextTag();//from w  ww  .j  a va2 s. c o  m
    Map<String, Object> map = new HashMap<String, Object>();
    for (;;) {
        int type = reader.getEventType();
        if (XMLStreamConstants.END_ELEMENT == type && DICT_NODE.equals(reader.getLocalName())) {
            reader.nextTag();
            break;
        }
        String key = StaxUtilities.readSimpleTextNodeIfAvailable(reader, null, KEY_NODE);
        if (key != null) {
            map.put(key, readValue(reader));
        }
    }
    return map;
}

From source file:com.graphhopper.reader.OSMInputFile.java

private OSMElement getNextXML() throws XMLStreamException {

    int event = parser.next();
    if (fileheader != null) {
        OSMElement copyfileheader = fileheader;
        fileheader = null;//from   w w  w . ja  v a2 s. c om
        return copyfileheader;
    }

    while (event != XMLStreamConstants.END_DOCUMENT) {
        if (event == XMLStreamConstants.START_ELEMENT) {
            String idStr = parser.getAttributeValue(null, "id");
            if (idStr != null) {
                String name = parser.getLocalName();
                long id = 0;
                switch (name.charAt(0)) {
                case 'n':
                    // note vs. node
                    if ("node".equals(name)) {
                        id = Long.parseLong(idStr);
                        return OSMNode.create(id, parser);
                    }
                    break;

                case 'w': {
                    id = Long.parseLong(idStr);
                    return OSMWay.create(id, parser);
                }
                case 'r':
                    id = Long.parseLong(idStr);
                    return OSMRelation.create(id, parser);
                }
            }
        }
        event = parser.next();
    }
    parser.close();
    return null;
}

From source file:de.tuebingen.uni.sfs.germanet.api.IliLoader.java

/**
 * Returns the <code>IliRecord</code> for which the start tag was just encountered.
 * @param parser the <code>parser</code> being used on the current file
 * @return a <code>IliRecord</code> representing the data parsed
 * @throws javax.xml.stream.XMLStreamException
 *//*ww w  . j  ava2 s. c o  m*/
private IliRecord processIliRecord(XMLStreamReader parser) throws XMLStreamException {
    int lexUnitId;
    String ewnRelation;
    String pwnWord;
    String pwn20Id;
    String pwn30Id;
    String pwn20paraphrase = "";
    String source;
    IliRecord curIli;
    List<String> englishSynonyms = new ArrayList<String>();
    boolean done = false;
    int event;
    String nodeName;
    lexUnitId = Integer.valueOf(parser.getAttributeValue(namespace, GermaNet.XML_LEX_UNIT_ID).substring(1));
    ewnRelation = parser.getAttributeValue(namespace, GermaNet.XML_EWN_RELATION);
    pwnWord = parser.getAttributeValue(namespace, GermaNet.XML_PWN_WORD);
    pwn20Id = parser.getAttributeValue(namespace, GermaNet.XML_PWN20_ID);
    pwn30Id = parser.getAttributeValue(namespace, GermaNet.XML_PWN30_ID);
    pwn20paraphrase = parser.getAttributeValue(namespace, GermaNet.XML_PWN20_PARAPHRASE);

    source = parser.getAttributeValue(namespace, GermaNet.XML_SOURCE);

    // process this lexUnit
    while (parser.hasNext() && !done) {
        event = parser.next();
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            nodeName = parser.getLocalName();
            if (nodeName.equals(GermaNet.XML_PWN20_SYNONYM)) {
                englishSynonyms.add(processEnglishSynonyms(parser));
            }
        case XMLStreamConstants.END_ELEMENT:
            nodeName = parser.getLocalName();
            // quit when we reach the end lexUnit tag
            if (nodeName.equals(GermaNet.XML_ILI_RECORD)) {
                done = true;
            }
            break;
        }
    }

    curIli = new IliRecord(lexUnitId, EwnRel.valueOf(ewnRelation), pwnWord, pwn20Id, pwn30Id, pwn20paraphrase,
            source);

    for (String synonym : englishSynonyms) {
        curIli.addEnglishSynonym(synonym);
    }

    return curIli;
}

From source file:com.liferay.portal.util.LocalizationImpl.java

public String getLocalization(String xml, String requestedLanguageId, boolean useDefault) {

    String value = _getCachedValue(xml, requestedLanguageId, useDefault);

    if (value != null) {
        return value;
    } else {/*www  . j  av a  2s .c  om*/
        value = StringPool.BLANK;
    }

    String systemDefaultLanguageId = LocaleUtil.toLanguageId(LocaleUtil.getDefault());

    String priorityLanguageId = null;

    Locale requestedLocale = LocaleUtil.fromLanguageId(requestedLanguageId);

    if (useDefault && LanguageUtil.isDuplicateLanguageCode(requestedLocale.getLanguage())) {

        Locale priorityLocale = LanguageUtil.getLocale(requestedLocale.getLanguage());

        if (!requestedLanguageId.equals(priorityLanguageId)) {
            priorityLanguageId = LocaleUtil.toLanguageId(priorityLocale);
        }
    }

    if (!Validator.isXml(xml)) {
        if (useDefault || requestedLanguageId.equals(systemDefaultLanguageId)) {

            value = xml;
        }

        _setCachedValue(xml, requestedLanguageId, useDefault, value);

        return value;
    }

    XMLStreamReader xmlStreamReader = null;

    ClassLoader portalClassLoader = PortalClassLoaderUtil.getClassLoader();

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    try {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(portalClassLoader);
        }

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();

        xmlStreamReader = xmlInputFactory.createXMLStreamReader(new UnsyncStringReader(xml));

        String defaultLanguageId = StringPool.BLANK;

        // Skip root node

        if (xmlStreamReader.hasNext()) {
            xmlStreamReader.nextTag();

            defaultLanguageId = xmlStreamReader.getAttributeValue(null, _DEFAULT_LOCALE);

            if (Validator.isNull(defaultLanguageId)) {
                defaultLanguageId = systemDefaultLanguageId;
            }
        }

        // Find specified language and/or default language

        String defaultValue = StringPool.BLANK;
        String priorityValue = StringPool.BLANK;

        while (xmlStreamReader.hasNext()) {
            int event = xmlStreamReader.next();

            if (event == XMLStreamConstants.START_ELEMENT) {
                String languageId = xmlStreamReader.getAttributeValue(null, _LANGUAGE_ID);

                if (Validator.isNull(languageId)) {
                    languageId = defaultLanguageId;
                }

                if (languageId.equals(defaultLanguageId) || languageId.equals(priorityLanguageId)
                        || languageId.equals(requestedLanguageId)) {

                    String text = xmlStreamReader.getElementText();

                    if (languageId.equals(defaultLanguageId)) {
                        defaultValue = text;
                    }

                    if (languageId.equals(priorityLanguageId)) {
                        priorityValue = text;
                    }

                    if (languageId.equals(requestedLanguageId)) {
                        value = text;
                    }

                    if (Validator.isNotNull(value)) {
                        break;
                    }
                }
            } else if (event == XMLStreamConstants.END_DOCUMENT) {
                break;
            }
        }

        if (useDefault && Validator.isNotNull(priorityLanguageId) && Validator.isNull(value)
                && Validator.isNotNull(priorityValue)) {

            value = priorityValue;
        }

        if (useDefault && Validator.isNull(value)) {
            value = defaultValue;
        }
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn(e, e);
        }
    } finally {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(contextClassLoader);
        }

        if (xmlStreamReader != null) {
            try {
                xmlStreamReader.close();
            } catch (Exception e) {
            }
        }
    }

    _setCachedValue(xml, requestedLanguageId, useDefault, value);

    return value;
}

From source file:com.evolveum.midpoint.common.validator.Validator.java

public void validate(InputStream inputStream, OperationResult validatorResult,
        String objectResultOperationName) {

    XMLStreamReader stream = null;
    try {//from   w  w w .  j  a  v a  2 s . c o  m

        Map<String, String> rootNamespaceDeclarations = new HashMap<String, String>();

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        stream = xmlInputFactory.createXMLStreamReader(inputStream);

        int eventType = stream.nextTag();
        if (eventType == XMLStreamConstants.START_ELEMENT) {
            if (!stream.getName().equals(SchemaConstants.C_OBJECTS)) {
                // This has to be an import file with a single objects. Try
                // to process it.
                OperationResult objectResult = validatorResult.createSubresult(objectResultOperationName);
                progress++;
                objectResult.addContext(OperationResult.CONTEXT_PROGRESS, progress);

                EventResult cont = null;
                try {
                    cont = readFromStreamAndValidate(stream, objectResult, rootNamespaceDeclarations,
                            validatorResult);
                } catch (RuntimeException e) {
                    // Make sure that unexpected error is recorded.
                    objectResult.recordFatalError(e);
                    throw e;
                }

                if (!cont.isCont()) {
                    String message = null;
                    if (cont.getReason() != null) {
                        message = cont.getReason();
                    } else {
                        message = "Object validation failed (no reason given)";
                    }
                    if (objectResult.isUnknown()) {
                        objectResult.recordFatalError(message);
                    }
                    validatorResult.recordFatalError(message);
                    return;
                }
                // return to avoid processing objects in loop
                validatorResult.computeStatus("Validation failed", "Validation warnings");
                return;
            }
            // Extract root namespace declarations
            for (int i = 0; i < stream.getNamespaceCount(); i++) {
                rootNamespaceDeclarations.put(stream.getNamespacePrefix(i), stream.getNamespaceURI(i));
            }
        } else {
            throw new SystemException("StAX Malfunction?");
        }

        while (stream.hasNext()) {
            eventType = stream.next();
            if (eventType == XMLStreamConstants.START_ELEMENT) {

                OperationResult objectResult = validatorResult.createSubresult(objectResultOperationName);
                progress++;
                objectResult.addContext(OperationResult.CONTEXT_PROGRESS, progress);

                EventResult cont = null;
                try {
                    // Read and validate individual object from the stream
                    cont = readFromStreamAndValidate(stream, objectResult, rootNamespaceDeclarations,
                            validatorResult);
                } catch (RuntimeException e) {
                    if (objectResult.isUnknown()) {
                        // Make sure that unexpected error is recorded.
                        objectResult.recordFatalError(e);
                    }
                    throw e;
                }

                if (objectResult.isError()) {
                    errors++;
                }

                objectResult.cleanupResult();
                validatorResult.summarize();

                if (cont.isStop()) {
                    if (cont.getReason() != null) {
                        validatorResult.recordFatalError("Processing has been stopped: " + cont.getReason());
                    } else {
                        validatorResult.recordFatalError("Processing has been stopped");
                    }
                    // This means total stop, no other objects will be
                    // processed
                    return;
                }
                if (!cont.isCont()) {
                    if (stopAfterErrors > 0 && errors >= stopAfterErrors) {
                        validatorResult.recordFatalError("Too many errors (" + errors + ")");
                        return;
                    }
                }
            }
        }

    } catch (XMLStreamException ex) {
        // validatorResult.recordFatalError("XML parsing error: " +
        // ex.getMessage()+" on line "+stream.getLocation().getLineNumber(),ex);
        validatorResult.recordFatalError("XML parsing error: " + ex.getMessage(), ex);
        if (handler != null) {
            handler.handleGlobalError(validatorResult);
        }
        return;
    }

    // Error count is sufficient. Detailed messages are in subresults
    validatorResult.computeStatus(errors + " errors, " + (progress - errors) + " passed");

}

From source file:com.graphhopper.reader.osm.OSMInputFile.java

private ReaderElement getNextXML() throws XMLStreamException {

    int event = parser.next();
    if (fileheader != null) {
        ReaderElement copyfileheader = fileheader;
        fileheader = null;//from  w  ww  .j  ava  2  s. c  o m
        return copyfileheader;
    }

    while (event != XMLStreamConstants.END_DOCUMENT) {
        if (event == XMLStreamConstants.START_ELEMENT) {
            String idStr = parser.getAttributeValue(null, "id");
            if (idStr != null) {
                String name = parser.getLocalName();
                long id = 0;
                switch (name.charAt(0)) {
                case 'n':
                    // note vs. node
                    if ("node".equals(name)) {
                        id = Long.parseLong(idStr);
                        return OSMXMLHelper.createNode(id, parser);
                    }
                    break;

                case 'w': {
                    id = Long.parseLong(idStr);
                    return OSMXMLHelper.createWay(id, parser);
                }
                case 'r':
                    id = Long.parseLong(idStr);
                    return OSMXMLHelper.createRelation(id, parser);
                }
            }
        }
        event = parser.next();
    }
    parser.close();
    return null;
}

From source file:de.huxhorn.sulky.plist.impl.PropertyListReader.java

private List<?> readArray(XMLStreamReader reader) throws XMLStreamException {
    reader.require(XMLStreamConstants.START_ELEMENT, null, ARRAY_NODE);
    reader.nextTag();//w  w w.j  a  v a 2s . co m
    List<Object> array = new ArrayList<Object>();
    for (;;) {
        int type = reader.getEventType();
        if (XMLStreamConstants.END_ELEMENT == type && ARRAY_NODE.equals(reader.getLocalName())) {
            reader.nextTag();
            break;
        }
        array.add(readValue(reader));
    }
    return array;
}

From source file:com.flexive.chemistry.webdav.TextDocumentResource.java

/**
 * Set the value of a property, stream points to the start of the property tag.
 *
 * @param parser    the XML parser/* w w  w.ja va2  s.c o  m*/
 * @throws XMLStreamException   on parsing errors
 */
protected void processProperty(XMLStreamReader parser) throws XMLStreamException {
    int level = 0;
    String name = null;
    for (int i = 0; i < parser.getAttributeCount(); i++) {
        if ("name".equals(parser.getAttributeName(i).getLocalPart())) {
            name = parser.getAttributeValue(i);
            break;
        }
    }
    if (name == null) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("property without name attribute encountered");
        }
        return;
    }

    String value = null;
    for (int event = parser.nextTag(); event != XMLStreamConstants.END_DOCUMENT
            && level >= 0; event = parser.nextTag()) {
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            if ("value".equals(parser.getLocalName())) {
                value = parser.getElementText().trim();
            } else if ("name".equals(parser.getLocalName())) {
                name = parser.getElementText();
            } else {
                level++;
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            level--;
            break;
        }
    }

    if (value != null) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Setting field " + name + " to " + value);
        }
        try {
            object.setValue(name, value);
        } catch (Exception e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Failed to set field " + name + " (ignored): " + e.getMessage());
            }
        }
    }
}

From source file:babel.content.pages.Page.java

public void unpersist(XMLStreamReader reader) throws XMLStreamException {
    String elemTag;// w  ww . j  a  va2s .  com
    PageVersion ver;

    m_pageURL = reader.getAttributeValue(0);
    m_versions.clear();

    while (true) {
        int event = reader.next();

        if (event == XMLStreamConstants.END_ELEMENT && XML_TAG_PAGE.equals(reader.getName().toString())) {
            break;
        }

        if (event == XMLStreamConstants.START_ELEMENT) {
            elemTag = reader.getName().toString();

            if ("MetaData".equals(elemTag)) {
                m_pageProps.unpersist(reader);
            } else if ("PageVersion".equals(elemTag)) {
                ver = new PageVersion();
                ver.unpersist(reader);

                m_versions.add(ver);
            }
        }
    }
}

From source file:de.ii.xtraplatform.ogc.api.gml.parser.GMLParser.java

private void parseFeature(SMInputCursor cursor) throws XMLStreamException {

    analyzer.analyzeFeatureStart(null, cursor.getNsUri(), cursor.getLocalName());

    featureDepth = cursor.getParentCount();

    for (int i = 0; i < cursor.getAttrCount(); i++) {
        analyzer.analyzeAttribute(cursor.getAttrNsUri(i), cursor.getAttrLocalName(i), cursor.getAttrValue(i));
    }// w ww  .  ja  va 2s  .c  om

    SMFlatteningCursor feature;
    StringBuilder text = null;
    if (parseText) {
        feature = (SMFlatteningCursor) cursor.descendantCursor().advance();
        text = new StringBuilder();
    } else {
        feature = (SMFlatteningCursor) cursor.descendantElementCursor().advance();
    }

    while (feature.readerAccessible()) {
        if (feature.getCurrEventCode() == XMLStreamConstants.START_ELEMENT) {
            boolean nil = false;

            for (int i = 0; i < feature.getAttrCount(); i++) {
                if (feature.getAttrNsUri(i).equals(XSI.getNS(XSI.VERSION.DEFAULT))
                        && feature.getAttrLocalName(i).equals(XSI.getWord(XSI.VOCABULARY.NIL))
                        && feature.getAttrValue(i).equals(XSI.getWord(XSI.VOCABULARY.NIL_TRUE))) {
                    nil = true;
                }
                analyzer.analyzeAttribute(feature.getAttrNsUri(i), feature.getAttrLocalName(i),
                        feature.getAttrValue(i));
            }

            analyzer.analyzePropertyStart(feature.getNsUri(), feature.getLocalName(),
                    feature.getParentCount() - featureDepth, feature, nil);

        } else if (feature.getCurrEventCode() == XMLStreamConstants.END_ELEMENT) {
            if (parseText && text.length() > 0) {
                analyzer.analyzePropertyText(feature.getNsUri(), feature.getLocalName(),
                        feature.getParentCount() - featureDepth, text.toString());
                text = new StringBuilder();
            }
            analyzer.analyzePropertyEnd(feature.getNsUri(), feature.getLocalName(),
                    feature.getParentCount() - featureDepth);
        } else if (parseText && (feature.getCurrEventCode() == XMLStreamConstants.CHARACTERS)) {
            text.append(feature.getText().trim());
        }

        feature = (SMFlatteningCursor) feature.advance();
    }

    analyzer.analyzeFeatureEnd();
}