<commit_before>/*
 * Copyright 2004-2005 The Apache Software Foundation or its licensors,
 *                     as applicable.
 *
 * 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 org.apache.jackrabbit.core.xml;

import org.apache.jackrabbit.core.BaseException;
import org.apache.jackrabbit.core.Constants;
import org.apache.jackrabbit.core.IllegalNameException;
import org.apache.jackrabbit.core.NamespaceResolver;
import org.apache.jackrabbit.core.QName;
import org.apache.jackrabbit.core.UnknownPrefixException;
import org.apache.jackrabbit.core.util.Base64;
import org.apache.jackrabbit.core.util.ValueHelper;
import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.jcr.BinaryValue;
import javax.jcr.InvalidSerializedDataException;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.Value;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Stack;

/**
 * <code>SysViewImportHandler</code>  ...
 */
class SysViewImportHandler extends DefaultHandler implements Constants {

    private static Logger log = Logger.getLogger(SysViewImportHandler.class);

    private final Importer importer;
    private final NamespaceResolver nsContext;

    /**
     * stack of ImportState instances; an instance is pushed onto the stack
     * in the startElement method every time a sv:node element is encountered;
     * the same instance is popped from the stack in the endElement method
     * when the corresponding sv:node element is encountered.
     */
    private final Stack stack = new Stack();

    /**
     * fields used temporarily while processing sv:property and sv:value elements
     */
    private QName currentPropName;
    private int currentPropType = PropertyType.UNDEFINED;
    private ArrayList currentPropValues = new ArrayList();
    private StringBuffer currentPropValue;

    SysViewImportHandler(Importer importer, NamespaceResolver nsContext) {
        this.importer = importer;
        this.nsContext = nsContext;
    }

    private void processNode(ImportState state, boolean start, boolean end)
            throws SAXException {
        if (!start && !end) {
            return;
        }
        Importer.NodeInfo node = new Importer.NodeInfo();
        node.setName(state.nodeName);
        node.setNodeTypeName(state.nodeTypeName);
        if (state.mixinNames != null) {
            QName[] mixins = (QName[]) state.mixinNames.toArray(new QName[state.mixinNames.size()]);
            node.setMixinNames(mixins);
        }
        node.setUUID(state.uuid);
        // call Importer
        try {
            if (start) {
                importer.startNode(node, state.props, nsContext);
            }
            if (end) {
                importer.endNode(node);
            }
        } catch (RepositoryException re) {
            throw new SAXException(re);
        }
    }

    //-------------------------------------------------------< ContentHandler >
    /**
     * @see ContentHandler#startDocument()
     */
    public void startDocument() throws SAXException {
        try {
            importer.start();
        } catch (RepositoryException re) {
            throw new SAXException(re);
        }
    }

