<commit_before>/**
 * Copyright (c) 2010, Distributed Systems Group, University of Konstanz
 * 
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 * 
 * THE SOFTWARE IS PROVIDED AS IS AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 * 
 */
package com.treetank.service.xml.serialize;

import java.io.IOException;
import java.util.Iterator;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Namespace;
import javax.xml.stream.events.XMLEvent;

import com.treetank.api.IAxis;
import com.treetank.api.IReadTransaction;
import com.treetank.axis.DescendantAxis;
import com.treetank.axis.FilterAxis;
import com.treetank.axis.TextFilter;
import com.treetank.exception.TreetankException;
import com.treetank.node.AbsStructNode;
import com.treetank.node.ENodes;
import com.treetank.node.ElementNode;
import com.treetank.utils.FastStack;
import com.treetank.utils.LogWrapper;

import org.slf4j.LoggerFactory;

/**
 * <h1>StAXSerializer</h1>
 * 
 * <p>
 * Provides a StAX implementation (event API) for retrieving a Treetank database.
 * </p>
 * 
 * @author <NAME>, University of Konstanz
 * 
 */
public final class StAXSerializer implements XMLEventReader {

    /**
     * Log wrapper for better output.
     */
    private static final LogWrapper LOGWRAPPER =
        new LogWrapper(LoggerFactory.getLogger(StAXSerializer.class));

    /**
     * Determines if start tags have to be closed, thus if end tags have to be
     * emitted.
     */
    private transient boolean mCloseElements;

    /**
     * {@inheritDoc}.
     */
    private transient XMLEvent mEvent;

    /**
     * XMLEventFactory to create events.
     * 
     * @see XMLEventFactory
     */
    private transient XMLEventFactory mFac = XMLEventFactory.newFactory();

    /** Current node key. */
    private transient long mKey;

    /**
     * Determines if all end tags have been emitted.
     */
    private transient boolean mCloseElementsEmitted;

    /** Determines if nextTag() method has been called. */
    private transient boolean mNextTag;

    /** axis for iteration. */
    private final transient IAxis mAxis;

    /** Stack for reading end element. */
    private final transient FastStack<Long> mStack;

    /**
     * Determines if the cursor has to move back after empty elements (used in
     * getElementText().
     */
    private transient boolean mGoBack;

    /**
     * Determines if the cursor has moved up and therefore has to move back
     * after to the right node (used in getElementText()).
     */
    private transient boolean mGoUp;

    /**
     * Last emitted key (start tags, text... except end tags; used in
     * getElementText()).
     */
    private transient long mLastKey;

    /**
     * Initialize XMLStreamReader implementation with transaction. The cursor
     * points to the node the XMLStreamReader starts to read. Do not serialize
     * the tank ids.
     * 
     * @param axis
     *            input axis
     */
    public StAXSerializer(final IAxis axis) {
        mNextTag = false;
        mAxis = axis;
        mStack = new FastStack<Long>();
    }

    /** 
     * Emit end tag.
     * 
     * @param paramRTX
     *                  Treetank reading transaction {@link IReadTransaction}.
     */
    private void emitEndTag(final IReadTransaction paramRTX) {
        final long nodeKey = paramRTX.getNode().getNodeKey();
        mEvent = mFac.createEndElement(paramRTX.getQNameOfCurrentNode(), new NamespaceIterator(paramRTX));
        paramRTX.moveTo(nodeKey);
    }

    /**
     * Emit a node.
     * 
     * @param paramRTX
     *                  Treetank reading transaction {@link IReadTransaction}.
     */
    private void emitNode(final IReadTransaction paramRTX) {
        switch (paramRTX.getNode().getKind()) {
        case ROOT_KIND:
            mEvent = mFac.createStartDocument();
            break;
        case ELEMENT_KIND:
            final long key = paramRTX.getNode().getNodeKey();
            final QName qName = paramRTX.getQNameOfCurrentNode();
            mEvent =
                mFac.createStartElement(qName, new AttributeIterator(paramRTX), new NamespaceIterator(
                    paramRTX));
            paramRTX.moveTo(key);
            break;
        case TEXT_KIND:
            mEvent = mFac.createCharacters(paramRTX.getValueOfCurrentNode());
            break;
        default:
            throw new IllegalStateException("Kind not known!");
        }
    }

    @Override
    public void close() throws XMLStreamException {
        try {
            mAxis.getTransaction().close();
        } catch (final TreetankException e) {
            LOGWRAPPER.error(e);
        }
    }

