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:com.evolveum.midpoint.prism.lex.dom.DomLexicalProcessor.java

@Override
public void readObjectsIteratively(@NotNull ParserSource source, @NotNull ParsingContext parsingContext,
        RootXNodeHandler handler) throws SchemaException, IOException {
    InputStream is = source.getInputStream();
    XMLStreamReader stream = null;
    try {/* w  ww  . j a  v a  2 s.c om*/
        stream = XMLInputFactory.newInstance().createXMLStreamReader(is);

        int eventType = stream.nextTag();
        if (eventType != XMLStreamConstants.START_ELEMENT) {
            throw new SystemException("StAX Malfunction?");
        }
        DOMConverter domConverter = new DOMConverter();
        Map<String, String> rootNamespaceDeclarations = new HashMap<>();

        QName objectsMarker = schemaRegistry.getPrismContext().getObjectsElementName();
        if (objectsMarker != null && !QNameUtil.match(stream.getName(), objectsMarker)) {
            readSingleObjectIteratively(stream, rootNamespaceDeclarations, domConverter, handler);
        }
        for (int i = 0; i < stream.getNamespaceCount(); i++) {
            rootNamespaceDeclarations.put(stream.getNamespacePrefix(i), stream.getNamespaceURI(i));
        }
        while (stream.hasNext()) {
            eventType = stream.next();
            if (eventType == XMLStreamConstants.START_ELEMENT) {
                if (!readSingleObjectIteratively(stream, rootNamespaceDeclarations, domConverter, handler)) {
                    return;
                }
            }
        }
    } catch (XMLStreamException ex) {
        String lineInfo = stream != null ? " on line " + stream.getLocation().getLineNumber() : "";
        throw new SchemaException("Exception while parsing XML" + lineInfo + ": " + ex.getMessage(), ex);
    } finally {
        if (source.closeStreamAfterParsing()) {
            IOUtils.closeQuietly(is);
        }
    }
}

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

private void openXMLStream(InputStream in) throws XMLStreamException {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    parser = factory.createXMLStreamReader(in, "UTF-8");

    int event = parser.next();
    if (event != XMLStreamConstants.START_ELEMENT || !parser.getLocalName().equalsIgnoreCase("osm")) {
        throw new IllegalArgumentException("File is not a valid OSM stream");
    }//w  ww .  j a va 2  s  .c  o  m
    // See https://wiki.openstreetmap.org/wiki/PBF_Format#Definition_of_the_OSMHeader_fileblock
    String timestamp = parser.getAttributeValue(null, "osmosis_replication_timestamp");

    if (timestamp == null)
        timestamp = parser.getAttributeValue(null, "timestamp");

    if (timestamp != null) {
        try {
            fileheader = new OSMFileHeader();
            fileheader.setTag("timestamp", timestamp);
        } catch (Exception ex) {
        }
    }

    eof = false;
}

From source file:com.evolveum.polygon.connector.hcm.DocumentProcessing.java

