001    //$HeadURL: svn+ssh://rbezema@svn.wald.intevation.org/deegree/base/tags/2.1/src/org/deegree/enterprise/control/ApplicationHandler.java $
002    /*----------------    FILE HEADER  ------------------------------------------
003    
004     This file is part of deegree.
005     Copyright (C) 2001-2006 by:
006     EXSE, Department of Geography, University of Bonn
007     http://www.giub.uni-bonn.de/deegree/
008     lat/lon GmbH
009     http://www.lat-lon.de
010    
011     This library is free software; you can redistribute it and/or
012     modify it under the terms of the GNU Lesser General Public
013     License as published by the Free Software Foundation; either
014     version 2.1 of the License, or (at your option) any later version.
015    
016     This library is distributed in the hope that it will be useful,
017     but WITHOUT ANY WARRANTY; without even the implied warranty of
018     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
019     Lesser General Public License for more details.
020    
021     You should have received a copy of the GNU Lesser General Public
022     License along with this library; if not, write to the Free Software
023     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
024    
025     Contact:
026    
027     Andreas Poth
028     lat/lon GmbH
029     Aennchenstr. 19
030     53177 Bonn
031     Germany
032     E-Mail: poth@lat-lon.de
033    
034     Prof. Dr. Klaus Greve
035     Department of Geography
036     University of Bonn
037     Meckenheimer Allee 166
038     53115 Bonn
039     Germany
040     E-Mail: greve@giub.uni-bonn.de
041    
042     
043     ---------------------------------------------------------------------------*/
044    package org.deegree.enterprise.control;
045    
046    import java.io.BufferedReader;
047    import java.io.File;
048    import java.io.IOException;
049    import java.io.InputStreamReader;
050    import java.io.Reader;
051    import java.io.StringReader;
052    import java.net.MalformedURLException;
053    import java.net.URL;
054    import java.net.URLDecoder;
055    import java.util.ArrayList;
056    import java.util.HashMap;
057    import java.util.List;
058    
059    import javax.servlet.ServletRequest;
060    import javax.servlet.http.HttpServletRequest;
061    
062    import org.deegree.datatypes.parameter.GeneralOperationParameterIm;
063    import org.deegree.datatypes.parameter.ParameterValueIm;
064    import org.deegree.framework.log.ILogger;
065    import org.deegree.framework.log.LoggerFactory;
066    import org.deegree.framework.util.CharsetUtils;
067    import org.deegree.framework.xml.NamespaceContext;
068    import org.deegree.framework.xml.XMLParsingException;
069    import org.deegree.framework.xml.XMLTools;
070    import org.deegree.ogcbase.CommonNamespaces;
071    import org.w3c.dom.Document;
072    import org.w3c.dom.Element;
073    import org.w3c.dom.Node;
074    import org.w3c.dom.NodeList;
075    import org.xml.sax.SAXException;
076    
077    /**
078     * Handler for all web events.
079     * 
080     * @author <a href="mailto:tfriebe@gmx.net">Torsten Friebe</a>
081     * @author <a href="mailto:poth@lat-lon.de">Andreas Poth</a>
082     * 
083     * @version $Revision: 7335 $
084     * 
085     */
086    public class ApplicationHandler implements WebListener {
087    
088        private static final ILogger LOG = LoggerFactory.getLogger( ApplicationHandler.class );
089    
090        private static final HashMap<String, Class> handler = new HashMap<String, Class>();
091    
092        private static final HashMap<String, String> handlerNext = new HashMap<String, String>();
093    
094        private static final HashMap<String, String> handlerANext = new HashMap<String, String>();
095    
096        private static final HashMap<String, List<ParameterValueIm>> handlerParam = new HashMap<String, List<ParameterValueIm>>();
097    
098        private static final String EVENT = "event";
099    
100        private static final String NAME = "name";
101    
102        private static final String CLASS = "class";
103    
104        private static final String NEXT = "next";
105    
106        private static final String ALTERNATIVENEXT = "alternativeNext";
107    
108        /**
109         * Creates a new ApplicationHandler object.
110         * 
111         * @param configFile
112         * @throws Exception
113         */
114        public ApplicationHandler( String configFile ) throws Exception {
115            ApplicationHandler.initHandler( configFile );
116        }
117    
118        /**
119         * Handles all web action events. Calls the specified listener using the mapping defined in
120         * control.xml file.
121         * 
122         * @param e
123         *            the action event generated out of the incoming http POST event.
124         */
125        public void actionPerformed( FormEvent e ) {
126            Object source = e.getSource();
127    
128            if ( source instanceof HttpServletRequest ) {
129                HttpServletRequest request = (HttpServletRequest) source;
130    
131                String actionName = request.getParameter( "action" );
132                LOG.logDebug( "Actionname: " + actionName );
133                if ( actionName != null ) {
134                    // handle simple KVP encoded request
135                    try {
136                        if ( "version".equalsIgnoreCase( actionName ) ) {
137                            this.showVersion( request );
138                        } else {
139                            try {
140                                this.delegateToHelper( actionName, e );
141                            } catch ( Exception ex ) {
142                                ex.printStackTrace();
143                                LOG.logError( "Action " + actionName + " is unknown!" );
144                            }
145                        }
146                    } catch ( Exception ex ) {
147                        request.setAttribute( "next", "error.jsp" );
148                        request.setAttribute( "javax.servlet.jsp.jspException", ex );
149                    }
150                } else {
151                    // handle RPC encoded request
152                    try {
153                        RPCMethodCall mc = getMethodCall( request );
154                        e = new RPCWebEvent( e, mc );
155                        this.delegateToHelper( mc.getMethodName(), e );
156                    } catch ( RPCException re ) {
157                        re.printStackTrace();
158                        request.setAttribute( "next", "error.jsp" );
159                        request.setAttribute( "javax.servlet.jsp.jspException", re );
160                    } catch ( Exception ee ) {
161                        ee.printStackTrace();
162                        request.setAttribute( "next", "error.jsp" );
163                        request.setAttribute( "javax.servlet.jsp.jspException", ee );
164                    }
165                }
166            }
167        }
168    
169        /**
170         * extracts the RPC method call from the
171         * 
172         * @param request
173         * @return the RPCMethodCall
174         * @throws RPCException
175         */
176        private RPCMethodCall getMethodCall( ServletRequest request )
177                                throws RPCException {
178    
179            String s = request.getParameter( "rpc" );
180    
181            try {
182                if ( s == null ) {
183                    StringBuffer sb = new StringBuffer( 1000 );
184                    try {
185                        BufferedReader br = request.getReader();
186                        String line = null;
187                        while ( ( line = br.readLine() ) != null ) {
188                            sb.append( line );
189                        }
190                        br.close();
191                    } catch ( Exception e ) {
192                        throw new RPCException( "Error reading stream from servlet\n" + e.toString() );
193                    }
194    
195                    s = sb.toString();
196                    LOG.logDebug( "found first (perhaps double) encoded String: " +  s );                
197                    s = URLDecoder.decode( s, CharsetUtils.getSystemCharset() );
198                    String[] splitter = s.split( " \t<>" );
199                    if( splitter.length == 1 ){
200                            s = URLDecoder.decode( s, CharsetUtils.getSystemCharset() );
201                            LOG.logDebug( "Decoding a second time: " +  s );
202                    }
203                    
204                    int pos1 = s.indexOf( "<methodCall>" );
205                    int pos2 = s.indexOf( "</methodCall>" );
206                    if ( pos1 < 0 ) {
207                        throw new RPCException( "request doesn't contain a RPC methodCall" );
208                    }
209                    s = s.substring( pos1, pos2 + 13 );
210                } else {
211                    s = URLDecoder.decode( s, CharsetUtils.getSystemCharset() );
212                }
213            } catch ( Exception e ) {
214                e.printStackTrace();
215                throw new RPCException( e.toString() );
216            }
217    
218            StringReader reader = new StringReader( s );
219            RPCMethodCall mc = RPCFactory.createRPCMethodCall( reader );
220    
221            return mc;
222        }
223    
224        /**
225         * 
226         * 
227         * @param action
228         * @param e
229         * 
230         * @throws Exception
231         */
232        protected void delegateToHelper( String action, FormEvent e )
233                                throws Exception {
234            action = action.trim();
235            Class cls = ApplicationHandler.handler.get( action );
236            AbstractListener helper = (AbstractListener) cls.newInstance();
237            helper.setNextPage( handlerNext.get( action ) );
238            helper.setDefaultNextPage( handlerNext.get( action ) );
239            helper.setAlternativeNextPage( handlerANext.get( action ) );
240            helper.setInitParameterList( handlerParam.get( action ) );
241            helper.handle( e );
242        }
243    
244        /**
245         * 
246         * 
247         * @param request
248         */
249        protected void showVersion( ServletRequest request ) {
250            request.setAttribute( "next", "snoopy.jsp" );
251        }
252    
253        /**
254         * 
255         * 
256         * @param configFile
257         * 
258         * @throws IOException
259         * @throws MalformedURLException
260         * @throws SAXException
261         */
262        private static void initHandler( String configFile )
263                                throws IOException, MalformedURLException, SAXException {
264            LOG.logInfo( "Reading event handler configuration file:" + configFile );
265            /*
266             * Read resource into Document...
267             */
268            URL url = new File( configFile ).toURL();
269            Reader reader = new InputStreamReader( url.openStream() );
270            Document doc = XMLTools.parse( reader );
271            /*
272             * Read and create page elements
273             */
274            NodeList nodes = doc.getElementsByTagName( EVENT );
275    
276            for ( int i = 0; i < nodes.getLength(); i++ ) {
277                String name = XMLTools.getAttrValue( nodes.item( i ), null, NAME, null );
278                String cls = XMLTools.getAttrValue( nodes.item( i ), null, CLASS, null );
279                String nextPage = XMLTools.getAttrValue( nodes.item( i ), null, NEXT, null );
280                String anextPage = XMLTools.getAttrValue( nodes.item( i ), null, ALTERNATIVENEXT, null );
281    
282                if ( anextPage == null ) {
283                    anextPage = nextPage;
284                }
285    
286                Class clscls = null;
287                try {
288                    clscls = Class.forName( cls );
289                    handler.put( name.trim(), clscls );
290                    handlerNext.put( name.trim(), nextPage );
291                    handlerANext.put( name.trim(), anextPage );
292                    List<ParameterValueIm> pvList = parseParameters( nodes.item( i ) );
293                    handlerParam.put( name.trim(), pvList );
294                    LOG.logInfo( "Handler '" + clscls + "' bound to event '" + name + "'" );
295                } catch ( Exception ex ) {
296                    ex.printStackTrace();
297                    LOG.logError( "No handler '" + cls + "' specified for event '" + name + "'", ex );
298                    throw new SAXException( "No handler class specified for event:" + name + " " + cls + "\n" + ex );
299                }
300            }
301        }
302    
303        /**
304         * several parameters can be passed to each Listener by adding
305         * 
306         * <pre>
307         *   &lt;parameter&gt;
308         *       &lt;name&gt;aName&lt;/name&gt;
309         *       &lt;value&gt;aValue&lt;/value&gt;
310         *   &lt;/parameter&gt;
311         * </pre>
312         * 
313         * sections to the corresponding &lt;event&gt; element.
314         * 
315         * @param node
316         * @return
317         * @throws XMLParsingException
318         */
319        private static List<ParameterValueIm> parseParameters( Node node )
320                                throws XMLParsingException {
321    
322            NamespaceContext nsc = CommonNamespaces.getNamespaceContext();
323            List nodes = XMLTools.getNodes( node, "parameter", nsc );
324            List<ParameterValueIm> pvs = new ArrayList<ParameterValueIm>();
325            for ( int i = 0; i < nodes.size(); i++ ) {
326                Element element = (Element) nodes.get( i );
327                String name = XMLTools.getRequiredNodeAsString( element, "name", nsc );
328                String value = XMLTools.getRequiredNodeAsString( element, "value", nsc );
329                GeneralOperationParameterIm descriptor = new GeneralOperationParameterIm( name, null, 1, 1 );
330                pvs.add( new ParameterValueIm( descriptor, value ) );
331            }
332    
333            return pvs;
334        }
335    
336    }