Java tutorial
/* * Copyright 2014 Christian Robert * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.perdian.commons.servlet; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.LocaleUtils; /** * Static helper method for working in a servlet environment * * @author Christian Robert */ public class ServletUtils { /** * Extracts a parameter value from the given request. The method makes * sure that the parameter retrieved from the request is properly cleaned * up, which means that any leading or trailing whitespaces will be removed * so the caller can expect just the plain and simple parameter value * * @param servletRequest * the request from which to extract the parameter value * @param parameterName * the name of the parameter to extract */ public static String extractParameterString(HttpServletRequest servletRequest, String parameterName) { return ServletUtils.extractParameterString(servletRequest, parameterName, null); } /** * Extracts a parameter value from the given request. The method makes * sure that the parameter retrieved from the request is properly cleaned * up, which means that any leading or trailing whitespaces will be removed * so the caller can expect just the plain and simple parameter value * * @param servletRequest * the request from which to extract the parameter value * @param parameterName * the name of the parameter to extract * @param defaultValue * the default value to be returned if the parameter is either not set * in the given requests or evaluates to an empty String. */ public static String extractParameterString(HttpServletRequest servletRequest, String parameterName, String defaultValue) { String parameterValue = servletRequest.getParameter(parameterName); String cleanParameterValue = parameterValue == null ? null : parameterValue.trim(); return cleanParameterValue == null || cleanParameterValue.length() <= 0 ? defaultValue : cleanParameterValue; } /** * Extracts a parameter value from the given request and try parsing it into * an integer value. The method makes sure that the parameter retrieved from * the request is properly cleaned up, which means that any leading or * trailing whitespaces will be removed so the caller can expect just the * plain and simple parameter value * * @param servletRequest * the request from which to extract the parameter value * @param parameterName * the name of the parameter to extract * @param defaultValue * the default value to be returned if the parameter is either not set * in the given requests or evaluates to an empty String. The default * value will also be returned if the property value cannot be converted * into a valid integer value. */ public static int extractParameterInt(HttpServletRequest servletRequest, String parameterName, int defaultValue) { String cleanParameterValue = ServletUtils.extractParameterString(servletRequest, parameterName, null); if (cleanParameterValue == null || cleanParameterValue.length() <= 0) { return defaultValue; } else { try { return Integer.parseInt(cleanParameterValue); } catch (Exception e) { return defaultValue; } } } /** * Extracts a parameter value from the given request and try parsing it into * a boolean value. The method makes sure that the parameter retrieved from * the request is properly cleaned up, which means that any leading or * trailing whitespaces will be removed so the caller can expect just the * plain and simple parameter value * * @param servletRequest * the request from which to extract the parameter value * @param parameterName * the name of the parameter to extract */ public static boolean extractParameterBoolean(HttpServletRequest servletRequest, String parameterName) { return ServletUtils.extractParameterBoolean(servletRequest, parameterName, false); } /** * Extracts a parameter value from the given request and try parsing it into * a boolean value. The method makes sure that the parameter retrieved from * the request is properly cleaned up, which means that any leading or * trailing whitespaces will be removed so the caller can expect just the * plain and simple parameter value * * @param servletRequest * the request from which to extract the parameter value * @param parameterName * the name of the parameter to extract * @param defaultValue * the default value to be returned if the parameter is either not set * in the given requests or evaluates to an empty String. The default * value will also be returned if the property value cannot be converted * into a valid boolean value. Valid Strings for boolean {@code true} * values are considered "true", "on" and "1" */ public static boolean extractParameterBoolean(HttpServletRequest servletRequest, String parameterName, boolean defaultValue) { String cleanParameterValue = ServletUtils.extractParameterString(servletRequest, parameterName, null); boolean parameterTrue = "true".equalsIgnoreCase(cleanParameterValue) || "on".equalsIgnoreCase(cleanParameterValue) || "1".equalsIgnoreCase(cleanParameterValue); return parameterTrue ? true : defaultValue; } /** * Extracts the locales supported by the client that sent a given request. * According to RFC 2161 the result list will be sorted according to any * specified preferenc value (see the RFC for details) * * @param servletRequest * the request from which to extract the information * @param defaultLocales * the locales to be returned if no locales could be extracted from the * request * @return * a {@code List} containing the accepted {@code java.util.Locale} * objects. If no locales are found in the request, then the method will * return the default locale list or an empty list if no default locales * have been passed - never {@code null} */ public static List<Locale> extractAcceptedLocales(HttpServletRequest servletRequest, List<Locale> defaultLocales) { Map<Float, List<Locale>> localeValuesByPriority = new TreeMap<>((o1, o2) -> -1 * Float.compare(o1, o2)); String headerValue = servletRequest.getHeader("accept-language"); if (headerValue != null) { StringTokenizer headerTokenizer = new StringTokenizer(headerValue, ","); while (headerTokenizer.hasMoreElements()) { String header = headerTokenizer.nextToken().trim(); int semicolonSeparator = header.indexOf(";"); String localeValue = semicolonSeparator > 0 ? header.substring(0, semicolonSeparator) : header; Locale locale = LocaleUtils.toLocale(localeValue); if (locale != null) { Float qValue = Float.valueOf(1f); String qParameter = ";q="; int qParameterIndex = header.indexOf(qParameter); if (qParameterIndex > 0) { try { String qParameterValue = header.substring(qParameterIndex + qParameter.length()); qValue = Float.valueOf(qParameterValue); } catch (Exception e) { // Ignore here and use the default } } List<Locale> targetList = localeValuesByPriority.get(qValue); if (targetList == null) { targetList = new ArrayList<>(); localeValuesByPriority.put(qValue, targetList); } targetList.add(locale); } } } List<Locale> localeValues = new ArrayList<>(); for (Map.Entry<Float, List<Locale>> localeValueEntry : localeValuesByPriority.entrySet()) { for (Locale locale : localeValueEntry.getValue()) { localeValues.add(locale); } } if (localeValues.isEmpty() && defaultLocales != null) { localeValues.addAll(defaultLocales); } return Collections.unmodifiableList(localeValues); } }