public Map<String, Object> parseXMLData(HcmConnectorConfiguration conf, ResultsHandler handler,
        Map<String, Object> schemaAttributeMap, Filter query) {

    XMLInputFactory factory = XMLInputFactory.newInstance();
    try {//from   w ww .  j ava  2s  .c om

        String uidAttributeName = conf.getUidAttribute();
        String primariId = conf.getPrimaryId();
        String startName = "";
        String value = null;

        StringBuilder assignmentXMLBuilder = null;

        List<String> builderList = new ArrayList<String>();

        Integer nOfIterations = 0;
        Boolean isSubjectToQuery = false;
        Boolean isAssigment = false;
        Boolean evaluateAttr = true;
        Boolean specificAttributeQuery = false;

        XMLEventReader eventReader = factory.createXMLEventReader(new FileReader(conf.getFilePath()));
        List<String> dictionary = populateDictionary(FIRSTFLAG);

        if (!attrsToGet.isEmpty()) {

            attrsToGet.add(uidAttributeName);
            attrsToGet.add(primariId);
            specificAttributeQuery = true;
            evaluateAttr = false;
            LOGGER.ok("The uid and primary id were added to the queried attribute list");

            schemaAttributeMap = modifySchemaAttributeMap(schemaAttributeMap);
        }

        while (eventReader.hasNext()) {

            XMLEvent event = eventReader.nextEvent();

            Integer code = event.getEventType();

            if (code == XMLStreamConstants.START_ELEMENT) {

                StartElement startElement = event.asStartElement();
                startName = startElement.getName().getLocalPart();

                if (!evaluateAttr && attrsToGet.contains(startName)) {

                    evaluateAttr = true;
                }

                if (!elementIsEmployeeData) {

                    if (startName.equals(EMPLOYEES)) {

                        if (dictionary.contains(nOfIterations.toString())) {
                            LOGGER.ok("The defined number of iterations has been hit: {0}",
                                    nOfIterations.toString());
                            break;
                        } else {
                            startName = "";
                            elementIsEmployeeData = true;
                            nOfIterations++;
                        }
                    }
                } else if (evaluateAttr) {

                    if (!isAssigment) {
                        if (!ASSIGNMENTTAG.equals(startName)) {

                        } else {
                            assignmentXMLBuilder = new StringBuilder();
                            isAssigment = true;
                        }
                    } else {

                        builderList = processAssignment(startName, null, START, builderList);
                    }

                    if (multiValuedAttributesList.contains(startName)) {

                        elementIsMultiValued = true;
                    }

                }

            } else if (elementIsEmployeeData) {

                if (code == XMLStreamConstants.CHARACTERS && evaluateAttr) {

                    Characters characters = event.asCharacters();

                    if (!characters.isWhiteSpace()) {

                        StringBuilder valueBuilder;
                        if (value != null) {
                            valueBuilder = new StringBuilder(value).append("")
                                    .append(characters.getData().toString());
                        } else {
                            valueBuilder = new StringBuilder(characters.getData().toString());
                        }
                        value = valueBuilder.toString();
                        // value = StringEscapeUtils.escapeXml10(value);
                        // LOGGER.info("The attribute value for: {0} is
                        // {1}", startName, value);
                    }
                } else if (code == XMLStreamConstants.END_ELEMENT) {

                    EndElement endElement = event.asEndElement();
                    String endName = endElement.getName().getLocalPart();

                    isSubjectToQuery = checkFilter(endName, value, query, uidAttributeName);

                    if (!isSubjectToQuery) {
                        attributeMap.clear();
                        elementIsEmployeeData = false;
                        value = null;

                        endName = EMPLOYEES;
                    }

                    if (endName.equals(EMPLOYEES)) {

                        attributeMap = handleEmployeeData(attributeMap, schemaAttributeMap, handler,
                                uidAttributeName, primariId);

                        elementIsEmployeeData = false;

                    } else if (evaluateAttr) {

                        if (endName.equals(startName)) {
                            if (value != null) {

                                if (!isAssigment) {
                                    if (!elementIsMultiValued) {

                                        attributeMap.put(startName, value);
                                    } else {

                                        multiValuedAttributeBuffer.put(startName, value);
                                    }
                                } else {

                                    value = StringEscapeUtils.escapeXml10(value);
                                    builderList = processAssignment(endName, value, VALUE, builderList);

                                    builderList = processAssignment(endName, null, END, builderList);
                                }
                                // LOGGER.info("Attribute name: {0} and the
                                // Attribute value: {1}", endName, value);
                                value = null;
                            }
                        } else {
                            if (endName.equals(ASSIGNMENTTAG)) {

                                builderList = processAssignment(endName, null, CLOSE, builderList);

                                // if (assigmentIsActive) {

                                for (String records : builderList) {
                                    assignmentXMLBuilder.append(records);

                                }
                                attributeMap.put(ASSIGNMENTTAG, assignmentXMLBuilder.toString());
                                // } else {
                                // }

                                builderList = new ArrayList<String>();
                                // assigmentIsActive = false;
                                isAssigment = false;

                            } else if (multiValuedAttributesList.contains(endName)) {
                                processMultiValuedAttributes(multiValuedAttributeBuffer);
                            }
                        }

                    }
                    if (specificAttributeQuery && evaluateAttr) {

                        evaluateAttr = false;
                    }
                }
            } else if (code == XMLStreamConstants.END_DOCUMENT) {
                handleBufferedData(uidAttributeName, primariId, handler);
            }
        }

    } catch (FileNotFoundException e) {
        StringBuilder errorBuilder = new StringBuilder("File not found at the specified path.")
                .append(e.getLocalizedMessage());
        LOGGER.error("File not found at the specified path: {0}", e);
        throw new ConnectorIOException(errorBuilder.toString());
    } catch (XMLStreamException e) {

        LOGGER.error("Unexpected processing error while parsing the .xml document : {0}", e);

        StringBuilder errorBuilder = new StringBuilder(
                "Unexpected processing error while parsing the .xml document. ")
                        .append(e.getLocalizedMessage());

        throw new ConnectorIOException(errorBuilder.toString());
    }
    return attributeMap;

}

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

