/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000-2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *     "Apache Jetspeed" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache" or
 *    "Apache Jetspeed", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

package org.apache.jetspeed.portal.portlets;

//Element Construction Set
import org.apache.ecs.*;

//Jetspeed stuff
import org.apache.jetspeed.portal.*;
import org.apache.jetspeed.util.*;
import org.apache.jetspeed.cache.disk.*;


//turbine
import org.apache.turbine.util.*;

//standard java stuff
import java.io.*;

import org.xml.sax.*;
import org.xml.sax.helpers.ParserFactory;

/**
 * This portlet serves well-formed WML file content and strips
 * them of superfluous tags liks <wml>
 *
 * <strong>The strip capability has been temporarily disabled due to
 * class conflicts in Tomcat 3.2, so this portlet can only currently
 * serve fragments of WML documents, without the <wml> tag</strong>
 *
 * @author <a href="mailto:raphael@apache.org">Raphaël Luta</a>
 * @version $Id: WMLFilePortlet.java,v 1.8 2003/03/04 00:05:05 sgala Exp $ 
 */
public class WMLFilePortlet extends FileWatchPortlet {

    private ConcreteElement content = new StringElement("Not available");
    
    /**
      * @see Portlet#supportsType
      */
    public boolean supportsType( MimeType type ) {
        return type.equals(MimeType.WML);
    }
 
    /** Initialize the content of the portlet
    */
    public void init() throws PortletException {

        PortletConfig config = this.getPortletConfig();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
 
        try {
            // RL: disable the SAX filter due to a class path problem
            // with Tomcat 3.2
            /*
            String url = JetspeedDiskCache.getInstance().getEntry( config.getURL() ).getURL();

            WMLFilter myFilter = new WMLFilter(new PrintWriter(bos));
            myFilter.filter(url);
            content = new JetspeedClearElement( bos.toString() );
            */
            content = new JetspeedClearElement(
                JetspeedDiskCache.getInstance().getEntry( config.getURL() ).getData() );
        } catch (Exception e) {
            throw new PortletException( e.getMessage() );
        } finally {
            try {
                bos.close();
            } catch (IOException e) {}
        }
    }

    public ConcreteElement getContent( RunData data ) {
        return content;
    }
    
    class WMLFilter extends HandlerBase {
    
        private static final String DEFAULT_PARSER_NAME = "javax.xml.parsers.SAXParser";

        protected PrintWriter out=new PrintWriter(System.out);

        public WMLFilter(PrintWriter outPW) throws UnsupportedEncodingException {
            this.out=outPW;
        }

        public void filter(String uri) {

            try {
                HandlerBase handler = this;
    
                Parser parser = ParserFactory.makeParser(DEFAULT_PARSER_NAME);
                parser.setDocumentHandler(handler);
                parser.setErrorHandler(handler);
                parser.parse(uri);
            }
            catch (Exception e) {
                Log.error( e );
            }
        }

        public void processingInstruction(String target, String data) {        
            //filter all PIs
        }

        public void startElement(String name, AttributeList attrs) {

            // strip <wml>
            if (name.equals("wml")) return;

            // else output the element        
            out.print('<');
            out.print(name);
            if (attrs != null) {
                int len = attrs.getLength();
                for (int i = 0; i < len; i++) {
                    out.print(' ');
                    out.print(attrs.getName(i));
                    out.print("=\"");
                    out.print(normalize(attrs.getValue(i)));
                    out.print('"');
                }
            }
            out.print('>');    
        }

        public void characters(char ch[], int start, int length) {
            out.print(normalize(new String(ch, start, length)));
        }

        public void ignorableWhitespace(char ch[], int start, int length) {
            characters(ch, start, length);
        }

        public void endElement(String name) {
            //filter <wml>
            if (name.equals("wml")) return;
            
            // outpu anything else
            out.print("</");
            out.print(name);
            out.print('>');
        }

        public void endDocument() {
            out.flush();
        }

        public void warning(SAXParseException ex) {
            Log.info(getLocationString(ex)+": "+ex.getMessage());
        }

        public void error(SAXParseException ex) {
            Log.error(getLocationString(ex)+": "+ex,ex);
        }

        public void fatalError(SAXParseException ex) throws SAXException {
            Log.error(getLocationString(ex)+": "+ex,ex);
            throw ex;
        }

        /**
        Retrieves the error location in the input stream
        */
        private String getLocationString(SAXParseException ex) {
            StringBuffer str = new StringBuffer();
    
            String systemId = ex.getSystemId();
            if (systemId != null) {
                int index = systemId.lastIndexOf('/');
                if (index != -1)
                    systemId = systemId.substring(index + 1);
                str.append(systemId);
            }
            str.append(':');
            str.append(ex.getLineNumber());
            str.append(':');
            str.append(ex.getColumnNumber());
    
            return str.toString();
    
        }

        /**
        Escapes characters data
        */
        protected String normalize(String s) {
            StringBuffer str = new StringBuffer();
    
            int len = (s != null) ? s.length() : 0;
            for (int i = 0; i < len; i++) {
                char ch = s.charAt(i);
                switch (ch) {
                    case '<': {
                        str.append("&lt;");
                        break;
                    }
                    case '>': {
                        str.append("&gt;");
                        break;
                    }
                    case '&': {
                        str.append("&amp;");
                        break;
                    }
                    case '"': {
                        str.append("&quot;");
                        break;
                    }
                    default: {
                        str.append(ch);
                    }
                }
            }

            return str.toString();

        }
    }
}
