<commit_before>/*
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package dk.statsbiblioteket.util.xml;

import dk.statsbiblioteket.util.MutablePair;
import dk.statsbiblioteket.util.Strings;
import dk.statsbiblioteket.util.reader.CharSequenceReader;

import javax.xml.stream.*;
import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Helper class for stream oriented processing of XML.
 */
public class XMLStepper {
    /**
     * Iterates through the start tags in the stream until the current sub tree in the DOM is depleted
     * Leaves the cursor after END_ELEMENT.
     * @param xml the stream to iterate.
     * @param callback called for each start element.
     */
    public static void iterateTags(XMLStreamReader xml, Callback callback) throws XMLStreamException {
        List<String> tagStack = new ArrayList<String>(10);
        while (true) {
            if (xml.getEventType() == XMLStreamReader.START_ELEMENT) {
                String currentTag = xml.getLocalName();
                tagStack.add(currentTag);
                if (!callback.elementStart(xml, tagStack, currentTag)) {
                    xml.next();
                }
                continue;
            }
            if (xml.getEventType() == XMLStreamReader.END_ELEMENT) {
                String currentTag = xml.getLocalName();
                if (tagStack.isEmpty()) {
                    callback.end();
                    return;
                }
                if (!currentTag.equals(tagStack.get(tagStack.size()-1))) {
                    throw new IllegalStateException(String.format(
                            "Encountered end tag '%s' where '%s' from the stack %s were expected",
                            currentTag, tagStack.get(tagStack.size()-1), Strings.join(tagStack, ", ")));
                }
                callback.elementEnd(tagStack.remove(tagStack.size()-1));
            } else if (xml.getEventType() == XMLStreamReader.END_DOCUMENT) {
                callback.end();
                return;
            }
            xml.next();
        }
    }<commit_msg>Added lenient option to XMLStepper<commit_after>/*
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package dk.statsbiblioteket.util.xml;

import dk.statsbiblioteket.util.MutablePair;
import dk.statsbiblioteket.util.Strings;
import dk.statsbiblioteket.util.reader.CharSequenceReader;

import javax.xml.stream.*;
import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Helper class for stream oriented processing of XML.
 */
public class XMLStepper {
    /**
     * Iterates through the start tags in the stream until the current sub tree in the DOM is depleted
     * Leaves the cursor after END_ELEMENT.
     * @param xml the stream to iterate.
     * @param callback called for each start element.
     */
    public static void iterateTags(XMLStreamReader xml, Callback callback) throws XMLStreamException {
        iterateTags(xml, false, callback);
    }

    /**
     * Iterates through the start tags in the stream until the current sub tree in the DOM is depleted
     * Leaves the cursor after END_ELEMENT.
     * @param xml the stream to iterate.
     * @param lenient if true, the iterator tries to compensate for element-exceeding advances in the XML stream by the callback.
     * @param callback called for each start element.
     */
    public static void iterateTags(XMLStreamReader xml, boolean lenient, Callback callback) throws XMLStreamException {
        List<String> tagStack = new ArrayList<String>(10);
        while (true) {
            if (xml.getEventType() == XMLStreamReader.START_ELEMENT) {
                String currentTag = xml.getLocalName();
                tagStack.add(currentTag);
                if (!callback.elementStart(xml, tagStack, currentTag)) {
                    xml.next();
                }
                continue;
            }
            if (xml.getEventType() == XMLStreamReader.END_ELEMENT) {
                String currentTag = xml.getLocalName();
                if (tagStack.isEmpty()) {
                    callback.end();
                    return;
                }
                if (!currentTag.equals(tagStack.get(tagStack.size()-1))) {
                    boolean fail = true;
                    if (lenient) {
                        fail = !reduceStack(tagStack, currentTag);
                    }
                    if (fail) {
                        throw new IllegalStateException(String.format(
                                "Encountered end tag '%s' where '%s' from the stack %s were expected",
                                currentTag, tagStack.get(tagStack.size() - 1), Strings.join(tagStack, ", ")));
                    }
                }
                callback.elementEnd(tagStack.remove(tagStack.size() - 1));
            } else if (xml.getEventType() == XMLStreamReader.END_DOCUMENT) {
                callback.end();
                return;
            }
            xml.next();
        }
    }

   /**
     * Reduce the stack from the end until the last element is equal to tag.
     * @param stack a stack of tags.
     * @param tag    the tag to reduce to
     * @return true if it was possible to reduce the stack.
     */
    private static boolean reduceStack(List<String> stack, String tag) {
        for (int i = 0 ; i < stack.size() ; i++) {
            if (stack.get(i).equals(tag)) {
                // Found a match, so we know we can reduce
                while (!tag.equals(stack.get(stack.size()-1))) {
                   stack.remove(stack.size()-1);
                }
                return true;
            }
        }
        return false;  // TODO: Implement this
    }
{'fraction_non_alphanumeric': 0.09286850860697238, 'fraction_numerical': 0.0030377549544336755, 'mean_word_length': 2.048500881834215, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 27}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2017034', 'n_tokens_mistral': 1846, 'n_tokens_neox': 1777, 'n_words': 581}