org.apache.click.util
Class ClickUtils

java.lang.Object
  extended by org.apache.click.util.ClickUtils

public class ClickUtils
extends Object

Provides miscellaneous Form, String and Stream utility methods.


Field Summary
static String DEFAULT_APP_CONFIG
          The default Click configuration filename:   "/WEB-INF/click.xml".
static String ENABLE_RESOURCE_VERSION
          The resource versioning request attribute: key:   enable-resource-version.
static String RESOURCE_VERSION_INDICATOR
          The static web resource version number indicator string.
static String VERSION_INDICATOR_SEP
          The version indicator separator string.
 
Constructor Summary
ClickUtils()
           
 
Method Summary
static void autoPostRedirect(HttpServletRequest request, HttpServletResponse response, String target, Map<?,?> params, boolean compress)
          Perform an auto post redirect to the specified target using the given response.
static void bind(AbstractLink link)
          A helper method that binds the submitted request value to the Link's value.
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.
static void bind(Field field)
          A helper method that binds the submitted request value to the Field's value.
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.
static boolean bindAndValidate(Field field)
          A helper method that binds and validates the Field's submitted request value.
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.
static Document buildDocument(InputStream inputStream)
          Return a new XML Document for the given input stream.
static Document buildDocument(InputStream inputStream, EntityResolver entityResolver)
          Return a new XML Document for the given input stream and XML entity resolver.
static boolean canBind(Control control, Context context)
          Return true if the given control's request value can be bound, false otherwise.
static Class classForName(String classname)
          Returns the Class object associated with the class or interface with the given string name, using the current Thread context class loader.
static void close(Closeable closeable)
          Close the given closeable (Reader, Writer, Stream) and ignore any exceptions thrown.
static void copyFormToObject(Form form, Object object, boolean debug)
          Populate the given object's attributes with the Form's field values.
static void copyObjectToForm(Object object, Form form, boolean debug)
          Populate the given Form field values with the object's attributes.
static Map<String,Object> createTemplateModel(Page page, Context context)
          Creates a template model of key/value pairs which can be used by template engines such as Velocity and Freemarker.
