Class HttpUtil
- All Implemented Interfaces:
JcmsConstants,JaliosConstants
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final StringRegular expression suitable for use ingetStringParameter(HttpServletRequest, String, String, String).static final StringRegular expression suitable for use ingetStringParameter(HttpServletRequest, String, String, String).static final StringHTTP Header name from which CSRF token to be validated can be retrievedstatic final StringExtraDBData attribute name used to store the current and expected value of the CSRF token.static final StringParameter name from which CSRF token to be validated can be retrievedstatic final StringSession attribute name used to store the current and expected value of the CSRF token.static final StringExtraDBData attribute name used to store the time at which member csrf token was saved (epoch time).static final StringRegular expression suitable for use ingetStringParameter(HttpServletRequest, String, String, String).static final StringRegular expression suitable for use ingetStringParameter(HttpServletRequest, String, String, String).static final StringRegular expression suitable for use ingetStringParameter(HttpServletRequest, String, String, String).static final StringAccept HTTP Header namestatic final StringRegular expression suitable for use ingetStringParameter(HttpServletRequest, String, String, String).static final StringRegular expression suitable for use ingetStringParameter(HttpServletRequest, String, String, String).static final StringFields inherited from interface com.jalios.util.JaliosConstants
CRLF, MILLIS_IN_ONE_DAY, MILLIS_IN_ONE_HOUR, MILLIS_IN_ONE_MINUTE, MILLIS_IN_ONE_MONTH, MILLIS_IN_ONE_SECOND, MILLIS_IN_ONE_WEEK, MILLIS_IN_ONE_YEARFields inherited from interface com.jalios.jcms.JcmsConstants
ADATE_SEARCH, ADVANCED_TAB, AJAX_MODE_ATTR, ARCHIVES_DIR, ASCII_WIDTH, CATEGORY_TAB, CDATE_SEARCH, CLASS_PROPERTY, COMMON_ALARM, CONTENT_TAB, COOKIE_MAX_AGE, COUNTRY_SPRITE, CS_TYPOLOGY_ROOT_CAT_VID, CTRL_TOPIC_INTERNAL, CTRL_TOPIC_REF, CTRL_TOPIC_VALUE, CTRL_TOPIC_WRITE, CUSTOM_PROP, DATA_DIRECTORY, DEFAULT_PHOTO_PROP, DOCCHOOSER_HEIGHT, DOCCHOOSER_WIDTH, DOCS_DIR, EDATE_SEARCH, EMAIL_REGEXP, ERROR_MSG, FORBIDDEN_FILE_ACCESS, FORBIDDEN_REDIRECT, FORCE_REDIRECT, GENERATIONAL_STORE_DIRECTORY, GLYPH_ICON_PREFIX, ICON_ARCHIVE, ICON_ICON_PREFIX, ICON_LOCK, ICON_LOCK_STRONG, ICON_PREFIX_PROP, ICON_WARN, ICON_WH_BOOK_CLOSED, ICON_WH_BOOK_OPEN, INFORMATION_MSG, IS_IN_FRONT_OFFICE, JALIOS_JUNIT_PROP, JCMS_CADDY, JCMS_MSG_LIST, JCMS_TOASTR_COLLECTION, JSYNC_DOWNLOAD_DIR, JSYNC_SYNC_ALARM, LANG_SPRITE, LOG_FILE, LOG_TOPIC_SECURITY, LOGGER_PROP, LOGGER_XMLPROP, MBR_PHOTO_DIR, MDATE_SEARCH, MONITOR_XML, OP_CREATE, OP_CREATE_STR, OP_DEEP_COPY, OP_DEEP_COPY_STR, OP_DEEP_DELETE, OP_DEEP_DELETE_STR, OP_DELETE, OP_DELETE_STR, OP_MERGE, OP_MERGE_STR, OP_UPDATE, OP_UPDATE_STR, ORGANIZATION_ROOT_GROUP_PROP, PDATE_SEARCH, PHOTO_DIR, PHOTO_ICON, PHOTO_ICON_HEIGHT, PHOTO_ICON_PROP_PREFIX, PHOTO_ICON_WIDTH, PHOTO_LARGE, PHOTO_LARGE_HEIGHT, PHOTO_LARGE_PROP_PREFIX, PHOTO_LARGE_WIDTH, PHOTO_MINI, PHOTO_MINI_HEIGHT, PHOTO_MINI_PROP_PREFIX, PHOTO_MINI_WIDTH, PHOTO_NORMAL, PHOTO_NORMAL_HEIGHT, PHOTO_NORMAL_PROP_PREFIX, PHOTO_NORMAL_WIDTH, PHOTO_SMALL, PHOTO_SMALL_HEIGHT, PHOTO_SMALL_PROP_PREFIX, PHOTO_SMALL_WIDTH, PHOTO_TINY, PHOTO_TINY_HEIGHT, PHOTO_TINY_PROP_PREFIX, PHOTO_TINY_WIDTH, PHOTO_XLARGE, PHOTO_XLARGE_HEIGHT, PHOTO_XLARGE_PROP_PREFIX, PHOTO_XLARGE_WIDTH, PREVIOUS_TAB, PRINT_VIEW, PRIVATE_FILE_ACCESS, PUBLIC_FILE_ACCESS, RAW_CONTENT_ICON_PREFIX, READ_RIGHT_TAB, SDATE_SEARCH, SEARCHENGINE_ALARM, SECURITY_LOG_FILE, SESSION_AUTHORIZED_FILENAMES_SET, SPRITE_ICON_PREFIX, STATS_REPORT_DIR, STATUS_PROP, STORE_XML, SUCCESS_MSG, SVG_ICON_PREFIX, SVGINLINE_ICON_PREFIX, SVGSPRITE_ICON_PREFIX, TEMPLATE_TAB, THEME_DIR, THUMBNAIL_LARGE_HEIGHT, THUMBNAIL_LARGE_WIDTH, THUMBNAIL_SMALL_HEIGHT, THUMBNAIL_SMALL_WIDTH, TTCARD_MEDIA_HEIGHT, TTCARD_MEDIA_WIDTH, TYPES_ICON_ALT_PROP, TYPES_ICON_SUFFIX_PROP, TYPES_ICON_TITLE_PROP, TYPES_PREFIX_PROP, TYPES_THUMB_SUFFIX_PROP, TYPES_UNKNOWN_CLASS_PROP, UDATE_SEARCH, UPDATE_RIGHT_TAB, UPLOAD_DIR, UPLOAD_PERMISSION_COUNT_PROP_PREFIX, UPLOAD_PERMISSION_SIZE_PROP_PREFIX, URL_REGEXP, VID_LOGGED_MEMBER, WARNING_MSG, WEBAPP_PROP, WFEXPRESS_ALARM, WFREMINDER_ALARM, WORKFLOW_TAB, WORKFLOW_XML -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic booleanCheck if the specified mime type can be understood by the client who emitted the specified request as specified by its Accept HTTP header.static voidaddAttachmentHeader(javax.servlet.http.HttpServletResponse response, String filename) Add the Content-Disposition HTTP header and attachement parameter field to specify which name to use on remote client when downloading a file.static voidaddAttachmentHeader(javax.servlet.http.HttpServletResponse response, String filename, boolean forceDownload) Add the Content-Disposition HTTP header and attachement parameter field to specify which name to use on remote client when downloading a file.static voidaddCookie(javax.servlet.http.HttpServletResponse response, javax.servlet.http.Cookie cookie) Add a cookie to the response.static voidAdd a header to the response after ensuring that there are no encoded or illegal characters in the name and name and value.static voidauthorizeUrl(String id, String url, boolean prefix) Authorize the specified URL in URL validation check.static booleancheckCSRF(javax.servlet.http.HttpServletRequest request) Check if the specified request is valid against CSRF attack.static voidclearMemberCSRFToken(Member member) Remove CSRF token of the specified memberstatic StringencodeForHTML(String input) Encode data for use in HTML using HTML entity encodingstatic StringencodeForHTMLAttribute(String input) Encode data for use in HTML attributes.static StringencodeForHTMLAttribute(String input, boolean unescapeHTML) Encode data for use in HTML attributes, optionally unescaping the HTML before the encoding.static StringencodeForJavaScript(String input) Encode data for insertion inside a data value or function argument in JavaScript.static StringencodeForURL(String input) Encode for use in a URL.static StringencodeForXML(String input) Encode data for use in an XML element.static StringencodeForXMLAttribute(String input) Encode data for use in an XML attribute.static StringgetAlphaNumParameter(javax.servlet.http.HttpServletRequest request, String parameterName, String defaultValue) Retrieve a String value from specified HTTP request parameter.static booleangetBooleanParameter(javax.servlet.http.HttpServletRequest request, String parameterName, boolean defaultValue) Retrieve a boolean value from specified HTTP request parameter.static CategorygetCategoryParameter(javax.servlet.http.HttpServletRequest request, String parameterName) Retrieve a Category from its id received in parameter.static StringgetChooserParameter(javax.servlet.http.HttpServletRequest request, String parameterName) Retrieve a verified targetInput, targetLabel or other target value used by JCMS Choosers inside javascript code.static longRetrieve the duration in milliseconds above which a member token is considered invalid.static StringgetCSRFToken(javax.servlet.http.HttpServletRequest request) Retrieve the value of CSRF token (both session & member) for the current request.static StringgetCurrentCSRFToken(javax.servlet.http.HttpServletRequest request) Retrieve the current valid CSRF Token expected on critical requests of the current session.static StringgetCurrentCSRFToken(javax.servlet.http.HttpSession session) Retrieve the current valid CSRF Token expected on critical requests of the current session.static StringgetCurrentMemberCSRFToken(Member member) Retrieve the current valid CSRF Token expected on critical requests of the specified member.static StringgetDataIdParameter(javax.servlet.http.HttpServletRequest request, String parameterName) Retrieve a Data id from parameter.getDataListParameter(javax.servlet.http.HttpServletRequest request, String parameterName, Class<T> clazz) Retrieve a list of Data from ids received in only one value of the parameter (seperated with spaces or coma).static DatagetDataParameter(javax.servlet.http.HttpServletRequest request, String parameterName) Retrieve a Data from its id received in parameter.static <T> TgetDataParameter(javax.servlet.http.HttpServletRequest request, String parameterName, Class<T> clazz) Retrieve a typed Data from its id received in parameter.static DategetDateParameter(javax.servlet.http.HttpServletRequest request, String parameterName, String dateLanguage, Date defaultValue) Retrieve a Date (date only) value from specified HTTP request parameter.static DategetDateParameter(javax.servlet.http.HttpServletRequest request, String parameterName, DateFormat dateFormat, Date defaultValue) Deprecated, for removal: This API element is subject to removal in a future version.static DategetDateTimeParameter(javax.servlet.http.HttpServletRequest request, String parameterName, String dateLanguage, Date defaultValue) Retrieve a Date (date and time) value from specified HTTP request parameter.static doublegetDoubleParameter(javax.servlet.http.HttpServletRequest request, String parameterName, double defaultValue) Retrieve a double value from specified HTTP request parameter.static GroupgetGroupParameter(javax.servlet.http.HttpServletRequest request, String parameterName) Retrieve a Group from its id received in parameter.static intgetIntParameter(javax.servlet.http.HttpServletRequest request, String parameterName, int defaultValue) Retrieve an integer value from specified HTTP request parameter.static StringgetJsonParameterFromRequest(javax.servlet.http.HttpServletRequest request) Returns a String (json format) representing all parameters in the specified request.static longgetLongParameter(javax.servlet.http.HttpServletRequest request, String parameterName, long defaultValue) Retrieve a long value from specified HTTP request parameter.static MembergetMemberParameter(javax.servlet.http.HttpServletRequest request, String parameterName) Retrieve a Member from its id received in parameter.static PublicationgetPublicationParameter(javax.servlet.http.HttpServletRequest request, String parameterName) Retrieve a Publication from its id received in parameter.static StringgetRemoteIpAddr(javax.servlet.http.HttpServletRequest request) Get the remote IP of the request (with usage ofXFORWARDheader or attribute)static StringgetStringEnumParameter(javax.servlet.http.HttpServletRequest request, String parameterName, String defaultValue, String... possibleValues) Retrieve a String value from specified HTTP request parameter.static StringgetStringParameter(javax.servlet.http.HttpServletRequest request, String parameterName, String defaultValue, String regex) Retrieve a String value from specified HTTP request parameter.static String[]getStringParameterValues(javax.servlet.http.HttpServletRequest request, String parameterName, String regex) Retrieve array of String values from specified HTTP request parameter.static StringgetUntrustedStringParameter(javax.servlet.http.HttpServletRequest request, String parameterName, String defaultValue) Retrieve any String value from the specified HTTP request parameter.static StringgetUrlWithCSRFToken(String url, javax.servlet.http.HttpServletRequest request, boolean escapeAmpersand) Adds the current CSRF token to the specified URL and returns it.static StringgetValidHttpUrl(javax.servlet.http.HttpServletRequest request, String parameterName) Retrieve a verified URL parameter value.static WorkspacegetWorkspaceParameter(javax.servlet.http.HttpServletRequest request, String parameterName) Retrieve a Workspace from its id received in parameter.static StringgetXForwardedFor(javax.servlet.http.HttpServletRequest request) Get the x-forwarded for element of the request (with usage ofXFORWARDheader or attribute)static booleanhasParameter(javax.servlet.http.HttpServletRequest request, String parameterName) Check if a parameter was received in the specified request.static voidinitializeCSRFToken(javax.servlet.http.HttpSession session) Initialize a new CSRF Token for the current session (if any)static voidinitializeMemberCSRFToken(Member member, javax.servlet.http.HttpServletRequest request) Initialize the CSRF Token for the specified member from the current CSRF token of the request (if any)static booleanCheck if CSRF token should be allowed through different session in order to allow a submition after session expiration.static booleanisValidAgainstRegex(String context, String property, String input) Check the specified input match the regex defined in specified propertystatic booleanisValidDisplayServletPath(String displayServletPath) Check if the specified path is valid for use by the display servletstatic booleanisValidHttpUrl(String url) Check that the specified URL (absolute or relative) is a valid URL authorized for use in redirection.static DateParses a date string using either legacy or ISO 8601 formats.static voidunauthorizeUrl(String id) Unauthorized a previously registered URL from URL validation check, by specifying the identifier that was used when authorized.static StringvalidateHttpUrl(String url) Validate an URL and returns it.static StringvalidateString(String value, String regex) Validate a String value against specified regular expression.static String[]validateStringValues(String[] values, String regex) Validate each value in the specified array of String values against specified regular expression.
-
Field Details
-
XFORWARD
- See Also:
-
DATAID_REGEX
Regular expression suitable for use ingetStringParameter(HttpServletRequest, String, String, String).Match all characters which could be used as a JCMS data id (JStore/JcmsDB), this includes virtual id such as "$channel.root-cat" : "^\\$?[0-9a-zA-Z_\\-\\.]+$". Beware that this regex does not validate that the id matchs a valid data.
- See Also:
-
ALPHANUM_REGEX
Regular expression suitable for use ingetStringParameter(HttpServletRequest, String, String, String).Match all alpha-numeric characters and the underscore (_ as in perl regex) and the dash (-): "^[0-9a-zA-Z_\\-]+$".
- See Also:
-
CLASSNAME_REGEX
Regular expression suitable for use ingetStringParameter(HttpServletRequest, String, String, String).Match Java class names, such as
com.jalios.jcms.Content.- See Also:
-
PROPERTYNAME_REGEX
Regular expression suitable for use ingetStringParameter(HttpServletRequest, String, String, String).Match JCMS property names, such as
$channel.root-category,some.important-property.foo_bar22/zig.- See Also:
-
TEMPLATEUSAGE_REGEX
Regular expression suitable for use ingetStringParameter(HttpServletRequest, String, String, String).Match JCMS template usage name, such as
box,full,front,query, ...- See Also:
-
CSS_COLOR_REGEX
Regular expression suitable for use ingetStringParameter(HttpServletRequest, String, String, String).Accept CSS color value, such as
red,transparent,rgb(255,0,51),hsl(240,100%,50%,5%),hsla(240deg 100% 50% / 5%),var(--j-palette-colors-gray-light-mode-800)...Warning : this regular expression does NOT verify that the specified value is a syntactically valid CSS color, it only verifies it contains authorized characters for CSS color values.
- Since:
- JCMS-8847
- See Also:
-
DATASOURCE_REGEX
Regular expression suitable for use ingetStringParameter(HttpServletRequest, String, String, String).Accept DataSource, such as
jdbc/mydbWarning : this regular expression does NOT verify that the specified value is a syntactically valid DataSource, it only verifies it contains authorized characters for DataSource values.
- Since:
- JCMS-8847
- See Also:
-
CSRF_TOKEN_SESSION_ATTRIBUTE
Session attribute name used to store the current and expected value of the CSRF token.Do not use directly, instead use
initializeCSRFToken(HttpSession).- See Also:
-
CSRF_TOKEN_MEMBER_EXTRADBDATA
ExtraDBData attribute name used to store the current and expected value of the CSRF token.Do not use directly, instead use
initializeMemberCSRFToken(Member, HttpServletRequest).- See Also:
-
CSRF_TOKEN_TIME_MEMBER_EXTRADBDATA
ExtraDBData attribute name used to store the time at which member csrf token was saved (epoch time). Used to control its validity in time. (expiration).Do not use directly, instead use
initializeMemberCSRFToken(Member, HttpServletRequest).- See Also:
-
CSRF_TOKEN_PARAMETER_NAME
Parameter name from which CSRF token to be validated can be retrieved- See Also:
-
CSRF_TOKEN_HEADER_NAME
HTTP Header name from which CSRF token to be validated can be retrieved- See Also:
-
HTTP_HEADER_ACCEPT
Accept HTTP Header name- See Also:
-
-
Constructor Details
-
HttpUtil
public HttpUtil()
-
-
Method Details
-
encodeForXML
Encode data for use in an XML element. The implementation should follow the XML Encoding Standard from the W3C.The use of a real XML parser is strongly encouraged. However, in the hopefully rare case that you need to make sure that data is safe for inclusion in an XML document and cannot use a parse, this method provides a safe mechanism to do so.
- Parameters:
input- the text to encode for XML- Returns:
- input encoded for XML, return empty string if null was specified as input parameter
- See Also:
-
encodeForXMLAttribute
Encode data for use in an XML attribute. The implementation should follow the XML Encoding Standard from the W3C.The use of a real XML parser is highly encouraged. However, in the hopefully rare case that you need to make sure that data is safe for inclusion in an XML document and cannot use a parse, this method provides a safe mechanism to do so.
- Parameters:
input- the text to encode for use as an XML attribute- Returns:
- input encoded for XML attribute, return empty string if null was specified as input parameter
- See Also:
-
encodeForHTML
Encode data for use in HTML using HTML entity encodingNote that the following characters: 00-08, 0B-0C, 0E-1F, and 7F-9F
cannot be used in HTML.
- Parameters:
input- the text to encode for HTML- Returns:
- input encoded for HTML, return empty string if null was specified as input parameter
- See Also:
-
encodeForHTMLAttribute
Encode data for use in HTML attributes.- Parameters:
input- the text to encode for an HTML attribute- Returns:
- input encoded for use as an HTML attribute, return empty string if null was specified as input parameter
-
encodeForHTMLAttribute
Encode data for use in HTML attributes, optionally unescaping the HTML before the encoding.Unescaping the HTML is needed when working with text value stored inside JCMS Data. Indeed, text entered by the user is escaped using
JcmsUtil.escapeHtml(String)prior being saved in the Data fields, thus in order to display the text exactly as entered by the user, unescaping the input usingJcmsUtil.unescapeHtml(String)is necessary.Example :
<span title="<%= encodeForHTMLAttribute(data.getTitle(userLang), true) %>">...</span> <span title="<%= encodeForHTMLAttribute(glp("..."), false) %>">...</span>- Parameters:
input- the text to encode for an HTML attributeunescapeHTML- set to true to unescape HTML PRIOR to HTML attribute encoding, set to false to only perform HTML attribute encoding.- Returns:
- input encoded for use as an HTML attribute, return empty string if null was specified as input parameter
- Since:
- jcms-9.0
-
encodeForJavaScript
Encode data for insertion inside a data value or function argument in JavaScript. Including user data directly inside a script is quite dangerous. Great care must be taken to prevent including user data directly into script code itself, as no amount of encoding will prevent attacks there. Please note there are some JavaScript functions that can never safely receive untrusted data as input – even if the user input is encoded. For example: <script> window.setInterval('<%= EVEN IF YOU ENCODE UNTRUSTED DATA YOU ARE XSSED HERE %>'); </script>- Parameters:
input- the text to encode for JavaScript- Returns:
- input encoded for use in JavaScript, return empty string if null was specified as input parameter
-
encodeForURL
Encode for use in a URL. This method performs URL encoding on the entire string.- Parameters:
input- the text to encode for use in a URL- Returns:
- input encoded for use in a URL, return empty string if null was specified as input parameter
- See Also:
-
addAttachmentHeader
public static void addAttachmentHeader(javax.servlet.http.HttpServletResponse response, String filename) Add the Content-Disposition HTTP header and attachement parameter field to specify which name to use on remote client when downloading a file.- Parameters:
response- the HttpServletResponse in which to send the header, if null method returns immediatelyfilename- the name of the file to use on remote client, if null or empty value method return immediately- Since:
- 8.0.3 / 9.0.1 - JCMS-4395
-
addAttachmentHeader
public static void addAttachmentHeader(javax.servlet.http.HttpServletResponse response, String filename, boolean forceDownload) Add the Content-Disposition HTTP header and attachement parameter field to specify which name to use on remote client when downloading a file.- Parameters:
response- the HttpServletResponse in which to send the header, if null method returns immediatelyfilename- the name of the file to use on remote client, if null or empty value method return immediatelyforceDownload- if true add "attachment" in the header value to force the download- Since:
- 10.0.8
-
getValidHttpUrl
public static String getValidHttpUrl(javax.servlet.http.HttpServletRequest request, String parameterName) Retrieve a verified URL parameter value.Example :
String redirect = getValidHttpUrl(request, "redirect");
- Parameters:
request- the request from which the parameter will be readparameterName- the name of the HTTP parameter to be retrieved- Returns:
- the URL or null if parameter was missing or received URL was invalid
-
validateHttpUrl
Validate an URL and returns it.Example :
String redirect = validateHttpUrl("http://www.example.com/");- Parameters:
url- the value to be verified- Returns:
- the URL or null if URL was invalid
-
isValidHttpUrl
Check that the specified URL (absolute or relative) is a valid URL authorized for use in redirection.The following rules are required :
- URLs must not exceed 2000 characters
- URLs must match dedicated regex property
channel.security.Validator.JCMSRedirectURL
- Relative URLs are always accepted
- URLs starting with site's base URL are accepted
- URLs starting with base URL of current servlet request are accepted
- URLs starting with any active configuration of reverse proxy's base URL are accepted (http or https)
- URLs matching any regex configured in JCMS properties
channel.security.authorized-redirect.*are accepted - Other URLs are rejected
You can enable
TRACElogging on this class for detailed information of validation being performed.<logger name="com.jalios.jcms.HttpUtil"> <level value="TRACE" /> </logger>
- Parameters:
url- the URL to check- Returns:
- true if a redirect can be perform with this URL, false otherwise
-
authorizeUrl
Authorize the specified URL in URL validation check.Use this method to authorize redirect to external trusted site, which are dynamically declared (e.g. SSO).
The authorization is voluntarly NOT saved upon restart.
Invoke this method each time the configuration changes, with its corresponding removal methodunauthorizeUrl(String).- Parameters:
id- a unique identifier to identify the URL being added, must no be nullurl- the URL prefix to add authorized, must no be nullprefix- true to authorized all URL prefixed with specified value, false to authorized only this exact URL- Since:
- 10.0.8 / JCMS-10400
- See Also:
-
unauthorizeUrl
Unauthorized a previously registered URL from URL validation check, by specifying the identifier that was used when authorized.Use this method to unauthorize a URL when the configuration changes.
- Parameters:
id- the unique identifier that was used inauthorizeUrl(String, String, boolean)to identify the authorized URL, must no be null- Since:
- 10.0.8 / JCMS-10400
- See Also:
-
isValidDisplayServletPath
Check if the specified path is valid for use by the display servlet- Parameters:
displayServletPath- a servlet path such as "/jcms/c_42/foo-bar"- Returns:
- true if the path is valid, false otherwise
-
isValidAgainstRegex
Check the specified input match the regex defined in specified property- Parameters:
context- a context used for logging if validation failsproperty- the name of a propery in which regexp is retrievedinput- the input to check- Returns:
- true if input validate the regexp, false otherwise
- Since:
- jcms-10.0.0 / JCMS-5568 (public since 10.0.8 / JCMS-10963)
-
getChooserParameter
public static String getChooserParameter(javax.servlet.http.HttpServletRequest request, String parameterName) Retrieve a verified targetInput, targetLabel or other target value used by JCMS Choosers inside javascript code.Example :
String targetInput = getChooserParameter("targetInput"); String targetLabel = getChooserParameter("targetLabel");- Parameters:
request- HttpServletRequest from which parameter must be readparameterName- the name of the HTTP parameter to be retrieved- Returns:
- a valid and sanitized target (input, label, ...) or null if parameter was missing or invalid
-
getDataParameter
public static <T> T getDataParameter(javax.servlet.http.HttpServletRequest request, String parameterName, Class<T> clazz) Retrieve a typed Data from its id received in parameter.Examples :
Portal portal = getDataParameter(request, "portal", Portal.class); SmallNews sm = getDataParameter(request, "id", SmallNews.class);
- Type Parameters:
T- the expected class of Data- Parameters:
request- HttpServletRequest from which parameter must be read, must not be nullparameterName- the name of the HTTP parameter from which data id will be retrieved, must not be nullclazz- the expected class of Data- Returns:
- the Data corresponding to the id received in parameter or null if parameter was missing, empty, invalid, or for a Data of another class
-
getDataListParameter
public static <T extends Data> List<T> getDataListParameter(javax.servlet.http.HttpServletRequest request, String parameterName, Class<T> clazz) Retrieve a list of Data from ids received in only one value of the parameter (seperated with spaces or coma).Examples :
List<Group> groupList = getDataListParameter(request, "groups", Portal.class); SmallNews sm = getDataParameter(request, "id", SmallNews.class);
- Type Parameters:
T- the expected class of Data- Parameters:
request- HttpServletRequest from which parameter must be read, must not be nullparameterName- the name of the HTTP parameter from which data ids will be retrieved, must not be nullclazz- the expected class of Data- Returns:
- the List of Data, corresponding to the ids received in parameter or empty list if parameter was missing, empty or invalid
-
getDataParameter
public static Data getDataParameter(javax.servlet.http.HttpServletRequest request, String parameterName) Retrieve a Data from its id received in parameter.Example :
Data data = getDataParameter(request, "id");
- Parameters:
request- HttpServletRequest from which parameter must be read, must not be nullparameterName- the name of the HTTP parameter from which data id will be retrieved, must not be null- Returns:
- the Data corresponding to the id received in parameter or null if parameter was missing, empty, invalid, or for a Data of another class
-
getWorkspaceParameter
public static Workspace getWorkspaceParameter(javax.servlet.http.HttpServletRequest request, String parameterName) Retrieve a Workspace from its id received in parameter.Example :
Workspace ws = getWorkspaceParameter(request, "ws");
- Parameters:
request- HttpServletRequest from which parameter must be read, must not be nullparameterName- the name of the HTTP parameter from which data id will be retrieved, must not be null- Returns:
- the Workspace corresponding to the id received in parameter or null if parameter was missing, empty, invalid, or for a Data of another class
-
getCategoryParameter
public static Category getCategoryParameter(javax.servlet.http.HttpServletRequest request, String parameterName) Retrieve a Category from its id received in parameter.Example :
Category cat = getCategoryParameter(request, "cid");
- Parameters:
request- HttpServletRequest from which parameter must be read, must not be nullparameterName- the name of the HTTP parameter from which data id will be retrieved, must not be null- Returns:
- the Category corresponding to the id received in parameter or null if parameter was missing, empty, invalid, or for a Data of another class
-
getPublicationParameter
public static Publication getPublicationParameter(javax.servlet.http.HttpServletRequest request, String parameterName) Retrieve a Publication from its id received in parameter.Example :
Publication pub = getPublicationParameter(request, "id");
- Parameters:
request- HttpServletRequest from which parameter must be read, must not be nullparameterName- the name of the HTTP parameter from which data id will be retrieved, must not be null- Returns:
- the Publication corresponding to the id received in parameter or null if parameter was missing, empty, invalid, or for a Data of another class
-
getMemberParameter
public static Member getMemberParameter(javax.servlet.http.HttpServletRequest request, String parameterName) Retrieve a Member from its id received in parameter.Example :
Member mbr = getMemberParameter(request, "mbrId");
- Parameters:
request- HttpServletRequest from which parameter must be read, must not be nullparameterName- the name of the HTTP parameter from which data id will be retrieved, must not be null- Returns:
- the Member corresponding to the id received in parameter or null if parameter was missing, empty, invalid, or for a Data of another class
-
getGroupParameter
public static Group getGroupParameter(javax.servlet.http.HttpServletRequest request, String parameterName) Retrieve a Group from its id received in parameter.Example :
Group grp = getGroupParameter(request, "grpId");
- Parameters:
request- HttpServletRequest from which parameter must be read, must not be nullparameterName- the name of the HTTP parameter from which data id will be retrieved, must not be null- Returns:
- the Group corresponding to the id received in parameter or null if parameter was missing, empty, invalid, or for a Data of another class
-
hasParameter
public static boolean hasParameter(javax.servlet.http.HttpServletRequest request, String parameterName) Check if a parameter was received in the specified request.Example :
if (hasParameter(request, "opRefresh")) { //... }This method is the same as doing :String value = getUntrustedStringParameter(request, parameterName); // request.getParameter(parameterName); return value != null;
- Parameters:
request- HttpServletRequest from which parameter must be read, must not be nullparameterName- name of the HTTP parameter from which value will be read, must not be null- Returns:
- false if parameter was not in the request (null value) true in any other case
-
getBooleanParameter
public static boolean getBooleanParameter(javax.servlet.http.HttpServletRequest request, String parameterName, boolean defaultValue) Retrieve a boolean value from specified HTTP request parameter.Important remark regarding behavior on missing/invalid parameter :
- Use the specified defaultValue if parameter is missing (null).
- Always returns
falsewhen parameter value contains invalid data (neither "true" nor "false").
Util.toBoolean(Object, boolean).- Parameters:
request- HttpServletRequest from which parameter must be read, must not be nullparameterName- name of the HTTP parameter from which value will be read, must not be nulldefaultValue- the default value to use if parameter is missing or invalid- Returns:
- a boolean value extracted from the value of the HTTP parameter if any, or the default value if parameter was missing or invalid
-
getIntParameter
public static int getIntParameter(javax.servlet.http.HttpServletRequest request, String parameterName, int defaultValue) Retrieve an integer value from specified HTTP request parameter.- Parameters:
request- HttpServletRequest from which parameter must be read, must not be nullparameterName- name of the HTTP parameter from which value will be read, must not be nulldefaultValue- the default value to use if parameter is missing or invalid- Returns:
- an integer value extracted from the value of the HTTP parameter if any, or the default value if parameter was missing or invalid
-
getLongParameter
public static long getLongParameter(javax.servlet.http.HttpServletRequest request, String parameterName, long defaultValue) Retrieve a long value from specified HTTP request parameter.- Parameters:
request- HttpServletRequest from which parameter must be read, must not be nullparameterName- name of the HTTP parameter from which value will be read, must not be nulldefaultValue- the default value to use if parameter is missing, empty or invalid- Returns:
- a long value extracted from the value of the HTTP parameter if any, or the default value if parameter was missing, empty or invalid
-
getDoubleParameter
public static double getDoubleParameter(javax.servlet.http.HttpServletRequest request, String parameterName, double defaultValue) Retrieve a double value from specified HTTP request parameter.- Parameters:
request- HttpServletRequest from which parameter must be read, must not be nullparameterName- name of the HTTP parameter from which value will be read, must not be nulldefaultValue- the default value to use if parameter is missing, empty or invalid- Returns:
- a double value extracted from the value of the HTTP parameter if any, or the default value if parameter was missing, empty or invalid
-
getDateTimeParameter
public static Date getDateTimeParameter(javax.servlet.http.HttpServletRequest request, String parameterName, String dateLanguage, Date defaultValue) Retrieve a Date (date and time) value from specified HTTP request parameter.The parameter will be parsed using date format specified in property
date-time-formatof the specified language.- Parameters:
request- HttpServletRequest from which parameter must be read, must not be nullparameterName- name of the HTTP parameter from which value will be parsed, must not be nulldateLanguage- the language in which the received parameter will be parseddefaultValue- the default value to use if parameter is missing, empty or invalid- Returns:
- a Date value extracted from the value of the HTTP parameter if any, or the default value if parameter was missing, empty or invalid
- See Also:
-
getDateParameter
public static Date getDateParameter(javax.servlet.http.HttpServletRequest request, String parameterName, String dateLanguage, Date defaultValue) Retrieve a Date (date only) value from specified HTTP request parameter.The parameter will be parsed using date format specified in property
date-formatof the specified language.- Parameters:
request- HttpServletRequest from which parameter must be read, must not be nullparameterName- name of the HTTP parameter from which value will be parsed, must not be nulldateLanguage- the language in which the received parameter will be parseddefaultValue- the default value to use if parameter is missing, empty or invalid- Returns:
- a Date value extracted from the value of the HTTP parameter if any, or the default value if parameter was missing, empty or invalid
- See Also:
-
getDateParameter
@Deprecated(forRemoval=true) public static Date getDateParameter(javax.servlet.http.HttpServletRequest request, String parameterName, DateFormat dateFormat, Date defaultValue) Deprecated, for removal: This API element is subject to removal in a future version.Retrieve a Date value from specified HTTP request parameter.The parameter will be parsed using the specified date format
- Parameters:
request- HttpServletRequest from which parameter must be read, must not be nullparameterName- name of the HTTP parameter from which value will be parsed, must not be nulldateFormat- the DateFormat to use to parse the date parameter, must not be nulldefaultValue- the default value to use if parameter is missing, empty or invalid- Returns:
- a Date value extracted from the value of the HTTP parameter if any, or the default value if parameter was missing, empty or invalid
- See Also:
-
parseDate
Parses a date string using either legacy or ISO 8601 formats.- Parameters:
dateStr- the input date string to parselang- the optional language code ("en", "fr", ...) for legacy parsing- Returns:
- a
Dateobject if parsing succeeds; null otherwise
-
getStringEnumParameter
public static String getStringEnumParameter(javax.servlet.http.HttpServletRequest request, String parameterName, String defaultValue, String... possibleValues) Retrieve a String value from specified HTTP request parameter.The parameter value must match one of the possible value specified, otherwise default value is used.
Example, read the "align" parameter expecting only values from authorized HTML table align :
getStringEnumParameter(request, "align", "left", new String[] { "left", "center", "right" });Verification is case sensitive.- Parameters:
request- HttpServletRequest from which parameter must be read, must not be nullparameterName- name of the HTTP parameter from which value will be read, must not be nulldefaultValue- the default value to use if parameter is missing or invalidpossibleValues- the values authorized, must not be null- Returns:
- a String value, or the default value if parameter was missing or invalid (did not match any possible value)
-
getAlphaNumParameter
public static String getAlphaNumParameter(javax.servlet.http.HttpServletRequest request, String parameterName, String defaultValue) Retrieve a String value from specified HTTP request parameter.The parameter value must match the alpha numeric regular expression
ALPHANUM_REGEX.- Parameters:
request- HttpServletRequest from which parameter must be read, must not be nullparameterName- name of the HTTP parameter from which value will be read, must not be nulldefaultValue- the default value to use if parameter is missing or invalid- Returns:
- a String value, or the default value if parameter was missing or invalid (did not match regex)
-
getDataIdParameter
public static String getDataIdParameter(javax.servlet.http.HttpServletRequest request, String parameterName) Retrieve a Data id from parameter.Contrary to most
get*Parametermethod in HttpUtil, this method returns an empty string if parameter value was missing, empty or invalid.Beware that this method will NOT check that the id match an existing or valid data.
Example :
In Java : String id = HttpUtil.getDataIdParameter(request, "id"); In JSP : <input name="id" value="<%= getDataIdParameter("id") %>"/>This method is the same as doing :String id = HttpUtil.getStringParameter(request, parameterName, "", HttpUtil.DATAID_REGEX);
- Parameters:
request- HttpServletRequest from which parameter must be read, must not be nullparameterName- the name of the HTTP parameter from which data id will be retrieved, must not be null- Returns:
- an id, or an empty string if parameter was missing, empty or invalid (never returns null)
-
getStringParameter
public static String getStringParameter(javax.servlet.http.HttpServletRequest request, String parameterName, String defaultValue, String regex) Retrieve a String value from specified HTTP request parameter.The parameter value must match the specified regular expression.
You are encouraged to use predefined constants for regular expression :
ALPHANUM_REGEXfor alpha numeric characters (egFooBar_42)CLASSNAME_REGEXfor Java class names (egcom.jalios.jcms.Content)PROPERTYNAME_REGEXfor JCMS property key (egchannel.data-write.enabled)TEMPLATEUSAGE_REGEXfor JCMS template usage name (egbox,full,front,query)
- Parameters:
request- HttpServletRequest from which parameter must be read, must not be nullparameterName- name of the HTTP parameter from which value will be read, must not be nulldefaultValue- the default value to use if parameter is missing or invalidregex- the regular expression the string is expected to match, must not be null- Returns:
- a String value, or the default value if parameter was missing or invalid (did not match regex)
-
validateString
Validate a String value against specified regular expression.You are encouraged to use predefined constants for regular expression :
ALPHANUM_REGEXfor alpha numeric characters (egFooBar_42)CLASSNAME_REGEXfor Java class names (egcom.jalios.jcms.Content)PROPERTYNAME_REGEXfor JCMS property key (egchannel.data-write.enabled)TEMPLATEUSAGE_REGEXfor JCMS template usage name (egbox,full,front,query)
- Parameters:
value- value to validateregex- the regular expression the string is expected to matchn, must not be null- Returns:
- a String value, or null if specified value was null or invalid (did not match regex)
-
getStringParameterValues
public static String[] getStringParameterValues(javax.servlet.http.HttpServletRequest request, String parameterName, String regex) Retrieve array of String values from specified HTTP request parameter.The parameter values must match the specified regular expression.
You are encouraged to use predefined constants for regular expression :
ALPHANUM_REGEXfor alpha numeric characters (egFooBar_42)CLASSNAME_REGEXfor Java class names (egcom.jalios.jcms.Content)PROPERTYNAME_REGEXfor JCMS property key (egchannel.data-write.enabled)TEMPLATEUSAGE_REGEXfor JCMS template usage name (egbox,full,front,query)
- Parameters:
request- HttpServletRequest from which parameter must be read, must not be nullparameterName- name of the HTTP parameter from which value will be read, must not be nullregex- the regular expression strings are expected to match, must not be null- Returns:
- an array of String values, null if parameter was missing, empty or partial array when all or some values were invalid (did not match regex)
-
validateStringValues
Validate each value in the specified array of String values against specified regular expression.You are encouraged to use predefined constants for regular expression :
ALPHANUM_REGEXfor alpha numeric characters (egFooBar_42)CLASSNAME_REGEXfor Java class names (egcom.jalios.jcms.Content)PROPERTYNAME_REGEXfor JCMS property key (egchannel.data-write.enabled)TEMPLATEUSAGE_REGEXfor JCMS template usage name (egbox,full,front,query)
- Parameters:
values- the values to validateregex- the regular expression strings are expected to match, must not be null- Returns:
- an array of String values, null if specified values array was null. Returns an empty or partial array when all or some values were invalid (did not match regex)
-
getUntrustedStringParameter
public static String getUntrustedStringParameter(javax.servlet.http.HttpServletRequest request, String parameterName, String defaultValue) Retrieve any String value from the specified HTTP request parameter.This method should be AVOIDED AT ALL COST, and used only on last restort, make sure you PROPERLY ENCODE the returned value in the output..
- Parameters:
request- HttpServletRequest from which parameter must be read, must not be nullparameterName- name of the HTTP parameter from which value will be read, must not be nulldefaultValue- the default value to use if parameter is missing- Returns:
- a String value, or the default value if parameter was missing or an empty string
-
addCookie
public static void addCookie(javax.servlet.http.HttpServletResponse response, javax.servlet.http.Cookie cookie) Add a cookie to the response.This method provides the following security check :
- Ensure that there are no encoded or illegal characters in the cookie's name and value (if invalid character are used, cookie is not added to response).
Authorized character can be configured in properties file using following properties :channel.security.Validator.HTTPCookieName: channel.security.Validator.HTTPCookieValue:
- Sets the secure and HttpOnly flags on the cookie according to properties configuration.
channel.security.HttpUtilities.ForceHttpOnlyCookies: true channel.security.HttpUtilities.ForceSecureCookies: true
- Parameters:
response- the HttpServletResponse in which to send the cookiecookie- the cookie to send in the response
- Ensure that there are no encoded or illegal characters in the cookie's name and value (if invalid character are used, cookie is not added to response).
-
addHeader
public static void addHeader(javax.servlet.http.HttpServletResponse response, String name, String value) Add a header to the response after ensuring that there are no encoded or illegal characters in the name and name and value. This implementation follows the following recommendation: "A recipient MAY replace any linear white space with a single SP before interpreting the field value or forwarding the message downstream." http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2- Parameters:
response- the HttpServletResponse in which HTTP header should be addedname- the HTTP header name to addvalue- the HTTP header value to add- Since:
- jcms-10.0.0 / JCMS-5568
-
getCSRFToken
Retrieve the value of CSRF token (both session & member) for the current request.- Parameters:
request- the curren HttpServletRequest- Returns:
- the token value or an empty string, never return null
- Since:
- jcms-7.0.4 jcms-7.1.1
-
initializeCSRFToken
public static void initializeCSRFToken(javax.servlet.http.HttpSession session) Initialize a new CSRF Token for the current session (if any)- Parameters:
session- the HttpSession in which CSRF token is added
-
getCurrentCSRFToken
Retrieve the current valid CSRF Token expected on critical requests of the current session.- Parameters:
session- the current HttpSession- Returns:
- the expected CSRF token value
-
getCurrentCSRFToken
Retrieve the current valid CSRF Token expected on critical requests of the current session.- Parameters:
request- the curren HttpServletRequest- Returns:
- the expected CSRF token value
-
isCSRFMemberTokenAllowed
public static boolean isCSRFMemberTokenAllowed()Check if CSRF token should be allowed through different session in order to allow a submition after session expiration.Initialized from property
channel.security.csrf.allow-token-through-sessionIf enabled, security is decreased as it allows more time for an attacker to retrieve the token, but usability increase as the end user is allowed to submit a form after session expiration.
- Returns:
- true if CSRF prevention is enabled, false otherwise
-
getCSRFMemberTokenMaxAge
public static long getCSRFMemberTokenMaxAge()Retrieve the duration in milliseconds above which a member token is considered invalid.Initialized from property
channel.security.csrf.member-token-max-age- Returns:
- a duration in milliseconds
-
initializeMemberCSRFToken
public static void initializeMemberCSRFToken(Member member, javax.servlet.http.HttpServletRequest request) Initialize the CSRF Token for the specified member from the current CSRF token of the request (if any)- Parameters:
member- the logged Memberrequest- the current HttpServletRequest
-
clearMemberCSRFToken
Remove CSRF token of the specified member- Parameters:
member- the member for which CSRF token should be removed
-
getCurrentMemberCSRFToken
Retrieve the current valid CSRF Token expected on critical requests of the specified member.This method must be used only if "token through session" option has been enabled.
- Parameters:
member- the current Member- Returns:
- the expected CSRF token value, or null if none could be found
- See Also:
-
checkCSRF
public static boolean checkCSRF(javax.servlet.http.HttpServletRequest request) Check if the specified request is valid against CSRF attack.- Parameters:
request- the HttpServletRequest to validate- Returns:
- true if the request is safe (or null), false if the request cannot be guaranteed for safety
-
getUrlWithCSRFToken
public static String getUrlWithCSRFToken(String url, javax.servlet.http.HttpServletRequest request, boolean escapeAmpersand) Adds the current CSRF token to the specified URL and returns it.If CSRF is disable, URL is returned as is.
- Parameters:
url- the URL to completerequest- the current request used to find the current CSRF tokenescapeAmpersand- will use "&" if true, "&" if false- Returns:
- a modified URL with the added CSRF token, or the unchanged specified URL if CSRF is disabled
-
getJsonParameterFromRequest
Returns a String (json format) representing all parameters in the specified request.- Parameters:
request- theHttpServletRequest- Returns:
- a String (json format) representing all parameters in the request, or an empty string if the request in parameter is null or the JSON conversion failed.
- Since:
- jcms-8.0.1
-
accept
Check if the specified mime type can be understood by the client who emitted the specified request as specified by its Accept HTTP header.This methods check the
"Accept"header to ensure it match the specified mime type.- Parameters:
request- the request in which the Accept header is being verifiedmimeType- a mime type, for example"text/html"- Returns:
- true if client accept mime type, false in any other case (invalid request or mime type specified, missing Accept Header, Accept Header does not match mimeType)
- Since:
- jcms-10.0.0 (for JCMS-5648 and JCMS-5942)
-
getRemoteIpAddr
Get the remote IP of the request (with usage ofXFORWARDheader or attribute)- Parameters:
request- theHttpServletRequest- Returns:
- the remote IP
-
getXForwardedFor
Get the x-forwarded for element of the request (with usage ofXFORWARDheader or attribute)- Parameters:
request- theHttpServletRequest- Returns:
- the remote IP from
XFORWARDheader or attribute
-
getDateParameter(HttpServletRequest, String, String, Date)orgetDateTimeParameter(HttpServletRequest, String, String, Date)