    /**
     * @see ContentHandler#startElement(String, String, String, Attributes)
     */
    public void startElement(String namespaceURI, String localName,
                             String qName, Attributes atts)
            throws SAXException {
        String elemName;
        String nsURI;
        if (namespaceURI != null && !"".equals(namespaceURI)) {
            nsURI = namespaceURI;
            elemName = localName;
        } else {
            try {
                nsURI = QName.fromJCRName(qName, nsContext).getNamespaceURI();
                elemName = QName.fromJCRName(qName, nsContext).getLocalName();
            } catch (BaseException e) {
                // should never happen...
                String msg = "internal error: failed to parse/resolve element name " + qName;
                log.debug(msg);
                throw new SAXException(msg, e);
            }
        }
        // check namespace
        if (!NS_SV_URI.equals(nsURI)) {
            throw new SAXException(new InvalidSerializedDataException("invalid namespace for element in system view xml document: " + nsURI));
        }
        // check element name
        if (SysViewSAXEventGenerator.NODE_ELEMENT.equals(elemName)) {
            // sv:node element

            // node name (value of sv:name attribute)
            String name = atts.getValue(SysViewSAXEventGenerator.NS_SV_URI, SysViewSAXEventGenerator.NAME_ATTRIBUTE);
            if (name == null) {
                // try qualified name
                name = atts.getValue(SysViewSAXEventGenerator.NS_SV_PREFIX + ":" + SysViewSAXEventGenerator.NAME_ATTRIBUTE);
            }
            if (name == null) {
                throw new SAXException(new InvalidSerializedDataException("missing mandatory sv:name attributeof element sv:node"));
            }

            if (!stack.isEmpty()) {
                // process current node first
                ImportState current = (ImportState) stack.peek();
                // need to start current node
                processNode(current, true, false);
                current.started = true;
            }

            // push new ImportState instance onto the stack
            ImportState state = new ImportState();
            try {
                state.nodeName = QName.fromJCRName(name, nsContext);
            } catch (IllegalNameException ine) {
                throw new SAXException(new InvalidSerializedDataException("illegal node name: " + name, ine));
            } catch (UnknownPrefixException upe) {
                throw new SAXException(new InvalidSerializedDataException("illegal node name: " + name, upe));
            }
            stack.push(state);
        } else if (SysViewSAXEventGenerator.PROPERTY_ELEMENT.equals(elemName)) {
            // sv:property element

            // reset temp fields
            currentPropValues.clear();

            // property name (value of sv:name attribute)
            String name = atts.getValue(SysViewSAXEventGenerator.NS_SV_URI, SysViewSAXEventGenerator.NAME_ATTRIBUTE);
            if (name == null) {
                // try qualified name
                name = atts.getValue(SysViewSAXEventGenerator.NS_SV_PREFIX + ":" + SysViewSAXEventGenerator.NAME_ATTRIBUTE);
            }
            if (name == null) {
                throw new SAXException(new InvalidSerializedDataException("missing mandatory sv:name attributeof element sv:property"));
            }
            try {
                currentPropName = QName.fromJCRName(name, nsContext);
            } catch (IllegalNameException ine) {<commit_msg>reimplementing Session.importXML & friends due to spec changes<commit_after>/*
 * Copyright 2004-2005 The Apache Software Foundation or its licensors,
 *                     as applicable.
 *
 * 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 org.apache.jackrabbit.core.xml;

import org.apache.jackrabbit.core.BaseException;
import org.apache.jackrabbit.core.Constants;
import org.apache.jackrabbit.core.IllegalNameException;
import org.apache.jackrabbit.core.NamespaceResolver;
import org.apache.jackrabbit.core.QName;
import org.apache.jackrabbit.core.UnknownPrefixException;
import org.apache.jackrabbit.core.util.Base64;
import org.apache.jackrabbit.core.util.ValueHelper;
import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.jcr.BinaryValue;
import javax.jcr.InvalidSerializedDataException;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.Value;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Stack;

/**
 * <code>SysViewImportHandler</code>  ...
 */
class SysViewImportHandler extends DefaultHandler implements Constants {

    private static Logger log = Logger.getLogger(SysViewImportHandler.class);

    private final Importer importer;
    private final NamespaceResolver nsContext;

    /**
     * stack of ImportState instances; an instance is pushed onto the stack
     * in the startElement method every time a sv:node element is encountered;
     * the same instance is popped from the stack in the endElement method
     * when the corresponding sv:node element is encountered.
     */
    private final Stack stack = new Stack();

    /**
     * fields used temporarily while processing sv:property and sv:value elements
     */
    private QName currentPropName;
    private int currentPropType = PropertyType.UNDEFINED;
    private ArrayList currentPropValues = new ArrayList();
    private StringBuffer currentPropValue;

    SysViewImportHandler(Importer importer, NamespaceResolver nsContext) {
        this.importer = importer;
        this.nsContext = nsContext;
    }

    private void processNode(ImportState state, boolean start, boolean end)
            throws SAXException {
        if (!start && !end) {
            return;
        }
        Importer.NodeInfo node = new Importer.NodeInfo();
        node.setName(state.nodeName);
        node.setNodeTypeName(state.nodeTypeName);
        if (state.mixinNames != null) {
            QName[] mixins = (QName[]) state.mixinNames.toArray(new QName[state.mixinNames.size()]);
            node.setMixinNames(mixins);
        }
        node.setUUID(state.uuid);
        // call Importer
        try {
            if (start) {
                importer.startNode(node, state.props, nsContext);
            }
            if (end) {
                importer.endNode(node);
            }
        } catch (RepositoryException re) {
            throw new SAXException(re);
        }
    }

    //-------------------------------------------------------< ContentHandler >
    /**
     * @see ContentHandler#startDocument()
     */
    public void startDocument() throws SAXException {
        try {
            importer.start();
        } catch (RepositoryException re) {
            throw new SAXException(re);
        }
    }

    /**
     * @see ContentHandler#startElement(String, String, String, Attributes)
     */
    public void startElement(String namespaceURI, String localName,
                             String qName, Attributes atts)
            throws SAXException {
        String elemName;
        String nsURI;
        if (namespaceURI != null && !"".equals(namespaceURI)) {
            nsURI = namespaceURI;
            elemName = localName;
        } else {
            try {
                nsURI = QName.fromJCRName(qName, nsContext).getNamespaceURI();
                elemName = QName.fromJCRName(qName, nsContext).getLocalName();
            } catch (BaseException e) {
                // should never happen...
                String msg = "internal error: failed to parse/resolve element name " + qName;
                log.debug(msg);
                throw new SAXException(msg, e);
            }
        }
        // check namespace
        if (!NS_SV_URI.equals(nsURI)) {
            throw new SAXException(new InvalidSerializedDataException("invalid namespace for element in system view xml document: " + nsURI));
        }
        // check element name
        if (SysViewSAXEventGenerator.NODE_ELEMENT.equals(elemName)) {
            // sv:node element

            // node name (value of sv:name attribute)
            String name = atts.getValue(SysViewSAXEventGenerator.NS_SV_URI, SysViewSAXEventGenerator.NAME_ATTRIBUTE);
            if (name == null) {
                // try qualified name
                name = atts.getValue(SysViewSAXEventGenerator.NS_SV_PREFIX + ":" + SysViewSAXEventGenerator.NAME_ATTRIBUTE);
            }
            if (name == null) {
                throw new SAXException(new InvalidSerializedDataException("missing mandatory sv:name attributeof element sv:node"));
            }

            if (!stack.isEmpty()) {
                // process current node first
                ImportState current = (ImportState) stack.peek();
                // need to start current node
                if (!current.started) {
                    processNode(current, true, false);
                    current.started = true;
                }
            }

            // push new ImportState instance onto the stack
            ImportState state = new ImportState();
            try {
                state.nodeName = QName.fromJCRName(name, nsContext);
            } catch (IllegalNameException ine) {
                throw new SAXException(new InvalidSerializedDataException("illegal node name: " + name, ine));
            } catch (UnknownPrefixException upe) {
                throw new SAXException(new InvalidSerializedDataException("illegal node name: " + name, upe));
            }
            stack.push(state);
        } else if (SysViewSAXEventGenerator.PROPERTY_ELEMENT.equals(elemName)) {
            // sv:property element

            // reset temp fields
            currentPropValues.clear();

            // property name (value of sv:name attribute)
            String name = atts.getValue(SysViewSAXEventGenerator.NS_SV_URI, SysViewSAXEventGenerator.NAME_ATTRIBUTE);
            if (name == null) {
                // try qualified name
                name = atts.getValue(SysViewSAXEventGenerator.NS_SV_PREFIX + ":" + SysViewSAXEventGenerator.NAME_ATTRIBUTE);
            }
            if (name == null) {
                throw new SAXException(new InvalidSerializedDataException("missing mandatory sv:name attributeof element sv:property"));
            }
            try {
                currentPropName = QName.fromJCRName(name, nsContext);
            } catch (IllegalNameException ine) {
{'fraction_non_alphanumeric': 0.09437844295480188, 'fraction_numerical': 0.0019911063914515165, 'mean_word_length': 2.285651984300044, 'pattern_counts': {'":': 4, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 12}, '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': '6960813', 'n_tokens_mistral': 3934, 'n_tokens_neox': 3817, 'n_words': 1040}