private Object readDate(XMLStreamReader reader) throws XMLStreamException {
    reader.require(XMLStreamConstants.START_ELEMENT, null, DATE_NODE);
    String text = StaxUtilities.readSimpleTextNodeIfAvailable(reader, null, DATE_NODE);
    try {//ww w  . ja v  a2s  .c om
        return format.parse(text);
    } catch (ParseException e) {
        throw new XMLStreamException("Invalid date: '" + text + "'", e);
    }
}

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

protected void processXmlProperties(InputStream in) {
    final XMLInputFactory factory = XMLInputFactory.newInstance();
    try {//from www. ja v a  2 s  .c  o  m
        final XMLStreamReader parser = factory.createXMLStreamReader(in);
        for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                if ("property".equals(parser.getLocalName())) {
                    processProperty(parser);
                } else if ("name".equals(parser.getLocalName())) {
                    processName(parser);
                }

            }
        }
    } catch (XMLStreamException e) {
        throw new RuntimeException("Failed to replace content: " + e.getMessage(), e);
    }
}

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

/**
 * Loads <code>WiktionaryParaphrases</code> from the given streams into this
 * <code>WiktionaryLoader</code>'s <code>GermaNet</code> object.
 * @param inputStreams the list of streams containing <code>WiktionaryParaphrases</code> data
 * @param xmlNames the names of the streams
 * @throws javax.xml.stream.XMLStreamException
 *//* w  w  w . j av  a  2 s . c om*/
protected void loadWiktionary(List<InputStream> inputStreams, List<String> xmlNames) throws XMLStreamException {

    for (int i = 0; i < inputStreams.size(); i++) {
        if (xmlNames.get(i).startsWith("wiktionary")) {
            logger.debug("Loading input stream " + xmlNames.get(i) + "...");
            XMLInputFactory factory = XMLInputFactory.newInstance();
            XMLStreamReader parser = factory.createXMLStreamReader(inputStreams.get(i));
            int event;
            String nodeName;

            //Parse entire file, looking for Wiktionary paraphrase start elements
            while (parser.hasNext()) {
                event = parser.next();
                switch (event) {
                case XMLStreamConstants.START_DOCUMENT:
                    namespace = parser.getNamespaceURI();
                    break;
                case XMLStreamConstants.START_ELEMENT:
                    nodeName = parser.getLocalName();
                    if (nodeName.equals(GermaNet.XML_WIKTIONARY_PARAPHRASE)) {
                        WiktionaryParaphrase wiki = processWiktionaryParaphrase(parser);
                        germaNet.addWiktionaryParaphrase(wiki);
                    }
                    break;
                }
            }
            parser.close();
        }
    }

    logger.debug("Done.");

}

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

private byte[] readData(XMLStreamReader reader) throws XMLStreamException {
    reader.require(XMLStreamConstants.START_ELEMENT, null, DATA_NODE);
    String text = StaxUtilities.readSimpleTextNodeIfAvailable(reader, null, DATA_NODE);
    return Base64.decodeBase64(text);
}

From source file:com.microsoft.tfs.core.memento.XMLMemento.java

/**
 * Reads the current element from the given reader and returns the
 * {@link XMLMemento} read from its data. The {@link XMLStreamReader} must
 * be positioned at {@link XMLStreamConstants#START_ELEMENT}.
 *
 * @param reader/*from  w ww.  ja  v  a2  s.c  o  m*/
 *        the reader (must not be <code>null</code>)
 * @return the {@link XMLMemento} read from the stream
 * @throws XMLStreamException
 *         if an error occurred reading from the reader
 */