    @Override
    public String getElementText() throws XMLStreamException {
        final IReadTransaction rtx = mAxis.getTransaction();<commit_msg>NEW - task 428: Gui Skeleton  https://projects.uni-konstanz.de/issues/show/428<commit_after>/**
 * Copyright (c) 2010, Distributed Systems Group, University of Konstanz
 * 
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 * 
 * THE SOFTWARE IS PROVIDED AS IS AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 * 
 */
package com.treetank.service.xml.serialize;

import java.io.IOException;
import java.util.Iterator;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Namespace;
import javax.xml.stream.events.XMLEvent;

import com.treetank.api.IAxis;
import com.treetank.api.IReadTransaction;
import com.treetank.axis.DescendantAxis;
import com.treetank.axis.FilterAxis;
import com.treetank.axis.TextFilter;
import com.treetank.exception.TreetankException;
import com.treetank.node.AbsStructNode;
import com.treetank.node.ENodes;
import com.treetank.node.ElementNode;
import com.treetank.utils.FastStack;
import com.treetank.utils.LogWrapper;

import org.slf4j.LoggerFactory;

/**
 * <h1>StAXSerializer</h1>
 * 
 * <p>
 * Provides a StAX implementation (event API) for retrieving a Treetank database.
 * </p>
 * 
 * @author <NAME>, University of Konstanz
 * 
 */
public final class StAXSerializer implements XMLEventReader {

    /**
     * Log wrapper for better output.
     */
    private static final LogWrapper LOGWRAPPER =
        new LogWrapper(LoggerFactory.getLogger(StAXSerializer.class));

    /**
     * Determines if start tags have to be closed, thus if end tags have to be
     * emitted.
     */
    private transient boolean mCloseElements;

    /** {@link XMLEvent}. */
    private transient XMLEvent mEvent;

    /** {@link XMLEventFactory} to create events. */
    private transient XMLEventFactory mFac = XMLEventFactory.newFactory();

    /** Current node key. */
    private transient long mKey;

    /** Determines if all end tags have been emitted. */
    private transient boolean mCloseElementsEmitted;

    /** Determines if nextTag() method has been called. */
    private transient boolean mNextTag;

    /** {@link IAxis} for iteration. */
    private final transient IAxis mAxis;

    /** Stack for reading end element. */
    private final transient FastStack<Long> mStack;

    /**
     * Determines if the cursor has to move back after empty elements (used in
     * getElementText().
     */
    private transient boolean mGoBack;

    /**
     * Determines if the cursor has moved up and therefore has to move back
     * after to the right node (used in getElementText()).
     */
    private transient boolean mGoUp;

    /**
     * Last emitted key (start tags, text... except end tags; used in
     * getElementText()).
     */
    private transient long mLastKey;

    /** Determines if {@link IReadTransaction} should be closed afterwards. */
    private transient boolean mCloseRtx;

    /**
     * Initialize XMLStreamReader implementation with transaction. The cursor
     * points to the node the XMLStreamReader starts to read. Do not serialize
     * the tank ids.
     * 
     * @param paramAxis
     *            {@link IAxis} which is used to iterate over and generate StAX events.
     */
    public StAXSerializer(final IAxis paramAxis) {
        this(paramAxis, true);
    }

    /**
     * Initialize XMLStreamReader implementation with transaction. The cursor
     * points to the node the XMLStreamReader starts to read. Do not serialize
     * the tank ids.
     * 
     * @param paramAxis
     *            {@link IAxis} which is used to iterate over and generate StAX events.
     * @param paramCloseRtx
     *            Determines if rtx should be closed afterwards.
     */
    public StAXSerializer(final IAxis paramAxis, final boolean paramCloseRtx) {
        mNextTag = false;
        mAxis = paramAxis;
        mCloseRtx = paramCloseRtx;
        mStack = new FastStack<Long>();
    }

    /**
     * Emit end tag.
     * 
     * @param paramRTX
     *            Treetank reading transaction {@link IReadTransaction}.
     */
    private void emitEndTag(final IReadTransaction paramRTX) {
        final long nodeKey = paramRTX.getNode().getNodeKey();
        mEvent = mFac.createEndElement(paramRTX.getQNameOfCurrentNode(), new NamespaceIterator(paramRTX));
        paramRTX.moveTo(nodeKey);
    }

    /**
     * Emit a node.
     * 
     * @param paramRTX
     *            Treetank reading transaction {@link IReadTransaction}.
     */
    private void emitNode(final IReadTransaction paramRTX) {
        switch (paramRTX.getNode().getKind()) {
        case ROOT_KIND:
            mEvent = mFac.createStartDocument();
            break;
        case ELEMENT_KIND:
            final long key = paramRTX.getNode().getNodeKey();
            final QName qName = paramRTX.getQNameOfCurrentNode();
            mEvent =
                mFac.createStartElement(qName, new AttributeIterator(paramRTX), new NamespaceIterator(
                    paramRTX));
            paramRTX.moveTo(key);
            break;
        case TEXT_KIND:
            mEvent = mFac.createCharacters(paramRTX.getValueOfCurrentNode());
            break;
        default:
            throw new IllegalStateException("Kind not known!");
        }
    }

    @Override
    public void close() throws XMLStreamException {
        if (mCloseRtx) {
            try {
                mAxis.getTransaction().close();
            } catch (final TreetankException e) {
                LOGWRAPPER.error(e);
            }
        }
    }

    @Override
    public String getElementText() throws XMLStreamException {
        final IReadTransaction rtx = mAxis.getTransaction();
{'fraction_non_alphanumeric': 0.08567392388233339, 'fraction_numerical': 0.0016619577862722287, 'mean_word_length': 2.717948717948718, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 18}, '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': '2502235', 'n_tokens_mistral': 3414, 'n_tokens_neox': 3271, 'n_words': 1051}