Class ClickUtils
- java.lang.Object
-
- org.openidentityplatform.openam.click.util.ClickUtils
-
public class ClickUtils extends Object
Provides miscellaneous Form, String and Stream utility methods.
-
-
Field Summary
Fields Modifier and Type Field Description static StringDEFAULT_APP_CONFIGThe default Click configuration filename: "/WEB-INF/click.xml".static StringENABLE_RESOURCE_VERSIONThe resourceversioningrequest attribute: key:enable-resource-version.static StringRESOURCE_VERSION_INDICATORThe static web resource version number indicator string.static StringVERSION_INDICATOR_SEPThe version indicator separator string.
-
Constructor Summary
Constructors Constructor Description ClickUtils()
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static voidautoPostRedirect(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, String target, Map<?,?> params, boolean compress)Perform an auto post redirect to the specified target using the given response.static voidbind(AbstractLink link)A helper method that binds the submitted request value to the Link's value.static voidbind(Container container)A helper method that binds the submitted request values of all Fields and Links inside the given container or child containers.static voidbind(Field field)A helper method that binds the submitted request value to the Field's value.static booleanbindAndValidate(Container container)A helper method that binds and validates the submitted request values of all Fields and Links inside the given container or child containers.static booleanbindAndValidate(Field field)A helper method that binds and validates the Field's submitted request value.static booleanbindAndValidate(Form form)* A helper method that binds and validates the submitted request values of all Fields and Links inside the given Form or child containers.static DocumentbuildDocument(InputStream inputStream)Return a new XML Document for the given input stream.static DocumentbuildDocument(InputStream inputStream, EntityResolver entityResolver)Return a new XML Document for the given input stream and XML entity resolver.static booleancanBind(org.openidentityplatform.openam.click.Control control, org.openidentityplatform.openam.click.Context context)Return true if the given control's request value can be bound, false otherwise.static ClassclassForName(String classname)Returns theClassobject associated with the class or interface with the given string name, using the current Thread context class loader.static voidclose(Closeable closeable)Close the given closeable (Reader, Writer, Stream) and ignore any exceptions thrown.static voidcopyFormToObject(Form form, Object object, boolean debug)Populate the given object's attributes with the Form's field values.static voidcopyObjectToForm(Object object, Form form, boolean debug)Populate the given Form field values with the object's attributes.static Map<String,Object>createTemplateModel(org.openidentityplatform.openam.click.Page page, org.openidentityplatform.openam.click.Context context)Creates a template model of key/value pairs which can be used by template engines such as Velocity and Freemarker.static Objectdecode(String string)Return an object from theencode(Object)string.static String[]decodePasswordCookie(String cookieVal, int xorMask)Decodes a cookie string containing a username and password.static String[]decodePasswordCookie(String cookieVal, String encoding, int xorMask)Decodes a cookie string containing a username and password.static StringdecodeURL(Object value)URL decode the specified value using the "UTF-8" encoding scheme.static voiddeployFile(jakarta.servlet.ServletContext servletContext, String resource, String targetDir)Deploy the specified classpath resource to the given target directory under the web application root directory.static voiddeployFileList(jakarta.servlet.ServletContext servletContext, Class<? extends org.openidentityplatform.openam.click.Control> controlClass, String targetDir)Deploys required files (from a file list) for a control that repsects a specific convention.static voiddeployFiles(jakarta.servlet.ServletContext servletContext, String[] resources, String targetDir)Deploy the specified classpath resources to the given target directory under the web application root directory.static Stringencode(Object object)Return an encoded version of theSerializableobject.static StringencodePasswordCookie(String username, String password, int xorMask)Builds a cookie string containing a username and password.static StringencodePasswordCookie(String username, String password, String encoding, int xorMask)Builds a cookie string containing a username and password, using offsets to customize the encoding.static StringencodeUrl(Object object, org.openidentityplatform.openam.click.Context context)Return an encoded URL value for the given object using the context request character encoding or "UTF-8" if the request character encoding is not specified.static StringencodeURL(Object value)URL encode the specified value using the "UTF-8" encoding scheme.static Stringescape(String value)Return an escaped string for the given string value.static StringescapeHtml(String value)Return a HTML escaped string for the given string value.static StringgetApplicationResourceVersionIndicator()If resource versioning is active this method will return the application version indicator for static web resources (eg JavaScript and Css) otherwise this method will return an empty string.static StringgetApplicationVersion()Return the web application version string.static ResourceBundlegetBundle(String baseName)Return a resource bundle using the specified base name.static ResourceBundlegetBundle(String baseName, Locale locale)Return a resource bundle using the specified base name and locale.static ElementgetChild(Element parent, String name)Return the first XML child Element for the given parent Element and child Element name.static List<Element>getChildren(Element parent, String name)Return the list of XML child Element elements with the given name from the given parent Element.static InputStreamgetClickConfig(jakarta.servlet.ServletContext servletContext)Return the InputStream for the Click configuration fileclick.xml.static StringgetClickVersion()Return the Click Framework version string.static ConfigServicegetConfigService(jakarta.servlet.ServletContext servletContext)Return the application configuration service instance from the given servlet context.static jakarta.servlet.http.CookiegetCookie(jakarta.servlet.http.HttpServletRequest request, String name)Returns the specified Cookie object, or null if the cookie does not exist.static StringgetCookieValue(jakarta.servlet.http.HttpServletRequest request, String name)Returns the value of the specified cookie as a String.static StringgetCssSelector(org.openidentityplatform.openam.click.Control control)Return the given control CSS selector or null if no selector can be found.static List<Field>getFormFields(Form form)Return the list of Fields for the given Form, including any Fields contained in child containers.static LogServicegetLogService()Return the application LogService instance using thread local Context to perform the lookup.static StringgetMimeType(String value)Return the mime-type or content-type for the given filename/extension.static StringgetParentMessage(org.openidentityplatform.openam.click.Control control, String name)Return the given control's top level parent's localized message for the specified name.static Map<String,String>getParentMessages(org.openidentityplatform.openam.click.Control control)Return the given control's top level parent's localized messages Map.static org.openidentityplatform.openam.click.PagegetParentPage(org.openidentityplatform.openam.click.Control control)Get the parent page of the given control or null if the control has no parent.static Map<String,Object>getRequestParameterMap(jakarta.servlet.http.HttpServletRequest request)Return an ordered map of request parameters from the given request.static StringgetRequestURI(jakarta.servlet.http.HttpServletRequest request)Return the requestURI from the request.static URLgetResource(String name, Class<?> aClass)Finds a resource with a given name.static InputStreamgetResourceAsStream(String name, Class<?> aClass)Finds a resource with a given name.static StringgetResourcePath(jakarta.servlet.http.HttpServletRequest request)Return the page resource path from the request.static StringgetResourceVersionIndicator(org.openidentityplatform.openam.click.Context context)Return Click's version indicator for static web resources (eg css, js and image files) if resource versioning is active, otherwise this method will return an empty string.static booleanhasRequestParameter(org.openidentityplatform.openam.click.Control control)Return true if the control has a submitted request value, false otherwise.static voidinvalidateCookie(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, String cookieName)Invalidate the specified cookie and delete it from the response object.static voidinvalidateCookie(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, String cookieName, String path)Invalidate the specified cookie and delete it from the response object.static org.openidentityplatform.openam.click.ActionResultinvokeAction(Object target, String method)Invoke the named method on the given target and return the Object result.static booleaninvokeListener(Object listener, String method)Invoke the named method on the given object and return the boolean result.static booleanisAjaxRequest(jakarta.servlet.http.HttpServletRequest request)Return true is this is an Ajax request, false otherwise.static booleanisEnableResourceVersion(org.openidentityplatform.openam.click.Context context)Return true if static web content resource versioning is enabled.static booleanisMultipartRequest(jakarta.servlet.http.HttpServletRequest request)Return true if the request is a multi-part content type POST request.static booleanisResourcesDeployable(jakarta.servlet.ServletContext servletContext)Returns true if Click resources (JavaScript, CSS, images etc) packaged in jars can be deployed to the root directory of the webapp, false otherwise.static StringlimitLength(String value, int maxlength)Return the value string limited to maxlength characters.static StringlimitLength(String value, int maxlength, String suffix)Return the value string limited to maxlength characters.static voidremoveState(org.apache.click.Stateful control, String controlName, org.openidentityplatform.openam.click.Context context)Remove the control state from the session for the given stateful control, control name and request context.static voidrestoreState(org.apache.click.Stateful control, String controlName, org.openidentityplatform.openam.click.Context context)Restore the control state from the session for the given stateful control, control name and request context.static voidsaveState(org.apache.click.Stateful control, String controlName, org.openidentityplatform.openam.click.Context context)Save the control state in the session for the given stateful control, control name and request context.static voidsetApplicationVersion(String applicationVersion)Set the web application version string.static jakarta.servlet.http.CookiesetCookie(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, String name, String value, int maxAge, String path)Sets the given cookie values in the servlet response.static StringtoGetterName(String property)Return the getter method name for the given property name.static StringtoIsGetterName(String property)Return the is getter method name for the given property name.static StringtoLabel(String name)Return a field label string from the given field name.static StringtoMD5Hash(String plaintext)Return an 32 char MD5 encoded string from the given plain text.static StringtoName(String label)Return a field name string from the given field label.static StringtoSetterName(String property)Return the setter method name for the given property name.
-
-
-
Field Detail
-
ENABLE_RESOURCE_VERSION
public static final String ENABLE_RESOURCE_VERSION
The resourceversioningrequest attribute: key:enable-resource-version.If this attribute is set to
trueand Click is running inproductionorprofilemode, Click resources returned fromControl.getHeadElements()will have aversion indicatoradded to their path.- See Also:
Control.getHeadElements(),getResourceVersionIndicator(Context), Constant Field Values
-
DEFAULT_APP_CONFIG
public static final String DEFAULT_APP_CONFIG
The default Click configuration filename: "/WEB-INF/click.xml".- See Also:
- Constant Field Values
-
VERSION_INDICATOR_SEP
public static final String VERSION_INDICATOR_SEP
The version indicator separator string.- See Also:
- Constant Field Values
-
RESOURCE_VERSION_INDICATOR
public static final String RESOURCE_VERSION_INDICATOR
The static web resource version number indicator string.
-
-
Method Detail
-
autoPostRedirect
public static void autoPostRedirect(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, String target, Map<?,?> params, boolean compress)Perform an auto post redirect to the specified target using the given response. If the params Map is defined then the form will post these values as name value pairs. If the compress value is true, this method will attempt to gzip compress the response content if requesting browser accepts "gzip" encoding.Once this method has returned you should not attempt to write to the servlet response.
- Parameters:
request- the servlet requestresponse- the servlet responsetarget- the target URL to send the auto post redirect toparams- the map of parameter values to postcompress- the flag to specify whether to attempt gzip compression of the response content
-
bind
public static void bind(Field field)
A helper method that binds the submitted request value to the Field's value. Since Field values are only bound during the"onProcess"event, this method can be used to bind a submitted Field value during the"onInit"event, which occurs before the"onProcess"event.This is especially useful for dynamic Form and Page behavior where Field values are inspected during the
"onInit"event to add or remove specific Fields.Please note: this method won't bind disabled fields, unless the field has an incoming request parameter matching its name. If an incoming request parameter is present, this method will switch off the Field's disabled property.
This method delegates to
canBind(org.openidentityplatform.openam.click.Control, org.openidentityplatform.openam.click.Context)to check if the Field value can be bound.public void onInit() { Form form = new Form("form"); Select select = new Select("select"); select.setAttribute("onchange", "Click.submit(form, false)"); // Bind the select Field request value ClickUtils.bind(select); if (select.getValue() == COMPANY) { form.add(new TextField("companyName")); } else { form.add(new TextField("fullname")); form.add(new TextField("age")); } }- Parameters:
field- the Field to bind
-
bind
public static void bind(AbstractLink link)
A helper method that binds the submitted request value to the Link's value. Seebind(org.openidentityplatform.openam.click.control.Field)for a detailed description.This method delegates to
canBind(org.openidentityplatform.openam.click.Control, org.openidentityplatform.openam.click.Context)to check if the Link value can be bound.- Parameters:
link- the AbstractLink to bind
-
bind
public static void bind(Container container)
A helper method that binds the submitted request values of all Fields and Links inside the given container or child containers. Seebind(org.openidentityplatform.openam.click.control.Field)for a detailed description.This method delegates to
canBind(org.openidentityplatform.openam.click.Control, org.openidentityplatform.openam.click.Context)to check if the Container Fields and Links can be bound.Below is an example to bind Form Field's during the onInit event:
public void onInit() { Form form = new Form("form"); Checkbox commentChk = new Checkbox("comment"); Select select = new Select("select"); select.setAttribute("onchange", "Click.submit(form, false)"); // Bind all Form Field request values ClickUtils.bind(form); if (select.getValue() == COMPANY) { form.add(new TextField("companyName")); } else { form.add(new TextField("fullname")); form.add(new TextField("age")); } if (commentChk.isChecked()) { form.add(new TextArea("feedback")); } }- Parameters:
container- the container which Fields and Links to bind
-
bindAndValidate
public static boolean bindAndValidate(Field field)
A helper method that binds and validates the Field's submitted request value. This method will return true if the validation succeeds, false otherwise. Seebind(org.openidentityplatform.openam.click.control.Field)for a detailed description.This method delegates to
canBind(org.openidentityplatform.openam.click.Control, org.openidentityplatform.openam.click.Context)to check if the Field value can be bound and validated.Please note: this method won't bind and validate disabled fields, unless the field has an incoming request parameter matching its name. If an incoming request parameter is present, this method will switch off the Field's disabled property.
public void onInit() { Form form = new Form("form"); Select select = new Select("select", true); select.addOption(Option.EMPTY_OPTION); select.setAttribute("onchange", "Click.submit(form, false)"); // Bind the Field request value and validate it before continuing if (ClickUtils.bindAndValidate(select)) { if (select.getValue() == COMPANY) { form.add(new TextField("companyName")); } else { form.add(new TextField("fullname")); form.add(new TextField("age")); } } }- Parameters:
field- the Field to bind and validate- Returns:
- true if field was bound and valid, or false otherwise
-
bindAndValidate
public static boolean bindAndValidate(Container container)
A helper method that binds and validates the submitted request values of all Fields and Links inside the given container or child containers. This method will return true if the validation succeeds, false otherwise.See
bindAndValidate(org.openidentityplatform.openam.click.control.Form)for a detailed description.- Parameters:
container- the container which Fields and Links to bind and validate- Returns:
- true if all Fields are valid, false otherwise
-
bindAndValidate
public static boolean bindAndValidate(Form form)
* A helper method that binds and validates the submitted request values of all Fields and Links inside the given Form or child containers. Note, the Form itself is also validated.This method will return true if the validation succeeds, false otherwise. See
bind(org.openidentityplatform.openam.click.control.Field)for a detailed description.This method delegates to
canBind(org.openidentityplatform.openam.click.Control, org.openidentityplatform.openam.click.Context)to check if the Form Fields and Links can be bound and validated.public void onInit() { Form form = new Form("form"); Checkbox commentChk = new Checkbox("comment"); Select select = new Select("select", true); select.addOption(Option.EMPTY_OPTION); select.setAttribute("onchange", "Click.submit(form, false)"); // Bind all Form field request values and validate it before continuing if (ClickUtils.bindAndValidate(form)) { if (select.getValue() == COMPANY) { form.add(new TextField("companyName")); } else { form.add(new TextField("fullname")); form.add(new TextField("age")); } if (commentChk.isChecked()) { form.add(new TextArea("feedback")); } } }- Parameters:
form- the form which Fields and Links to bind and validate- Returns:
- true if the form, it's fields and links was bound and valid, false otherwise
-
buildDocument
public static Document buildDocument(InputStream inputStream)
Return a new XML Document for the given input stream.- Parameters:
inputStream- the input stream- Returns:
- new XML Document
- Throws:
RuntimeException- if a parsing error occurs
-
buildDocument
public static Document buildDocument(InputStream inputStream, EntityResolver entityResolver)
Return a new XML Document for the given input stream and XML entity resolver.- Parameters:
inputStream- the input streamentityResolver- the XML entity resolver- Returns:
- new XML Document
- Throws:
RuntimeException- if a parsing error occurs
-
canBind
public static boolean canBind(org.openidentityplatform.openam.click.Control control, org.openidentityplatform.openam.click.Context context)Return true if the given control's request value can be bound, false otherwise.The following algorithm is used to determine if the Control can be bound to a request value or not.
- return false if the request is a forward.
See
Context.isForward() - return true if the request is an Ajax request.
See
Context.isAjaxRequest() - return true if the control has no parent Form
- return true if the control's parent Form was submitted, false otherwise.
See
Form.isFormSubmission()
- Parameters:
control- the control to check if it can be bound or notcontext- the request context- Returns:
- true if the given control request value be bound, false otherwise
- return false if the request is a forward.
See
-
classForName
public static Class classForName(String classname) throws ClassNotFoundException
Returns theClassobject associated with the class or interface with the given string name, using the current Thread context class loader.- Parameters:
classname- the name of the class to load- Returns:
- the
Classobject - Throws:
ClassNotFoundException- if the class cannot be located
-
close
public static void close(Closeable closeable)
Close the given closeable (Reader, Writer, Stream) and ignore any exceptions thrown.- Parameters:
closeable- the closeable (Reader, Writer, Stream) to close.
-
createTemplateModel
public static Map<String,Object> createTemplateModel(org.openidentityplatform.openam.click.Page page, org.openidentityplatform.openam.click.Context context)
Creates a template model of key/value pairs which can be used by template engines such as Velocity and Freemarker.The following objects will be added to the model:
- the Page
modelMap key/value pairs - context - the Servlet context path, e.g. /mycorp
- format - the Page
Formatobject for formatting the display of objects. - messages - the
MessagesMapadaptor for thePage.getMessages()method. - path - the
pathof thepagetemplate. - request - the page
HttpServletRequestobject. - response - the page
HttpServletResponseobject. - session - the
SessionMapadaptor for the usersHttpSession.
- Parameters:
page- the page to populate the template model fromcontext- the request context- Returns:
- a template model as a map
- the Page
-
invalidateCookie
public static void invalidateCookie(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, String cookieName, String path)Invalidate the specified cookie and delete it from the response object.This method was derived from Atlassian
CookieUtilsmethod of the same name, release under the BSD License.- Parameters:
request- the servlet requestresponse- the servlet responsecookieName- The name of the cookie you want to deletepath- of the path the cookie you want to delete
-
isAjaxRequest
public static boolean isAjaxRequest(jakarta.servlet.http.HttpServletRequest request)
Return true is this is an Ajax request, false otherwise.An Ajax request is identified by the presence of the request
headeror requestparameter: "X-Requested-With". "X-Requested-With" is the de-facto standard identifier used by Ajax libraries.Note: incoming requests that contains a request
parameter"X-Requested-With" will result in this method returning true, even though the request itself was not initiated through aXmlHttpRequestobject. This allows one to programmatically enable Ajax requests. A common use case for this feature is when uploading files through an IFrame element. By specifying "X-Requested-With" as a request parameter the IFrame request will be handled like a normal Ajax request.- Parameters:
request- the servlet request- Returns:
- true if this is an Ajax request, false otherwise
-
isMultipartRequest
public static boolean isMultipartRequest(jakarta.servlet.http.HttpServletRequest request)
Return true if the request is a multi-part content type POST request.- Parameters:
request- the page servlet request- Returns:
- true if the request is a multi-part content type POST request
-
invalidateCookie
public static void invalidateCookie(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, String cookieName)Invalidate the specified cookie and delete it from the response object. Deletes only cookies mapped against the root "/" path. Otherwise useinvalidateCookie(HttpServletRequest, HttpServletResponse, String, String)This method was derived from Atlassian
CookieUtilsmethod of the same name, release under the BSD License.- Parameters:
request- the servlet requestresponse- the servlet responsecookieName- The name of the cookie you want to delete.- See Also:
invalidateCookie(HttpServletRequest, HttpServletResponse, String, String)
-
getBundle
public static ResourceBundle getBundle(String baseName)
Return a resource bundle using the specified base name.- Parameters:
baseName- the base name of the resource bundle, a fully qualified class name- Returns:
- a resource bundle for the given base name
- Throws:
MissingResourceException- if no resource bundle for the specified base name can be found
-
getBundle
public static ResourceBundle getBundle(String baseName, Locale locale)
Return a resource bundle using the specified base name and locale.- Parameters:
baseName- the base name of the resource bundle, a fully qualified class namelocale- the locale for which a resource bundle is desired- Returns:
- a resource bundle for the given base name and locale
- Throws:
MissingResourceException- if no resource bundle for the specified base name can be found
-
getChild
public static Element getChild(Element parent, String name)
Return the first XML child Element for the given parent Element and child Element name.- Parameters:
parent- the parent element to get the child fromname- the name of the child element- Returns:
- the first child element for the given name and parent
-
getChildren
public static List<Element> getChildren(Element parent, String name)
Return the list of XML child Element elements with the given name from the given parent Element.- Parameters:
parent- the parent element to get the child fromname- the name of the child element- Returns:
- the list of XML child elements for the given name
-
getClickConfig
public static InputStream getClickConfig(jakarta.servlet.ServletContext servletContext)
Return the InputStream for the Click configuration fileclick.xml. This method will first lookup theclick.xmlunder the applicationsWEB-INFdirectory, and then if not found it will attempt to find the configuration file on the classpath root.- Parameters:
servletContext- the servlet context to obtain the Click configuration from- Returns:
- the InputStream for the Click configuration file
- Throws:
RuntimeException- if the resource could not be found
-
getConfigService
public static ConfigService getConfigService(jakarta.servlet.ServletContext servletContext)
Return the application configuration service instance from the given servlet context.- Parameters:
servletContext- the servlet context to get the config service instance- Returns:
- the application config service instance
-
getCookie
public static jakarta.servlet.http.Cookie getCookie(jakarta.servlet.http.HttpServletRequest request, String name)Returns the specified Cookie object, or null if the cookie does not exist.This method was derived from Atlassian
CookieUtilsmethod of the same name, release under the BSD License.- Parameters:
request- the servlet requestname- the name of the cookie- Returns:
- the Cookie object if it exists, otherwise null
-
setCookie
public static jakarta.servlet.http.Cookie setCookie(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, String name, String value, int maxAge, String path)Sets the given cookie values in the servlet response.This will also put the cookie in a list of cookies to send with this request's response (so that in case of a redirect occurring down the chain, the first filter will always try to set this cookie again)
The cookie secure flag is set if the request is secure.
This method was derived from Atlassian
CookieUtilsmethod of the same name, release under the BSD License.- Parameters:
request- the servlet requestresponse- the servlet responsename- the cookie namevalue- the cookie valuemaxAge- the maximum age of the cookie in seconds. A negative value will expire the cookie at the end of the session, while 0 will delete the cookie.path- the cookie path- Returns:
- the Cookie object created and set in the response
-
getCookieValue
public static String getCookieValue(jakarta.servlet.http.HttpServletRequest request, String name)
Returns the value of the specified cookie as a String. If the cookie does not exist, the method returns null.This method was derived from Atlassian
CookieUtilsmethod of the same name, release under the BSD License.- Parameters:
request- the servlet requestname- the name of the cookie- Returns:
- the value of the cookie, or null if the cookie does not exist.
-
getClickVersion
public static String getClickVersion()
Return the Click Framework version string.- Returns:
- the Click Framework version string
-
getApplicationVersion
public static String getApplicationVersion()
Return the web application version string.- Returns:
- the web application version string
-
setApplicationVersion
public static void setApplicationVersion(String applicationVersion)
Set the web application version string.- Parameters:
applicationVersion- the web application version string
-
getResourceVersionIndicator
public static String getResourceVersionIndicator(org.openidentityplatform.openam.click.Context context)
Return Click's version indicator for static web resources (eg css, js and image files) if resource versioning is active, otherwise this method will return an empty string.Click's resource versioning becomes active under the following conditions:
- the
ENABLE_RESOURCE_VERSIONrequest attribute must be set totrue - the application mode must be either "production" or "profile"
"_1.4".- Parameters:
context- the request context- Returns:
- a version indicator for web resources
- the
-
getApplicationResourceVersionIndicator
public static String getApplicationResourceVersionIndicator()
If resource versioning is active this method will return the application version indicator for static web resources (eg JavaScript and Css) otherwise this method will return an empty string.Application resource versioning becomes active under the following conditions:
- the
ENABLE_RESOURCE_VERSIONrequest attribute must be set totrue - the application mode must be either "production" or "profile"
"_1.2".The application version can be set through the static method
setApplicationVersion(java.lang.String).- Returns:
- an application version indicator for web resources
- the
-
getCssSelector
public static String getCssSelector(org.openidentityplatform.openam.click.Control control)
Return the given control CSS selector or null if no selector can be found.Please note: it is highly recommended to set a control's ID attribute when dealing with Ajax requests.
The CSS selector is calculated as follows:
- if control.getId() is set, prepend it with a '#' char
and return the value. An example selector will be:
#field-id - if control.getName() is set do the following:
- if the control is of type
ActionLink, it's "class" attribute selector will be returned. For example:a[class=red]. Please note: if the link class attribute is not set, the class attribute will be set to its name, prefixed with a dash, '-'. For example:a[class=-my-link]. - if the control is not an ActionLink, it is assumed the control
will render its "
name" attribute and the name attribute selector will be returned. For example:input[name=my-button].
- if the control is of type
- otherwise return null.
- Parameters:
control- the control which CSS selector to return- Returns:
- the control CSS selector or null if no selector can be found
- Throws:
IllegalArgumentException- if control is null
- if control.getId() is set, prepend it with a '#' char
and return the value. An example selector will be:
-
copyFormToObject
public static void copyFormToObject(Form form, Object object, boolean debug)
Populate the given object's attributes with the Form's field values.The specified Object can either be a POJO (plain old java object) or a
Map. If a POJO is specified, its attributes are populated from matching form fields. If a map is specified, its key/value pairs are populated from matching form fields.- Parameters:
form- the Form to obtain field values fromobject- the object to populate with field valuesdebug- log debug statements when populating the object
-
copyObjectToForm
public static void copyObjectToForm(Object object, Form form, boolean debug)
Populate the given Form field values with the object's attributes.The specified Object can either be a POJO (plain old java object) or a
Map. If a POJO is specified, its attributes are copied to matching form fields. If a map is specified, its key/value pairs are copied to matching form fields.- Parameters:
object- the object to obtain attribute values fromform- the Form to populatedebug- log debug statements when populating the form
-
deployFile
public static void deployFile(jakarta.servlet.ServletContext servletContext, String resource, String targetDir)Deploy the specified classpath resource to the given target directory under the web application root directory.This method will not override any existing resources found in the target directory.
If an IOException or SecurityException occurs this method will log a warning message.
- Parameters:
servletContext- the web applications servlet contextresource- the classpath resource nametargetDir- the target directory to deploy the resource to
-
deployFiles
public static void deployFiles(jakarta.servlet.ServletContext servletContext, String[] resources, String targetDir)Deploy the specified classpath resources to the given target directory under the web application root directory.- Parameters:
servletContext- the web applications servlet contextresources- the array of classpath resource namestargetDir- the target directory to deploy the resource to
-
deployFileList
public static void deployFileList(jakarta.servlet.ServletContext servletContext, Class<? extends org.openidentityplatform.openam.click.Control> controlClass, String targetDir)Deploys required files (from a file list) for a control that repsects a specific convention.Convention:
There's a descriptor file generated by the
tools/standalone/dev-tasks/ListFilesTask. The files to deploy are all in a subdirectory placed in the same directory with the control. See documentation for more details.Usage:
In your Control simply use the code below, and everything should work automatically.
public void onDeploy(ServletContext servletContext) { ClickUtils.deployFileList(servletContext, HeavyControl.class, "click"); }- Parameters:
servletContext- the web applications servlet contextcontrolClass- the class of the Control that has files for deploymenttargetDir- target directory where to deploy the files to. In most cases this is only the reserved directoryclick
-
encode
public static String encode(Object object) throws IOException
Return an encoded version of theSerializableobject. The object will be serialized, compressed and Base 64 encoded.- Parameters:
object- the object to encode- Returns:
- a serialized, compressed and Base 64 string encoding of the given object
- Throws:
IOException- if an I/O error occursIllegalArgumentException- if the object parameter is null, or if the object is not Serializable
-
decode
public static Object decode(String string) throws ClassNotFoundException, IOException
Return an object from theencode(Object)string.- Parameters:
string- the encoded string- Returns:
- an object from the encoded
- Throws:
ClassNotFoundException- if the class could not be instantiatedIOException- if an data I/O error occurs
-
encodePasswordCookie
public static String encodePasswordCookie(String username, String password, int xorMask)
Builds a cookie string containing a username and password.Note: with open source this is not really secure, but it prevents users from snooping the cookie file of others and by changing the XOR mask and character offsets, you can easily tweak results.
This method was derived from Atlassian
CookieUtilsmethod of the same name, release under the BSD License.- Parameters:
username- the usernamepassword- the passwordxorMask- the XOR mask to encrypt the value with, must be same as as the value used to decrypt the cookie password- Returns:
- String encoding the input parameters, an empty string if one of
the arguments equals
null
-
encodePasswordCookie
public static String encodePasswordCookie(String username, String password, String encoding, int xorMask)
Builds a cookie string containing a username and password, using offsets to customize the encoding.Note: with open source this is not really secure, but it prevents users from snooping the cookie file of others and by changing the XOR mask and character offsets, you can easily tweak results.
This method was derived from Atlassian
CookieUtilsmethod of the same name, release under the BSD License.- Parameters:
username- the usernamepassword- the passwordencoding- a String used to customize cookie encoding (only the first 3 characters are used)xorMask- the XOR mask to encrypt the value with, must be same as as the value used to decrypt the cookie password- Returns:
- String encoding the input parameters, an empty string if one of
the arguments equals
null.
-
decodePasswordCookie
public static String[] decodePasswordCookie(String cookieVal, int xorMask)
Decodes a cookie string containing a username and password.This method was derived from Atlassian
CookieUtilsmethod of the same name, release under the BSD License.- Parameters:
cookieVal- the encoded cookie username and password valuexorMask- the XOR mask to decrypt the value with, must be same as as the value used to encrypt the cookie password- Returns:
- String[] containing the username at index 0 and the password at
index 1, or
{ null, null }if cookieVal equalsnullor the empty string.
-
decodePasswordCookie
public static String[] decodePasswordCookie(String cookieVal, String encoding, int xorMask)
Decodes a cookie string containing a username and password.This method was derived from Atlassian
CookieUtilsmethod of the same name, release under the BSD License.- Parameters:
cookieVal- the encoded cookie username and password valueencoding- a String used to customize cookie encoding (only the first 3 characters are used) - should be the same string you used to encode the cookie!xorMask- the XOR mask to decrypt the value with, must be same as as the value used to encrypt the cookie password- Returns:
- String[] containing the username at index 0 and the password at
index 1, or
{ null, null }if cookieVal equalsnullor the empty string.
-
encodeURL
public static String encodeURL(Object value)
URL encode the specified value using the "UTF-8" encoding scheme.For example
(http://host?name=value with spaces)will become(http://host?name=value+with+spaces).This method uses
URLEncoder.encode(java.lang.String, java.lang.String)internally.- Parameters:
value- the value to encode using "UTF-8"- Returns:
- an encoded URL string
-
decodeURL
public static String decodeURL(Object value)
URL decode the specified value using the "UTF-8" encoding scheme.For example
(http://host?name=value+with+spaces)will become(http://host?name=value with spaces).This method uses
URLDecoder.decode(java.lang.String, java.lang.String)internally.- Parameters:
value- the value to decode using "UTF-8"- Returns:
- an encoded URL string
-
encodeUrl
public static String encodeUrl(Object object, org.openidentityplatform.openam.click.Context context)
Return an encoded URL value for the given object using the context request character encoding or "UTF-8" if the request character encoding is not specified.For example
(http://host?name=value with spaces)will become(http://host?name=value+with+spaces).This method uses
URLEncoder.encode(java.lang.String, java.lang.String)internally.- Parameters:
object- the object value to encode as a URL stringcontext- the context providing the request character encoding- Returns:
- an encoded URL string
-
escapeHtml
public static String escapeHtml(String value)
Return a HTML escaped string for the given string value.- Parameters:
value- the string value to escape- Returns:
- the HTML escaped string value
-
escape
public static String escape(String value)
Return an escaped string for the given string value. The following characters are escaped: <, >, ", ', &.- Parameters:
value- the string value to escape- Returns:
- the escaped string value
-
hasRequestParameter
public static boolean hasRequestParameter(org.openidentityplatform.openam.click.Control control)
Return true if the control has a submitted request value, false otherwise.- Parameters:
control- the control which request parameter to check- Returns:
- true if the control has a submitted request value, false otherwise
-
invokeListener
public static boolean invokeListener(Object listener, String method)
Invoke the named method on the given object and return the boolean result.- Parameters:
listener- the object with the method to invokemethod- the name of the method to invoke- Returns:
- true if the listener method returned true
- See Also:
Control.setListener(Object, String)
-
invokeAction
public static org.openidentityplatform.openam.click.ActionResult invokeAction(Object target, String method)
Invoke the named method on the given target and return the Object result.- Parameters:
target- the target object with the method to invokemethod- the name of the method to invoke- Returns:
- an ActionResult instance
-
isEnableResourceVersion
public static boolean isEnableResourceVersion(org.openidentityplatform.openam.click.Context context)
Return true if static web content resource versioning is enabled.- Parameters:
context- the request context- Returns:
- true if static web content resource versioning is enabled
-
limitLength
public static String limitLength(String value, int maxlength)
Return the value string limited to maxlength characters. If the string gets curtailed, "..." is appended to it.Adapted from Velocity Tools Formatter.
- Parameters:
value- the string value to limit the length ofmaxlength- the maximum string length- Returns:
- a length limited string
-
limitLength
public static String limitLength(String value, int maxlength, String suffix)
Return the value string limited to maxlength characters. If the string gets curtailed and the suffix parameter is appended to it.Adapted from Velocity Tools Formatter.
- Parameters:
value- the string value to limit the length ofmaxlength- the maximum string lengthsuffix- the suffix to append to the length limited string- Returns:
- a length limited string
-
getLogService
public static LogService getLogService()
Return the application LogService instance using thread local Context to perform the lookup.- Returns:
- the application LogService instance
-
getFormFields
public static List<Field> getFormFields(Form form)
Return the list of Fields for the given Form, including any Fields contained in child containers. The list of returned fields will exclude anyButtonorLabelfields.- Parameters:
form- the form to obtain the fields from- Returns:
- the list of contained form fields
-
getMimeType
public static String getMimeType(String value)
Return the mime-type or content-type for the given filename/extension.Example:
// Lookup mimetype for file String mimeType = ClickUtils.getMimeType("hello-world.pdf"); // Lookup mimetype for extension mimeType = ClickUtils.getMimeType("pdf");- Parameters:
value- the filename or extension to obtain the mime-type for- Returns:
- the mime-type for the given filename/extension, or null if not found
-
getParentMessages
public static Map<String,String> getParentMessages(org.openidentityplatform.openam.click.Control control)
Return the given control's top level parent's localized messages Map.This method will walk up to the control's parent page object and return pages messages. If the control's top level parent is a control then the parent's messages map will be returned. If the top level parent is not a Page or Control instance an empty map will be returned.
- Parameters:
control- the control to get the parent messages Map for- Returns:
- the top level parent's Map of localized messages
-
getParentMessage
public static String getParentMessage(org.openidentityplatform.openam.click.Control control, String name)
Return the given control's top level parent's localized message for the specified name.This method will walk up to the control's parent page object and for each parent control found, look for a message of the specified name. A message found in a parent control will override the message of a child control.
Given the following property files:
MyPage.properties
myfield.label=Page
and MyForm.propertiesmyfield.label=Form
and a the following snippet:public MyPage extends Page { public void onInit() { MyForm form = new MyForm("form"); TextField field = new TextField("myfield"); form.add(field); //1. System.out.println(ClickUtils.getParentMessage(field, "myfield.label")); addControl(form); //2. System.out.println(ClickUtils.getParentMessage(field, "myfield.label")); } }The first (1.) println statement above will outputFormbecause at that stage MyForm is the highest level parent of field.getParentMessagewill find the propertymyfield.labelin the MyForm message properties and returnFormThe second (2.) println statement will output
Pageas now MyPage is the highest level parent. On its first pass up the hierarchy,getParentMessagewill find the propertymyfield.labelin the MyForm message properties and on its second pass will find the same property in MyPage message properties. As MyPage is higher up the hierarchy than MyForm, MyPage will override MyForm and the property value will bePage.- Parameters:
control- the control to get the parent message forname- the specific property name to find- Returns:
- the top level parent's Map of localized messages
-
getParentPage
public static org.openidentityplatform.openam.click.Page getParentPage(org.openidentityplatform.openam.click.Control control)
Get the parent page of the given control or null if the control has no parent. This method will walk up the control's parent hierarchy to find its parent page.- Parameters:
control- the control to get the parent page from- Returns:
- the parent page of the control or null if the control has no parent
-
getRequestParameterMap
public static Map<String,Object> getRequestParameterMap(jakarta.servlet.http.HttpServletRequest request)
Return an ordered map of request parameters from the given request.- Parameters:
request- the servlet request to obtain request parameters from- Returns:
- the ordered map of request parameters
-
getResourcePath
public static String getResourcePath(jakarta.servlet.http.HttpServletRequest request)
Return the page resource path from the request. For example:http://www.mycorp.com/banking/secure/login.htm -> /secure/login.htm
- Parameters:
request- the page servlet request- Returns:
- the page resource path from the request
-
getRequestURI
public static String getRequestURI(jakarta.servlet.http.HttpServletRequest request)
Return the requestURI from the request. For example:http://www.mycorp.com/banking/secure/login.htm -> /banking/secure/login.htm
- Parameters:
request- the page servlet request- Returns:
- the requestURI from the request
-
getResourceAsStream
public static InputStream getResourceAsStream(String name, Class<?> aClass)
Finds a resource with a given name. This method returns null if no resource with this name is found.This method uses the current
ThreadcontextClassLoaderto find the resource. If the resource is not found the class loader of the given class is then used to find the resource.- Parameters:
name- the name of the resourceaClass- the class lookup the resource against, if the resource is not found using the currentThreadcontextClassLoader.- Returns:
- the input stream of the resource if found or null otherwise
-
getResource
public static URL getResource(String name, Class<?> aClass)
Finds a resource with a given name. This method returns null if no resource with this name is found.This method uses the current
ThreadcontextClassLoaderto find the resource. If the resource is not found the class loader of the given class is then used to find the resource.- Parameters:
name- the name of the resourceaClass- the class lookup the resource against, if the resource is not found using the currentThreadcontextClassLoader.- Returns:
- the URL of the resource if found or null otherwise
-
removeState
public static void removeState(org.apache.click.Stateful control, String controlName, org.openidentityplatform.openam.click.Context context)Remove the control state from the session for the given stateful control, control name and request context.- Parameters:
control- the stateful control which state to removecontrolName- the name of the control which state to removecontext- the request context
-
restoreState
public static void restoreState(org.apache.click.Stateful control, String controlName, org.openidentityplatform.openam.click.Context context)Restore the control state from the session for the given stateful control, control name and request context.This method delegates to
Stateful.setState(java.lang.Object)to restore the control state.- Parameters:
control- the stateful control which state to restorecontrolName- the name of the control which state to restorecontext- the request context
-
saveState
public static void saveState(org.apache.click.Stateful control, String controlName, org.openidentityplatform.openam.click.Context context)Save the control state in the session for the given stateful control, control name and request context.* This method delegates to
Stateful.getState()to retrieve the control state to save.- Parameters:
control- the stateful control which state to savecontrolName- the name of the control control which state to savecontext- the request context
-
toGetterName
public static String toGetterName(String property)
Return the getter method name for the given property name.- Parameters:
property- the property name- Returns:
- the getter method name for the given property name.
-
toIsGetterName
public static String toIsGetterName(String property)
Return the is getter method name for the given property name.- Parameters:
property- the property name- Returns:
- the is getter method name for the given property name.
-
toLabel
public static String toLabel(String name)
Return a field label string from the given field name. For example:faxNumber -> Fax Number
Note toLabel will return an empty String ("") if a
nullString name is specified.- Parameters:
name- the field name- Returns:
- a field label string from the given field name
-
toMD5Hash
public static String toMD5Hash(String plaintext)
Return an 32 char MD5 encoded string from the given plain text. The returned value is MD5 hash compatible with Tomcat catalina Realm.Adapted from
org.apache.catalina.util.MD5Encoder- Parameters:
plaintext- the plain text value to encode- Returns:
- encoded MD5 string
-
toName
public static String toName(String label)
Return a field name string from the given field label.A label of
" OK do it!"is returned as"okDoIt". Any characters will also be removed.A label of
"customerSelect"is returned as"customerSelect".- Parameters:
label- the field label or caption- Returns:
- a field name string from the given field label
-
toSetterName
public static String toSetterName(String property)
Return the setter method name for the given property name.- Parameters:
property- the property name- Returns:
- the setter method name for the given property name.
-
isResourcesDeployable
public static boolean isResourcesDeployable(jakarta.servlet.ServletContext servletContext)
Returns true if Click resources (JavaScript, CSS, images etc) packaged in jars can be deployed to the root directory of the webapp, false otherwise.This method will return false in restricted environments where write access to the underlying file system is disallowed. Examples where write access is not allowed include the WebLogic JEE server (this can be changed though) and Google App Engine.
- Parameters:
servletContext- the application servlet context- Returns:
- true if writes are allowed, false otherwise
-
-