org.directwebremoting.util
Class LocalUtil

java.lang.Object
  extended by org.directwebremoting.util.LocalUtil

public final class LocalUtil
extends java.lang.Object

Various utilities, stuff that we're still surprised isn't in the JDK, and stuff that perhaps is borderline JDK material, but isn't really pure DWR either. TODO: This probably needs cutting up into

Author:
Joe Walker [joe at getahead dot ltd dot uk]

Method Summary
static void addNoCacheHeaders(javax.servlet.http.HttpServletResponse resp)
          Add headers to prevent browsers and proxies from caching this reply.
static java.lang.String capitalize(java.lang.String input)
          Changes the first letter to upper case.
static java.lang.Class<?> classForName(java.lang.String className)
          Utility to essentially do Class forName and allow configurable Classloaders.
static
<T> java.lang.Class<? extends T>
classForName(java.lang.String debugContext, java.lang.String className, java.lang.Class<T> impl)
          Utility to essentially do Class forName with the assumption that the environment expects failures for missing jar files and can carry on if this process fails.
static
<T> T
classNewInstance(java.lang.String name, java.lang.String className, java.lang.Class<T> impl)
          Utility to essentially do Class forName and newInstance with the assumption that the environment expects failures for missing jar files and can carry on if this process fails.
static void close(java.io.Closeable in)
          InputStream closer that can cope if the input stream is null.
static void close(OutputStreamLoader loader)
          OutputStreamLoader closer that can cope if the input is null.
static void debugRequest(javax.servlet.http.HttpServletRequest request)
          If something has gone wrong we want to know all about the request that caused the failure
static boolean equals(java.lang.Object object1, java.lang.Object object2)
          A helper for implementing Object.equals(Object) when some of your members could be null.
static java.lang.reflect.Field[] getAllFields(java.lang.Class<?> clazz)
          Return a list of all fields (whatever access status, and on whatever superclass they were defined) that can be found on this class.
static java.util.List<java.lang.Class<?>> getAllSuperclasses(java.lang.Class<?> clazz)
          Return a List of super-classes for the given class.
static java.lang.reflect.Method getMethod(java.lang.Class<?> clazz, java.lang.String name, java.lang.Class<?>... args)
          Utility to retrieve a method.
static java.lang.Class<?> getNonPrimitiveType(java.lang.Class<?> type)
           
static
<T> T
getProperty(java.lang.Object pojo, java.lang.String propertyName, java.lang.Class<T> type)
          Utility to find a getter and return it's value from an object If Java had the option to temporarily do dynamic typing there would be no need for this.
static java.lang.Class<?> getPropertyType(java.lang.Class<?> real, java.lang.String key)
          Set a property on an object using reflection
