View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.configuration2.web;
19  
20  import java.util.ArrayList;
21  import java.util.Collection;
22  import java.util.Iterator;
23  import java.util.List;
24  import java.util.Map;
25  
26  import javax.servlet.ServletRequest;
27  
28  /**
29   * A configuration wrapper to read the parameters of a servlet request. This configuration is read only, adding or
30   * removing a property will throw an UnsupportedOperationException.
31   *
32   * @since 1.1
33   */
34  public class ServletRequestConfiguration extends BaseWebConfiguration {
35      /** Stores the wrapped request. */
36      protected ServletRequest request;
37  
38      /**
39       * Create a ServletRequestConfiguration using the request parameters.
40       *
41       * @param request the servlet request
42       */
43      public ServletRequestConfiguration(final ServletRequest request) {
44          this.request = request;
45      }
46  
47      @Override
48      protected Object getPropertyInternal(final String key) {
49          final String[] values = request.getParameterValues(key);
50  
51          if (values == null || values.length == 0) {
52              return null;
53          }
54          if (values.length == 1) {
55              return handleDelimiters(values[0]);
56          }
57          // ensure that escape characters in all list elements are removed
58          final List<Object> result = new ArrayList<>(values.length);
59          for (final String value : values) {
60              final Object val = handleDelimiters(value);
61              if (val instanceof Collection) {
62                  result.addAll((Collection<?>) val);
63              } else {
64                  result.add(val);
65              }
66          }
67          return result;
68      }
69  
70      @Override
71      protected Iterator<String> getKeysInternal() {
72          // According to the documentation of getParameterMap(), keys are Strings.
73          final Map<String, ?> parameterMap = request.getParameterMap();
74          return parameterMap.keySet().iterator();
75      }
76  }