/*
 * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (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.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.cms.installer;


import org.xml.sax.helpers.DefaultHandler;

import java.util.Map;

/**
 *
 * SAX event handler class for parsing configuration file.
 *
 * Parse URL-to-Page/Dispatcher/Servlet mappings from a file.
 *
 * Format of the file is XML:
 * <pre>
 * &lt;dispatcher-configuration&gt;
 *   &lt;url-mapping
 *     &lt;url&gt;my-page&lt;/url&gt;
 *     OR &lt;page-class&gt;com.arsdigita.Page.class&lt;/page-class&gt;
 *   &lt;url-mapping
 * &lt;/dispatcher-configuration&gt;
 * </pre>
 */
public class PageClassConfigHandler extends DefaultHandler {

    private Map m_map;
    private Map m_rmap;
    private StringBuffer m_buffer;
    private String m_url;
    private String m_className;
    
    /** 
     * @param map A map to configure (pages-> classes)
     * @param rmap A map to configure (classes-> pages)
     *
     * @pre md.m_map != null
     */
    public PageClassConfigHandler(Map map, Map rmap) {
        m_map = map;
        // reverse map
        m_rmap = rmap;
        m_buffer = new StringBuffer();
    }

    public void characters(char[] ch, int start, int len) {
        for (int i = 0; i < len; i++) {
            m_buffer.append(ch[start + i]);
        }
    }

    public void endElement(String uri, String localName, String qn) {
        if ( qn.equals("url") ) {
            m_url = m_buffer.toString().trim();
        } else if ( qn.equals("page-class") ) {
            m_className = m_buffer.toString().trim();
        } else if ( qn.equals("url-mapping") ) {
            m_map.put(m_url, m_className);
            m_rmap.put(m_className, m_url);
        }
        m_buffer = new StringBuffer();
    }
}
