001    // $HeadURL: https://svn.wald.intevation.org/svn/deegree/base/branches/2.3_testing/src/org/deegree/framework/util/KVP2Map.java $
002    /*----------------------------------------------------------------------------
003     This file is part of deegree, http://deegree.org/
004     Copyright (C) 2001-2009 by:
005     Department of Geography, University of Bonn
006     and
007     lat/lon GmbH
008    
009     This library is free software; you can redistribute it and/or modify it under
010     the terms of the GNU Lesser General Public License as published by the Free
011     Software Foundation; either version 2.1 of the License, or (at your option)
012     any later version.
013     This library is distributed in the hope that it will be useful, but WITHOUT
014     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
015     FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
016     details.
017     You should have received a copy of the GNU Lesser General Public License
018     along with this library; if not, write to the Free Software Foundation, Inc.,
019     59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
020    
021     Contact information:
022    
023     lat/lon GmbH
024     Aennchenstr. 19, 53177 Bonn
025     Germany
026     http://lat-lon.de/
027    
028     Department of Geography, University of Bonn
029     Prof. Dr. Klaus Greve
030     Postfach 1147, 53001 Bonn
031     Germany
032     http://www.geographie.uni-bonn.de/deegree/
033    
034     e-mail: info@deegree.org
035     ----------------------------------------------------------------------------*/
036    package org.deegree.framework.util;
037    
038    import static java.net.URLDecoder.decode;
039    
040    import java.io.UnsupportedEncodingException;
041    import java.util.Enumeration;
042    import java.util.HashMap;
043    import java.util.Map;
044    import java.util.StringTokenizer;
045    import java.util.TreeMap;
046    
047    import javax.servlet.ServletRequest;
048    import javax.servlet.http.HttpServletRequest;
049    
050    import org.deegree.framework.log.ILogger;
051    import org.deegree.framework.log.LoggerFactory;
052    
053    /**
054     * offeres utility method for transformating a key-value-pair encoded request to a <tt>Map</tt>
055     * 
056     * @version $Revision: 19270 $
057     * @author <a href="mailto:poth@lat-lon.de">Andreas Poth</a>
058     * @author last edited by: $Author: apoth $
059     * 
060     * @version 1.0. $Revision: 19270 $, $Date: 2009-08-20 10:28:52 +0200 (Do, 20. Aug 2009) $
061     * 
062     * @since 2.0
063     */
064    public class KVP2Map {
065    
066        private static final ILogger LOG = LoggerFactory.getLogger( KVP2Map.class );
067    
068        /**
069         * Transforms a String/KVPs like it is used for HTTP-GET request to a Map.
070         * 
071         * TODO: Check if the trim () call may cause side effects. It is currently used to eliminate possible new line
072         * characters at the end of the string, that occured using the <code>GenericClient</code>.
073         * 
074         * @param kvp
075         *            key-value-pair encoded request
076         * @return created Map
077         */
078        public static Map<String, String> toMap( String kvp ) {
079    
080            StringTokenizer st = new StringTokenizer( kvp.trim(), "&?" );
081            HashMap<String, String> map = new HashMap<String, String>();
082    
083            while ( st.hasMoreTokens() ) {
084                String s = st.nextToken();
085                if ( s != null ) {
086                    int pos = s.indexOf( '=' );
087    
088                    if ( pos > -1 ) {
089                        String s1 = s.substring( 0, pos );
090                        String s2 = s.substring( pos + 1, s.length() );
091                        map.put( s1.toUpperCase(), s2 );
092                    }
093                }
094            }
095    
096            return map;
097    
098        }
099    
100        /**
101         * @param iterator
102         *            Enumeration containing KVP encoded parameters
103         * @return created Map
104         */
105        public static Map<String, String> toMap( Enumeration<String> iterator ) {
106            HashMap<String, String> map = new HashMap<String, String>();
107    
108            while ( iterator.hasMoreElements() ) {
109                String s = iterator.nextElement();
110                if ( s != null ) {
111                    int pos = s.indexOf( '=' );
112    
113                    if ( pos > -1 ) {
114                        String s1 = s.substring( 0, pos );
115                        String s2 = s.substring( pos + 1, s.length() );
116                        map.put( s1.toUpperCase(), s2 );
117                    }
118                }
119            }
120    
121            return map;
122        }
123    
124        /**
125         * @see #toMap(HttpServletRequest)
126         * @param request
127         * @return a Map which contains kvp's from the given request
128         */
129        public static Map<String, String> toMap( HttpServletRequest request ) {
130            return toMap( (ServletRequest)request );
131        }
132        
133        /**
134         * returns the parameters of a <tt>HttpServletRequest</tt> as <tt>Map</tt>. (HINT: all the keys get changed to upper
135         * case)
136         * 
137         * @param request
138         * @return a Map which contains kvp's from the given request
139         */
140        @SuppressWarnings("unchecked")
141        public static Map<String, String> toMap( ServletRequest request ) {
142            Map<String, String> result = null;
143            // encoding heuristics for URL encoding
144            // if %c3 is found (a sign of UTF-8 encoding) parse it manually, setting the encoding right
145            String queryString = ( (HttpServletRequest) request ).getQueryString();
146            if ( queryString != null && queryString.toLowerCase().indexOf( "%c3" ) != -1 ) {
147                result = new TreeMap<String, String>();
148                try {
149                    for ( String kv : queryString.split( "&" ) ) {
150                        String[] pair = kv.split( "=", 2 );
151                        if ( pair.length == 2 ) {
152                            result.put( decode( pair[0], "UTF-8" ).toUpperCase(), decode( pair[1], "UTF-8" ) );
153                        }
154                    }
155                } catch ( UnsupportedEncodingException e ) {
156                    LOG.logError( "Unknown error", e );
157                }
158            } else {
159                // according to javax.servlet.* documentation, the type is correct
160                Map<String, String[]> map = request.getParameterMap();
161                result = new HashMap<String, String>();
162                for ( String key : map.keySet() ) {
163                    String[] tmp = map.get( key );
164                    for ( int i = 0; i < tmp.length; i++ ) {
165                        tmp[i] = tmp[i].trim();
166                    }
167                    result.put( key.toUpperCase(), StringTools.arrayToString( tmp, ',' ) );
168                }
169    
170            }
171            return result;
172        }
173    
174    }