static long getSystemClassloadTime()
          /** Get a timestamp for the earliest time that we know the JVM started
static java.lang.reflect.Method getWriteMethod(java.lang.Class<?> clazz, java.beans.PropertyDescriptor property)
          Obtains the write method for a property.
static boolean hasLength(java.lang.CharSequence str)
          Check that the given CharSequence is neither null nor of length 0.
static boolean hasText(java.lang.CharSequence str)
          Check whether the given CharSequence has actual text.
static java.lang.Object invoke(java.lang.Object object, java.lang.reflect.Method method, java.lang.Object[] params)
          Calling methods using reflection is useful for graceful fallback - this is a helper method to make this easy
static boolean isEquivalent(java.lang.Class<?> c1, java.lang.Class<?> c2)
          True if c1 is java.lang.Boolean and c2 is boolean, etc.
static boolean isJavaIdentifier(java.lang.String test)
          Determines if the specified string is permissible as a Java identifier.
static boolean isJavaIdentifierWithPackage(java.lang.String test)
          Determines if the specified string is permissible as a Java identifier potentially prefixed with package names.
static boolean isJavaScriptTypeAssignableTo(java.lang.String javaScriptType, java.lang.Class<?> clazz)
          Determines if a JavaScript type is assignable to the passed in Java class.
static boolean isLetterOrDigitOrUnderline(java.lang.String test)
          Determines if the specified string contains only Unicode letters or digits as defined by Character.isLetterOrDigit(char)
static boolean isServletClass(java.lang.Class<?> paramType)
          Is this class one that we auto fill, so the user can ignore?
static boolean isSimpleName(java.lang.String name)
          Is this object property one that we can use in a JSON style or do we need to get fancy.
static boolean isTypeSimplyConvertable(java.lang.Class<?> paramType)
          Can the type be used in a call to simpleConvert(String, Class)?
static boolean isWrapper(java.lang.Object object)
          Checks if this object is an instance of a primitive wrapper.
static
<T> java.lang.Iterable<T>
iterableizer(java.util.Enumeration<?> en, java.lang.Class<T> type)
          Go Java! Why do I even need to do this?
static
<T> java.lang.Iterable<T>
iterableizer(java.util.Enumeration<T> en)
          Go Java! How many people have written this code?
static java.lang.String join(java.lang.Object[] array, java.lang.String separator)
          Create a string by joining the array elements together with the separator in-between each element.
static java.util.Locale parseLocaleString(java.lang.String localeString)
          Parse the given localeString into a Locale.
static java.lang.Class<?> primitiveToWrapper(java.lang.Class<?> clazz)
          Converts the specified primitive Class object to its corresponding wrapper Class object.
static void setParams(java.lang.Object object, java.util.Map<java.lang.String,?> params, java.util.List<java.lang.String> ignore)
          Set use reflection to set the setters on the object called by the keys in the params map with the corresponding values
static void setProperty(java.lang.Object object, java.lang.String key, java.lang.Object value)
          Set a property on an object using reflection
static int shrink(long diff)
          Comparator.compare(Object, Object) demands that the return is 1, 0, -1.
static
<T> T
simpleConvert(java.lang.String value, java.lang.Class<T> paramType)
          A very simple conversion function for all the IoC style setup and reflection that we are doing.
static java.lang.Class<?> toClass(java.lang.reflect.Type parameterType, java.lang.String debugContext)
          Utility to find a Class from a Type if possible, assuming String.class if the conversion can't be made
static java.lang.String urlDecode(java.lang.String value)
          URL decode a value.
static java.lang.String urlEncode(java.lang.String value)
          URL encode a value.
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Method Detail

join

public static java.lang.String join(java.lang.Object[] array,
                                    java.lang.String separator)
Create a string by joining the array elements together with the separator in-between each element. A null (in the array or as a separator) is treated as an empty string.

Parameters:
array - The array of elements to join
separator - The string sequence to place between array elements
Returns:
A string containing the joined elements

hasText

public static boolean hasText(java.lang.CharSequence str)
Check whether the given CharSequence has actual text. More specifically, returns true if the string not null, its length is greater than 0, and it contains at least one non-whitespace character.

 LocalUtil.hasText(null) = false
 LocalUtil.hasText("") = false
 LocalUtil.hasText(" ") = false
 LocalUtil.hasText("12345") = true
 LocalUtil.hasText(" 12345 ") = true
 

Parameters:
str - the CharSequence to check (may be null)
Returns:
true if the CharSequence is not null, its length is greater than 0, and it does not contain whitespace only
See Also:
Character.isWhitespace(char)

hasLength

public static boolean hasLength(java.lang.CharSequence str)
Check that the given CharSequence is neither null nor of length 0. Note: Will return true for a CharSequence that purely consists of whitespace.

 LocalUtil.hasLength(null) = false
 LocalUtil.hasLength("") = false
 LocalUtil.hasLength(" ") = true
 LocalUtil.hasLength("Hello") = true
 

Parameters:
str - the CharSequence to check (may be null)
Returns:
true if the CharSequence is not null and has length
See Also:
hasText(java.lang.CharSequence)

isJavaIdentifier

public static boolean isJavaIdentifier(java.lang.String test)
Determines if the specified string is permissible as a Java identifier. Returns true if the string is non-null, non-zero length with a Java identifier start as the first character and Java identifier parts in all remaining characters.

Parameters:
test - the string to be tested.
Returns:
true if the string is a Java identifier, false otherwise.
See Also:
Character.isJavaIdentifierPart(char), Character.isJavaIdentifierStart(char)

isJavaIdentifierWithPackage

public static boolean isJavaIdentifierWithPackage(java.lang.String test)
Determines if the specified string is permissible as a Java identifier potentially prefixed with package names. It tests each segment of the string separated by "." and returns true if all segments have non-zero length with a Java identifier start as the first character and Java identifier parts in all remaining characters.

Parameters:
test - the string to be tested.
Returns:
true if the string is a Java identifier, false otherwise.

isLetterOrDigitOrUnderline

public static boolean isLetterOrDigitOrUnderline(java.lang.String test)
Determines if the specified string contains only Unicode letters or digits as defined by Character.isLetterOrDigit(char)

Parameters:
test - The string to test
Returns:
true if the string is non-null, non-empty and contains only characters that are unicode letters or digits
See Also:
Character.isLetterOrDigit(char)

isEquivalent

public static boolean isEquivalent(java.lang.Class<?> c1,
                                   java.lang.Class<?> c2)
True if c1 is java.lang.Boolean and c2 is boolean, etc.

Parameters:
c1 - the first class to test
c2 - the second class to test
Returns:
true if the classes are equivalent

equals

public static boolean equals(java.lang.Object object1,
                             java.lang.Object object2)
A helper for implementing Object.equals(Object) when some of your members could be null. Returns true if both objects are null, or if neither object is null, but object1.equals(object2) returns true. Otherwise returns false.

Parameters:
object1 - The first object to compare.
object2 - The second object to compare.
Returns:
True if the objects are both null or Object.equals(Object)

shrink

public static int shrink(long diff)
Comparator.compare(Object, Object) demands that the return is 1, 0, -1. This helps implement that.

Parameters:
diff - The result of some subtraction.
Returns:
1, 0, -1

getNonPrimitiveType

public static java.lang.Class<?> getNonPrimitiveType(java.lang.Class<?> type)
Parameters:
type - The class to de-primitivize
Returns:
The non-primitive version of the class

addNoCacheHeaders

public static void addNoCacheHeaders(javax.servlet.http.HttpServletResponse resp)
Add headers to prevent browsers and proxies from caching this reply.

Parameters:
resp - The response to add headers to

isServletClass

public static boolean isServletClass(java.lang.Class<?> paramType)
Is this class one that we auto fill, so the user can ignore?

Parameters:
paramType - The type to test
Returns:
true if the type is a Servlet type

debugRequest

public static void debugRequest(javax.servlet.http.HttpServletRequest request)
If something has gone wrong we want to know all about the request that caused the failure

Parameters:
request - The HttpServletRequest the borked

iterableizer

public static <T> java.lang.Iterable<T> iterableizer(java.util.Enumeration<T> en)
Go Java! How many people have written this code?

Parameters:
en - The Enumeration that we want to iterate over
Returns:
An implementation of Iterable for use in a for each loop

iterableizer

public static <T> java.lang.Iterable<T> iterableizer(java.util.Enumeration<?> en,
                                                     java.lang.Class<T> type)
Go Java! Why do I even need to do this?

Parameters:
en - The Enumeration that we want to iterate over
type - For when we were given an Enumeration and need an Iterator
Returns:
An implementation of Iterable for use in a for each loop

urlDecode

public static java.lang.String urlDecode(java.lang.String value)
URL decode a value. URLDecoder.decode(String, String) throws an UnsupportedEncodingException, which is silly given that the most common use case will be to pass in "UTF-8"

Parameters:
value - The string to decode
Returns:
The decoded string

urlEncode

public static java.lang.String urlEncode(java.lang.String value)
URL encode a value. URLEncoder.encode(String, String) throws an UnsupportedEncodingException, which is silly given that the most common use case will be to pass in "UTF-8"

Parameters:
value - The string to decode
Returns:
The decoded string

setParams

public static void setParams(java.lang.Object object,
                             java.util.Map<java.lang.String,?> params,
                             java.util.List<java.lang.String> ignore)
Set use reflection to set the setters on the object called by the keys in the params map with the corresponding values

Parameters:
object - The object to setup
params - The settings to use
ignore - List of keys to not warn about if they are not properties Note only the warning is skipped, we still try the setter

setProperty

public static void setProperty(java.lang.Object object,
                               java.lang.String key,
                               java.lang.Object value)
                        throws java.lang.NoSuchMethodException,
                               java.lang.SecurityException,
                               java.lang.IllegalAccessException,
                               java.lang.IllegalArgumentException,
                               java.lang.reflect.InvocationTargetException
Set a property on an object using reflection

Parameters:
object - The object to call the setter on
key - The name of the property to set.
value - The new value to use for the property
Throws:
java.lang.NoSuchMethodException - Passed on from reflection code
java.lang.SecurityException - Passed on from reflection code
java.lang.IllegalAccessException - Passed on from reflection code
java.lang.IllegalArgumentException - Passed on from reflection code
java.lang.reflect.InvocationTargetException - Passed on from reflection code

isWrapper

public static final boolean isWrapper(java.lang.Object object)
Checks if this object is an instance of a primitive wrapper.

Parameters:
object - anything
Returns:
true if this object is an Integer, Long, Float, Double, Boolean...

getPropertyType

public static java.lang.Class<?> getPropertyType(java.lang.Class<?> real,
                                                 java.lang.String key)
Set a property on an object using reflection

Parameters:
real - The object type to find the setter on
key - The name of the property to set.

isTypeSimplyConvertable

public static boolean isTypeSimplyConvertable(java.lang.Class<?> paramType)
Can the type be used in a call to simpleConvert(String, Class)?

Parameters:
paramType - The type to test
Returns:
true if the type is acceptable to simpleConvert()

simpleConvert

public static <T> T simpleConvert(java.lang.String value,
                                  java.lang.Class<T> paramType)
A very simple conversion function for all the IoC style setup and reflection that we are doing.

Parameters:
value - The value to convert
paramType - The type to convert to. Currently any primitive types and String are supported.
Returns:
The converted object.

isSimpleName

public static boolean isSimpleName(java.lang.String name)
Is this object property one that we can use in a JSON style or do we need to get fancy. i.e does it contain only letters and numbers with an initial letter.

Parameters:
name - The name to test for JSON compatibility
Returns:
true if the name is simple

classForName

public static java.lang.Class<?> classForName(java.lang.String className)
                                       throws java.lang.ClassNotFoundException
Utility to essentially do Class forName and allow configurable Classloaders.

The initial implementation makes use of the context classloader for the current thread.

Parameters:
className - The class to create
Returns:
The class if it is safe or null otherwise.
Throws:
java.lang.ClassNotFoundException - If className is not valid

classForName

public static <T> java.lang.Class<? extends T> classForName(java.lang.String debugContext,
                                                            java.lang.String className,
                                                            java.lang.Class<T> impl)
Utility to essentially do Class forName with the assumption that the environment expects failures for missing jar files and can carry on if this process fails.

Type Parameters:
T - The base type that we want a class to implement
Parameters:
debugContext - The name for debugging purposes
className - The class to create
impl - The implementation class - what should className do?
Returns:
The class if it is safe or null otherwise.

getMethod

public static java.lang.reflect.Method getMethod(java.lang.Class<?> clazz,
                                                 java.lang.String name,
                                                 java.lang.Class<?>... args)
Utility to retrieve a method.

Parameters:
clazz - - The class where the method exists.
name - - The name of the method to retrieve.
args - - The arguments the method takes.
Returns:
- The method, null if an exception is thrown or clazz is null.

classNewInstance

public static <T> T classNewInstance(java.lang.String name,
                                     java.lang.String className,
                                     java.lang.Class<T> impl)
Utility to essentially do Class forName and newInstance with the assumption that the environment expects failures for missing jar files and can carry on if this process fails.

Type Parameters:
T - The base type that we want a class to implement
Parameters:
name - The name for debugging purposes
className - The class to create
impl - The implementation class - what should className do?
Returns:
The new instance if it is safe or null otherwise.

invoke

public static java.lang.Object invoke(java.lang.Object object,
                                      java.lang.reflect.Method method,
                                      java.lang.Object[] params)
                               throws java.lang.IllegalStateException
Calling methods using reflection is useful for graceful fallback - this is a helper method to make this easy

Parameters:
object - The object to use as 'this'
method - The method to call, can be null in which case null is returned
params - The parameters to pass to the reflection call
Returns:
The results of calling method.invoke() or null
Throws:
java.lang.IllegalStateException - If anything goes wrong

close

public static void close(java.io.Closeable in)
InputStream closer that can cope if the input stream is null. If anything goes wrong, the errors are logged and ignored.

Parameters:
in - The resource to close

close

public static void close(OutputStreamLoader loader)
OutputStreamLoader closer that can cope if the input is null. If anything goes wrong, the errors are logged and ignored.

Parameters:
loader - The resource to close

getAllSuperclasses

public static java.util.List<java.lang.Class<?>> getAllSuperclasses(java.lang.Class<?> clazz)
Return a List of super-classes for the given class.

Parameters:
clazz - the class to look up
Returns:
the List of super-classes in order going up from this one

getAllFields

public static java.lang.reflect.Field[] getAllFields(java.lang.Class<?> clazz)
Return a list of all fields (whatever access status, and on whatever superclass they were defined) that can be found on this class.

This is like a union of Class.getDeclaredFields() which ignores and super-classes, and Class.getFields() which ignored non-public fields

Parameters:
clazz - The class to introspect
Returns:
The complete list of fields

getProperty

public static <T> T getProperty(java.lang.Object pojo,
                                java.lang.String propertyName,
                                java.lang.Class<T> type)
Utility to find a getter and return it's value from an object If Java had the option to temporarily do dynamic typing there would be no need for this.

Parameters:
pojo - The POJO to extract some data from.
propertyName - The name of the property form which we form a getter name by upper-casing the first letter (in the EN locale) and prefixing with 'get'
Returns:
The value of property, or null if it does not exist

toClass

public static java.lang.Class<?> toClass(java.lang.reflect.Type parameterType,
                                         java.lang.String debugContext)
Utility to find a Class from a Type if possible, assuming String.class if the conversion can't be made


parseLocaleString

public static java.util.Locale parseLocaleString(java.lang.String localeString)
Parse the given localeString into a Locale.

This is the inverse operation of Locale's toString.

Parameters:
localeString - the locale string, following Locale's toString() format ("en", "en_UK", etc); also accepts spaces as separators, as an alternative to underscores
Returns:
a corresponding Locale instance

primitiveToWrapper

public static java.lang.Class<?> primitiveToWrapper(java.lang.Class<?> clazz)
Converts the specified primitive Class object to its corresponding wrapper Class object.

Parameters:
clazz - the class to convert, may be null
Returns:
the wrapper class for cls or cls if cls is not a primitive. null if null input.

capitalize

public static java.lang.String capitalize(java.lang.String input)
Changes the first letter to upper case. No other letters are affected.

Parameters:
input - any
Returns:
any

getWriteMethod

public static java.lang.reflect.Method getWriteMethod(java.lang.Class<?> clazz,
                                                      java.beans.PropertyDescriptor property)
Obtains the write method for a property.

Parameters:
property - any
Returns:
any

isJavaScriptTypeAssignableTo

public static boolean isJavaScriptTypeAssignableTo(java.lang.String javaScriptType,
                                                   java.lang.Class<?> clazz)
Determines if a JavaScript type is assignable to the passed in Java class.

Parameters:
javaScriptType -
clazz -
Returns:
boolean

getSystemClassloadTime

public static long getSystemClassloadTime()
/** Get a timestamp for the earliest time that we know the JVM started

Returns:
a JVM start time

Copyright 2008