static Object decode(String string)
          Return an object from the encode(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 String decodeURL(Object value)
          URL decode the specified value using the "UTF-8" encoding scheme.
static void deployFile(ServletContext servletContext, String resource, String targetDir)
          Deploy the specified classpath resource to the given target directory under the web application root directory.
static void deployFileList(ServletContext servletContext, Class<? extends Control> controlClass, String targetDir)
          Deploys required files (from a file list) for a control that repsects a specific convention.
static void deployFiles(ServletContext servletContext, String[] resources, String targetDir)
          Deploy the specified classpath resources to the given target directory under the web application root directory.
static String encode(Object object)
          Return an encoded version of the Serializable object.
static String encodePasswordCookie(String username, String password, int xorMask)
          Builds a cookie string containing a username and password.
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.
static String encodeURL(Object value)
          URL encode the specified value using the "UTF-8" encoding scheme.
static String encodeUrl(Object object, 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 String escape(String value)
          Return an escaped string for the given string value.
static String escapeHtml(String value)
          Return a HTML escaped string for the given string value.
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.
static String getApplicationVersion()
          Return the web application version string.
static ResourceBundle getBundle(String baseName)
          Return a resource bundle using the specified base name.
static ResourceBundle getBundle(String baseName, Locale locale)
          Return a resource bundle using the specified base name and locale.
static Element getChild(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 InputStream getClickConfig(ServletContext servletContext)
          Return the InputStream for the Click configuration file click.xml.
static String getClickVersion()
          Return the Click Framework version string.
static ConfigService getConfigService(ServletContext servletContext)
          Return the application configuration service instance from the given servlet context.
static Cookie getCookie(HttpServletRequest request, String name)
          Returns the specified Cookie object, or null if the cookie does not exist.
static String getCookieValue(HttpServletRequest request, String name)
          Returns the value of the specified cookie as a String.
static String getCssSelector(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 FieldSets.
static LogService getLogService()
          Return the application LogService instance using thread local Context to perform the lookup.
static String getMimeType(String value)
          Return the mime-type or content-type for the given filename/extension.
static String getParentMessage(Control control, String name)
          Return the given control's top level parent's localized message for the specified name.
static Map<String,String> getParentMessages(Control control)
          Return the given control's top level parent's localized messages Map.
static Page getParentPage(Control control)
          Get the parent page of the given control or null if the control has no parent.
static Map<String,Object> getRequestParameterMap(HttpServletRequest request)
          Return an ordered map of request parameters from the given request.
static String getRequestURI(HttpServletRequest request)
          Return the requestURI from the request.
static URL getResource(String name, Class<?> aClass)
          Finds a resource with a given name.
static InputStream getResourceAsStream(String name, Class<?> aClass)
          Finds a resource with a given name.
static String getResourcePath(HttpServletRequest request)
          Return the page resource path from the request.
static String getResourceVersionIndicator(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 boolean hasRequestParameter(Control control)
          Return true if the control has a submitted request value, false otherwise.
static void invalidateCookie(HttpServletRequest request, HttpServletResponse response, String cookieName)
          Invalidate the specified cookie and delete it from the response object.
static void invalidateCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String path)
          Invalidate the specified cookie and delete it from the response object.
static ActionResult invokeAction(Object target, String method)
          Invoke the named method on the given target and return the Object result.
static boolean invokeListener(Object listener, String method)
          Invoke the named method on the given object and return the boolean result.
static boolean isAjaxRequest(HttpServletRequest request)
          Return true is this is an Ajax request, false otherwise.
static boolean isEnableResourceVersion(Context context)
          Return true if static web content resource versioning is enabled.
static boolean isMultipartRequest(HttpServletRequest request)
          Return true if the request is a multi-part content type POST request.
static boolean isResourcesDeployable(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 String limitLength(String value, int maxlength)
          Return the value string limited to maxlength characters.
static String limitLength(String value, int maxlength, String suffix)
          Return the value string limited to maxlength characters.
static void removeState(Stateful control, String controlName, Context context)
          Remove the control state from the session for the given stateful control, control name and request context.
static void restoreState(Stateful control, String controlName, Context context)
          Restore the control state from the session for the given stateful control, control name and request context.
static void saveState(Stateful control, String controlName, Context context)
          Save the control state in the session for the given stateful control, control name and request context.
static void setApplicationVersion(String applicationVersion)
          Set the web application version string.
static Cookie setCookie(HttpServletRequest request, HttpServletResponse response, String name, String value, int maxAge, String path)
          Sets the given cookie values in the servlet response.
static String toGetterName(String property)
          Return the getter method name for the given property name.
static String toIsGetterName(String property)
          Return the is getter method name for the given property name.
static String toLabel(String name)
          Return a field label string from the given field name.
static String toMD5Hash(String plaintext)
          Return an 32 char MD5 encoded string from the given plain text.
static String toName(String label)
          Return a field name string from the given field label.
static String toSetterName(String property)
          Return the setter method name for the given property name.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

ENABLE_RESOURCE_VERSION

public static final String ENABLE_RESOURCE_VERSION
The resource versioning request attribute: key:   enable-resource-version.

If this attribute is set to true and Click is running in production or profile mode, Click resources returned from Control.getHeadElements() will have a version indicator added 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.

Constructor Detail

ClickUtils

public ClickUtils()
Method Detail

autoPostRedirect

public static void autoPostRedirect(HttpServletRequest request,
                                    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 request
response - the servlet response
target - the target URL to send the auto post redirect to
params - the map of parameter values to post
compress - 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.apache.click.Control, org.apache.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. See bind(org.apache.click.control.Field) for a detailed description.

This method delegates to canBind(org.apache.click.Control, org.apache.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. See bind(org.apache.click.control.Field) for a detailed description.

This method delegates to canBind(org.apache.click.Control, org.apache.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. See bind(org.apache.click.control.Field) for a detailed description.

This method delegates to canBind(org.apache.click.Control, org.apache.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.apache.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.apache.click.control.Field) for a detailed description.

This method delegates to canBind(org.apache.click.Control, org.apache.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 stream
entityResolver - the XML entity resolver
Returns:
new XML Document
Throws:
RuntimeException - if a parsing error occurs

canBind

public static boolean canBind(Control control,
                              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.

Parameters:
control - the control to check if it can be bound or not
context - the request context
Returns:
true if the given control request value be bound, false otherwise

classForName

public static Class classForName(String classname)
                          throws ClassNotFoundException
Returns the Class object 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 Class object
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(Page page,
                                                     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:

Parameters:
page - the page to populate the template model from
context - the request context
Returns:
a template model as a map

invalidateCookie

public static void invalidateCookie(HttpServletRequest request,
                                    HttpServletResponse response,
                                    String cookieName,
                                    String path)
Invalidate the specified cookie and delete it from the response object.

This method was derived from Atlassian CookieUtils method of the same name, release under the BSD License.

Parameters:
request - the servlet request
response - the servlet response
cookieName - The name of the cookie you want to delete
path - of the path the cookie you want to delete

isAjaxRequest

public static boolean isAjaxRequest(HttpServletRequest request)
Return true is this is an Ajax request, false otherwise.

An Ajax request is identified by the presence of the request header or request parameter: "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 a XmlHttpRequest object. 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(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(HttpServletRequest request,
                                    HttpServletResponse response,
                                    String cookieName)
Invalidate the specified cookie and delete it from the response object. Deletes only cookies mapped against the root "/" path. Otherwise use invalidateCookie(HttpServletRequest, HttpServletResponse, String, String)

This method was derived from Atlassian CookieUtils method of the same name, release under the BSD License.

Parameters:
request - the servlet request
response - the servlet response
cookieName - 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 name
locale - 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 from
name - 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 from
name - the name of the child element
Returns:
the list of XML child elements for the given name

getClickConfig

public static InputStream getClickConfig(ServletContext servletContext)
Return the InputStream for the Click configuration file click.xml. This method will first lookup the click.xml under the applications WEB-INF directory, 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(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 Cookie getCookie(HttpServletRequest request,
                               String name)
Returns the specified Cookie object, or null if the cookie does not exist.

This method was derived from Atlassian CookieUtils method of the same name, release under the BSD License.

Parameters:
request - the servlet request
name - the name of the cookie
Returns:
the Cookie object if it exists, otherwise null

setCookie

public static Cookie setCookie(HttpServletRequest request,
                               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 CookieUtils method of the same name, release under the BSD License.

Parameters:
request - the servlet request
response - the servlet response
name - the cookie name
value - the cookie value
maxAge - 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(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 CookieUtils method of the same name, release under the BSD License.

Parameters:
request - the servlet request
name - 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(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 version indicator is based on the current Click release version. For example when using Click 1.4 this method will return the string "_1.4".

Parameters:
context - the request context
Returns:
a version indicator for web resources

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 version indicator is based on the application version. For example if the application version is 1.2 this method will return the string "_1.2".

The application version can be set through the static method setApplicationVersion(java.lang.String).

Returns:
an application version indicator for web resources

getCssSelector

public static String getCssSelector(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:

  1. if control.getId() is set, prepend it with a '#' char and return the value. An example selector will be: #field-id
  2. if control.getName() is set do the following:
    1. 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].
    2. 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].
  3. 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

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 from
object - the object to populate with field values
debug - 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 from
form - the Form to populate
debug - log debug statements when populating the form

deployFile

public static void deployFile(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 context
resource - the classpath resource name
targetDir - the target directory to deploy the resource to

deployFiles

public static void deployFiles(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 context
resources - the array of classpath resource names
targetDir - the target directory to deploy the resource to

deployFileList

public static void deployFileList(ServletContext servletContext,
                                  Class<? extends 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 context
controlClass - the class of the Control that has files for deployment
targetDir - target directory where to deploy the files to. In most cases this is only the reserved directory click

encode

public static String encode(Object object)
                     throws IOException
Return an encoded version of the Serializable object. 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 occurs
IllegalArgumentException - 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 the encode(Object) string.

Parameters:
string - the encoded string
Returns:
an object from the encoded
Throws:
ClassNotFoundException - if the class could not be instantiated
IOException - 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 CookieUtils method of the same name, release under the BSD License.

Parameters:
username - the username
password - the password
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

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 CookieUtils method of the same name, release under the BSD License.

Parameters:
username - the username
password - the password
encoding - 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 CookieUtils method of the same name, release under the BSD License.

Parameters:
cookieVal - the encoded cookie username and password value
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 equals null or 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 CookieUtils method of the same name, release under the BSD License.

Parameters:
cookieVal - the encoded cookie username and password value
encoding - 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 equals null or 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,
                               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 string
context - 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(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 invoke
method - the name of the method to invoke
Returns:
true if the listener method returned true
See Also:
Control.setListener(Object, String)

invokeAction

public static 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 invoke
method - the name of the method to invoke
Returns:
an ActionResult instance

isEnableResourceVersion

public static boolean isEnableResourceVersion(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 of
maxlength - 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 of
maxlength - the maximum string length
suffix - 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 FieldSets. The list of returned fields will exclude any Button, FieldSet or Label fields.

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(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(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.properties
 myfield.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 output Form because at that stage MyForm is the highest level parent of field. getParentMessage will find the property myfield.label in the MyForm message properties and return Form

The second (2.) println statement will output Page as now MyPage is the highest level parent. On its first pass up the hierarchy, getParentMessage will find the property myfield.label in 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 be Page.

Parameters:
control - the control to get the parent message for
name - the specific property name to find
Returns:
the top level parent's Map of localized messages

getParentPage

public static Page getParentPage(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(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(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(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 Thread context ClassLoader to 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 resource
aClass - the class lookup the resource against, if the resource is not found using the current Thread context ClassLoader.
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 Thread context ClassLoader to 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 resource
aClass - the class lookup the resource against, if the resource is not found using the current Thread context ClassLoader.
Returns:
the URL of the resource if found or null otherwise

removeState

public static void removeState(Stateful control,
                               String controlName,
                               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 remove
controlName - the name of the control which state to remove
context - the request context

restoreState

public static void restoreState(Stateful control,
                                String controlName,
                                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 restore
controlName - the name of the control which state to restore
context - the request context

saveState

public static void saveState(Stateful control,
                             String controlName,
                             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 save
controlName - the name of the control control which state to save
context - 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 null String 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 &nbsp; 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(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