View Javadoc
1   package emissary.server.mvc.adapters;
2   
3   import jakarta.servlet.ServletRequest;
4   import org.slf4j.Logger;
5   import org.slf4j.LoggerFactory;
6   
7   import java.util.ArrayList;
8   import java.util.List;
9   import javax.annotation.Nullable;
10  
11  /**
12   * Utilities for dealing with request parameters
13   */
14  @SuppressWarnings("AvoidObjectArrays")
15  public class RequestUtil {
16      public static final int INT_PARAM_NOT_FOUND = -99;
17      public static final float FLOAT_PARAM_NOT_FOUND = -99.99f;
18  
19      private static final Logger logger = LoggerFactory.getLogger(RequestUtil.class);
20  
21      private RequestUtil() {}
22  
23      /**
24       * Get attribute or parameter from request. Attribute has priority over parameter when both are present. If no parameter
25       * is found, return the default value.
26       */
27      public static String getParameter(final ServletRequest request, final String param, @Nullable final String defaultVal) {
28          Object o = request.getAttribute(param);
29          if (o == null) {
30              o = sanitizeParameter(request.getParameter(param));
31          }
32  
33          if (o == null) {
34              o = defaultVal;
35          }
36          return (String) o;
37      }
38  
39  
40      /**
41       * Get attribute or parameter from request. Attribute has priority over parameter when both are present. If no parameter
42       * is found, return null.
43       */
44      public static String getParameter(final ServletRequest request, final String param) {
45          return getParameter(request, param, null);
46      }
47  
48      /**
49       * Get attribute or parameters from request and return an array of Strings. Attribute has priority over parameter when
50       * both are present
51       */
52      public static String[] getParameterValues(final ServletRequest request, final String param) {
53          String[] retArray;
54          Object o = request.getAttribute(param);
55  
56          if (o == null) {
57              o = sanitizeParameters(request.getParameterValues(param));
58          }
59  
60          try {
61              retArray = (String[]) o;
62          } catch (ClassCastException e) {
63              retArray = new String[1];
64              retArray[0] = (String) o;
65          }
66  
67          if (retArray != null) {
68              for (int i = 0; i < retArray.length; i++) {
69                  logger.debug("RequestUtil.getParameterValues for {} [{}]: {}", param, i, retArray[i]);
70              }
71          } else {
72              logger.debug("RequestUtil.getParameterValues for {} is null", param);
73          }
74  
75          return retArray;
76      }
77  
78      /**
79       * gets an int parameter.
80       *
81       * @return the parameter's int value, or -99 if the parameter is null.
82       */
83      public static int getIntParam(final ServletRequest request, final String param) {
84          return getIntParam(request, param, INT_PARAM_NOT_FOUND);
85      }
86  
87      /**
88       * gets an int parameter.
89       *
90       * @return the parameter's int value, or the default value if the parameter is null.
91       */
92      public static int getIntParam(final ServletRequest request, final String param, final int defValue) {
93          int retval = defValue;
94          String sInt = getParameter(request, param);
95          if (sInt != null) {
96              sInt = sInt.trim();
97              if (sInt.length() > 0) {
98                  try {
99                      retval = Integer.parseInt(sInt);
100                 } catch (NumberFormatException e) {
101                     logger.info("RequestUtil.getIntParam. Param {} had unparseable value '{}'.", param, sInt);
102 
103                 }
104             }
105         }
106 
107         logger.debug("RequestUtil.getIntParam for {}: {}.", param, retval);
108 
109         return retval;
110     }
111 
112     /**
113      * Retrieves boolean as a String ("true") and returns boolean.
114      * 
115      * @return boolean
116      */
117     public static boolean getBooleanParam(final ServletRequest request, final String param) {
118         return getBooleanParam(request, param, "true", false);
119     }
120 
121     /**
122      * Retrieves boolean if the string value of the parameter equals the trueString argument. If the parameter is not
123      * present, false will be returned
124      * 
125      * @return boolean
126      */
127     public static boolean getBooleanParam(final ServletRequest request, final String param, final String trueString) {
128         return getBooleanParam(request, param, trueString, false);
129     }
130 
131     /**
132      * Retrieves boolean if the string value of the parameter equals the trueString argument.
133      * 
134      * @return boolean
135      */
136     public static boolean getBooleanParam(final ServletRequest request, final String param, final String trueString, final boolean defaultVal) {
137         final String s = getParameter(request, param);
138         if (s != null) {
139             return s.equalsIgnoreCase(trueString);
140         }
141 
142         return defaultVal;
143     }
144 
145     /**
146      * Retrieves a list of Integers from the request
147      * 
148      * @return Integer[]
149      */
150     public static Integer[] getIntegers(final ServletRequest request, final String param) {
151         return getIntegers(request, param, INT_PARAM_NOT_FOUND);
152     }
153 
154     /**
155      * Retrieves a list of Integers from the request
156      * 
157      * @return Integer[]
158      */
159     public static Integer[] getIntegers(final ServletRequest request, final String param, final int defValue) {
160         final String[] values = getParameterValues(request, param);
161 
162         if (values == null) {
163             return new Integer[0];
164         }
165 
166         final Integer[] intValues = new Integer[values.length];
167 
168         for (int i = 0; i < values.length; i++) {
169             try {
170                 String temp = values[i];
171                 if (temp != null) {
172                     temp = temp.trim();
173                 }
174                 intValues[i] = Integer.valueOf(temp);
175             } catch (NumberFormatException ne) {
176                 logger.info("RequestUtil.getIntegers. Param {} had unparseable value '{}'.", param, values[i]);
177 
178                 intValues[i] = defValue;
179             }
180         }
181 
182         return intValues;
183     }
184 
185     /**
186      * gets a string parameter
187      *
188      * @return the parameter's value, or "" if the parameter is null.
189      */
190     public static String getParamNoNull(final ServletRequest request, final String param) {
191         final String temp = getParameter(request, param);
192         if (temp != null) {
193             return temp;
194         }
195         return "";
196     }
197 
198     /**
199      * gets a float parameter.
200      *
201      * @return the parameter's int value, or -99 if the parameter is null.
202      */
203     public static float getFloatParam(final ServletRequest request, final String param) {
204         return getFloatParam(request, param, FLOAT_PARAM_NOT_FOUND);
205     }
206 
207     /**
208      * gets a float parameter.
209      *
210      * @return the parameter's float value, or the default value if the parameter is null.
211      */
212     public static float getFloatParam(final ServletRequest request, final String param, final float defValue) {
213         float retval = defValue;
214         String sFloat = getParameter(request, param);
215         if (sFloat != null) {
216             sFloat = sFloat.trim();
217             if (sFloat.length() > 0) {
218                 try {
219                     retval = Float.parseFloat(sFloat);
220                 } catch (NumberFormatException e) {
221                     logger.info("RequestUtil.getFloatParam. Param {} had unparseable value '{}'.", param, sFloat);
222 
223                 }
224             }
225         }
226 
227         logger.debug("RequestUtil.getFloatParam for {}: {}.", param, retval);
228 
229         return retval;
230     }
231 
232     /**
233      * Sanitize request parameter to remove CR/LF values
234      *
235      * @param parameter the String to sanitize
236      * @return a new String object with any CR/LF characters removed or null when the provided argument is null
237      */
238     @Nullable
239     public static String sanitizeParameter(String parameter) {
240         return (null == parameter ? null : parameter.replaceAll("[\n\r]", "_"));
241     }
242 
243     /**
244      * Sanitize request parameters to remove CR/LF values
245      *
246      * @param parameters the String[] to sanitize
247      * @return a new String[] object with any CR/LF characters removed
248      */
249     public static String[] sanitizeParameters(String[] parameters) {
250         List<String> sanitizedParameters = new ArrayList<>();
251         if (null != parameters) {
252             for (String parameter : parameters) {
253                 sanitizedParameters.add(sanitizeParameter(parameter));
254             }
255         }
256         return sanitizedParameters.toArray(new String[0]);
257     }
258 
259     /**
260      * Sanitize request parameters to remove CR/LF values
261      *
262      * @param parameters the List String to sanitize
263      * @return a new List String object with any CR/LF characters removed
264      */
265     public static List<String> sanitizeParametersStringList(List<String> parameters) {
266         List<String> sanitizedParameters = new ArrayList<>();
267         if (null != parameters) {
268             for (String parameter : parameters) {
269                 sanitizedParameters.add(sanitizeParameter(parameter));
270             }
271         }
272         return sanitizedParameters;
273     }
274 }