/** 
 * 
 * Copyright 2004 Protique Ltd
 * 
 * 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.codehaus.activemq.ws.soap;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.util.StreamReaderDelegate;

/**
 * An {@link StreamReaderDelegate} which creates a logical sub-document
 * from a stream until a certain close element is discovered - such as for making
 * the contents of a SOAP body appear as a logical XML document.
 *
 * @version $Revision: 1.1 $
 */
public class SubDocumentXMLStreamFilter extends StreamReaderDelegate implements XMLStreamConstants {
    boolean first = true;
    boolean finished = false;
    private final QName name;

    public SubDocumentXMLStreamFilter(QName name, XMLStreamReader in) {
        super(in);
        this.name = name;
    }

    public boolean hasNext() throws XMLStreamException {
        if (first) {
            return true;
        }
        else if (finished) {
            return false;
        }
        return super.hasNext();
    }

    public int next() throws XMLStreamException {
        if (first) {
            first = false;
            return START_DOCUMENT;
        }
        else {
            int answer = super.next();
            if (answer == END_ELEMENT && name.equals(getName())) {
                finished = true;
                return END_DOCUMENT;
            }
            return answer;
        }
    }

    public int nextTag() throws XMLStreamException {
        int eventType = next();
        while ((eventType == CHARACTERS && isWhiteSpace()) // skip whitespace
                || (eventType == CDATA && isWhiteSpace())
                // skip whitespace
                || eventType == SPACE
                || eventType == PROCESSING_INSTRUCTION
                || eventType == COMMENT
                ) {
            eventType = next();
        }
        if (eventType != START_ELEMENT && eventType != END_ELEMENT) {
            throw new XMLStreamException("expected start or end tag", getLocation());
        }
        return eventType;
    }

    public int getEventType() {
        if (first) {
            return START_DOCUMENT;
        }
        else if (finished) {
            return END_DOCUMENT;
        }
        return super.getEventType();
    }
}

