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 import java.util.Objects;
26
27 import javax.servlet.ServletRequest;
28
29 /**
30 * A configuration wrapper to read the parameters of a servlet request. This configuration is read only, adding or
31 * removing a property will throw an UnsupportedOperationException.
32 *
33 * @since 1.1
34 */
35 public class ServletRequestConfiguration extends BaseWebConfiguration {
36
37 /** Stores the wrapped request. */
38 protected ServletRequest request;
39
40 /**
41 * Create a ServletRequestConfiguration using the request parameters.
42 *
43 * @param request the servlet request
44 */
45 public ServletRequestConfiguration(final ServletRequest request) {
46 this.request = Objects.requireNonNull(request, "config");
47 }
48
49 @Override
50 protected Iterator<String> getKeysInternal() {
51 // According to the documentation of getParameterMap(), keys are Strings.
52 final Map<String, ?> parameterMap = request.getParameterMap();
53 return parameterMap.keySet().iterator();
54 }
55
56 @Override
57 protected Object getPropertyInternal(final String key) {
58 final String[] values = request.getParameterValues(key);
59
60 if (values == null || values.length == 0) {
61 return null;
62 }
63 if (values.length == 1) {
64 return handleDelimiters(values[0]);
65 }
66 // ensure that escape characters in all list elements are removed
67 final List<Object> result = new ArrayList<>(values.length);
68 for (final String value : values) {
69 final Object val = handleDelimiters(value);
70 if (val instanceof Collection) {
71 result.addAll((Collection<?>) val);
72 } else {
73 result.add(val);
74 }
75 }
76 return result;
77 }
78 }