private synchronized void readFromElement(final XMLStreamReader reader) throws XMLStreamException {
    Check.notNull(reader, "reader"); //$NON-NLS-1$

    /*
     * Read all the attributes from the current element.
     */
    final int attributeCount = reader.getAttributeCount();
    for (int i = 0; i < attributeCount; i++) {
        putString(reader.getAttributeLocalName(i), reader.getAttributeValue(i));
    }

    /*
     * Process child nodes (which may be text or child Mementos).
     */
    String localName;
    int event;
    do {
        event = reader.next();

        if (event == XMLStreamConstants.START_ELEMENT) {
            localName = reader.getLocalName();

            final XMLMemento child = (XMLMemento) createChild(localName);
            child.readFromElement(reader);
        } else if (event == XMLStreamConstants.CHARACTERS) {
            putTextData(reader.getText());
        }
    } while (event != XMLStreamConstants.END_ELEMENT);
}

From source file:edu.indiana.d2i.htrc.io.index.solr.SolrClient.java

private NamedVector parseOneVolume(InputStream content) throws XMLStreamException, IOException {
    //      java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(content));
    //      String line = "";
    //      while ((line = br.readLine()) != null) {
    //         System.out.println(line);
    //      }/*  w  w  w . j av  a2s  . c om*/
    //      br.close();

    String volumeID = null;
    Vector vector = null;
    XMLStreamReader parser = factory.createXMLStreamReader(content);
    while (parser.hasNext()) {
        int event = parser.next();
        if (event == XMLStreamConstants.START_ELEMENT) {
            String attributeValue = parser.getAttributeValue(null, "name");
            if (attributeValue != null) {
                if (attributeValue.equals(VOLUME_ID)) {
                    volumeID = parser.getElementText();
                    volumeID = pairtree.uncleanId(volumeID);
                } else if (attributeValue.equals(VOLUME_OCR)) {
                    vector = createVector(parser);
                    break;
                }
            }
        }
    }

    NamedVector tv = new NamedVector(vector, volumeID);
    return tv;
}

From source file:di.uniba.it.tee2.wiki.WikipediaDumpIterator.java

@Override
public WikiPage next() {
    WikiPage page = new WikiPage();
    try {/* w w  w.j  av a  2  s. c o m*/
        StringBuilder wikimediaText = new StringBuilder();
        StringBuilder title = new StringBuilder();
        int wikiID = -1;
        int revisionID = -1;
        boolean finishedParsingArticle = false;
        boolean inrevision = false;
        char lastElement = 'n';
        while (!finishedParsingArticle && xmlStreamReader.hasNext()) {
            int eventCode = xmlStreamReader.next();
            switch (eventCode) {
            case XMLStreamConstants.START_ELEMENT:
                switch (xmlStreamReader.getLocalName()) {
                case "title":
                    lastElement = 't';
                    break;
                case "text":
                    lastElement = 'c';
                    break;
                case "revision":
                    inrevision = true;
                    break;
                case "id":
                    lastElement = 'd';
                    break;
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                switch (xmlStreamReader.getLocalName()) {
                case "page":
                    finishedParsingArticle = true;
                    break;
                case "title":
                    lastElement = 'n';
                    break;
                case "text":
                    lastElement = 'n';
                    break;
                case "id":
                    lastElement = 'n';
                    break;
                case "revision":
                    inrevision = false;
                    break;
                }
                break;
            case XMLStreamConstants.CHARACTERS:
                if (lastElement == 't') {
                    title.append(xmlStreamReader.getText());
                } else if (lastElement == 'c') {
                    wikimediaText.append(xmlStreamReader.getText());
                } else if (lastElement == 'd') {
                    if (inrevision && revisionID == -1) {
                        revisionID = Integer.parseInt(xmlStreamReader.getText());
                    } else if (wikiID == -1) {
                        wikiID = Integer.parseInt(xmlStreamReader.getText());
                    }
                }
                break;
            }
        }

        page.setWikiID(wikiID);
        page.setRevisionID(revisionID);
        page.setTitle(title.toString());
        try {
            ParsedPage parsedPage = parser.parse(wikimediaText.toString());
            page.setParsedPage(parsedPage);
        } catch (Exception ex) {
            Logger.getLogger(WikipediaDumpIterator.class.getName()).log(Level.WARNING,
                    "Error to parse page: " + page.getTitle(), ex);
        }
    } catch (XMLStreamException ex) {
        Logger.getLogger(WikipediaDumpIterator.class.getName()).log(Level.WARNING, "Error reading XML stream",
                ex);
    }
    return page;
}