/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2011 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id: NamespaceFilter.java 21943 2011-11-30 16:44:28Z sauthieg $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.datasource.deployer.reader;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.XMLFilterImpl;

/**
 * Allows to filter a given namespace
 * @author benoitf
 */
public class NamespaceFilter extends XMLFilterImpl {

    private String usedNamespaceUri;

    // State variable
    private boolean addedNamespace = false;

    public NamespaceFilter(final String namespaceUri) {
        super();
        this.usedNamespaceUri = namespaceUri;
    }

    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        startControlledPrefixMapping();
    }

    @Override
    public void startElement(final String arg0, final String arg1, final String arg2, final Attributes arg3)
            throws SAXException {
        super.startElement(this.usedNamespaceUri, arg1, arg2, arg3);
    }

    @Override
    public void endElement(final String arg0, final String arg1, final String arg2) throws SAXException {
        super.endElement(this.usedNamespaceUri, arg1, arg2);
    }

    @Override
    public void startPrefixMapping(final String prefix, final String url) throws SAXException {
        this.startControlledPrefixMapping();
    }

    private void startControlledPrefixMapping() throws SAXException {

        if (!this.addedNamespace) {
            // We should add namespace since it is set and has not yet been
            // done.
            super.startPrefixMapping("", this.usedNamespaceUri);

            // Make sure we dont do it twice
            this.addedNamespace = true;
        }
    }

}
