|
Version 4.10.0 | ||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
Object hirondelle.web4j.util.Util
public final class Util
Static convenience methods for common tasks, which eliminate code duplication.
Args
wraps certain methods of this class into a form suitable for checking arguments.
WebUtil
includes utility methods particular to web applications.
Method Summary | ||
---|---|---|
static
|
asMap(List<V> aList,
Class<K> aClass,
String aKeyMethodName)
Transform a List into a Map. |
|
static Locale |
buildLocale(String aRawLocale)
Return a Locale object by parsing aRawLocale. |
|
static TimeZone |
buildTimeZone(String aTimeZone)
Return a TimeZone corresponding to a given String . |
|
static boolean |
contains(Pattern aPattern,
String aText)
Return true only if aText is non-null, and contains a substring that matches aPattern. |
|
static String |
getArrayAsString(Object aArray)
Convenience method for producing a simple textual representation of an array. |
|
static Logger |
getLogger(Class<?> aClass)
Return a Logger whose name follows a specific naming convention. |
|
static Pattern |
getPatternFromList(List<?> aList)
Create a Pattern corresponding to a List. |
|
static boolean |
hasMaxDecimals(BigDecimal aAmount,
int aMaxNumDecimalPlaces)
Return true only if the number of decimal places in aAmount is in the range 0..aMaxNumDecimalPlaces (inclusive). |
|
static boolean |
hasMaxDecimals(Decimal aAmount,
int aMaxNumDecimalPlaces)
Return true only if the number of decimal places in aAmount is in the range 0..aMaxNumDecimalPlaces (inclusive). |
|
static boolean |
hasNumDecimals(BigDecimal aAmount,
int aNumDecimals)
Return true only if aAmount has exactly the number of specified decimals. |
|
static boolean |
hasNumDecimals(Decimal aAmount,
int aNumDecimals)
Return true only if aAmount has exactly the number of specified decimals. |
|
static boolean |
isInRange(int aNumber,
int aLow,
int aHigh)
Return true only if aNumber is in the range aLow..aHigh (inclusive). |
|
static boolean |
isSuccess(int aNumEdits)
Return true only if aNumEdits is greater than 0. |
|
static boolean |
isZeroMoney(BigDecimal aMoney)
Return true only if aMoney equals 0 or 0.00. |
|
static String |
logOnePerLine(Collection<?> aCollection)
Return a String suitable for logging, having one item from aCollection per line. |
|
static String |
logOnePerLine(Collection<?> aCollection,
int aIndentLevel)
As in logOnePerLine(Collection) , but with specified indentation level. |
|
static String |
logOnePerLine(Map<?,?> aMap)
Return a String suitable for logging, having one item from aMap per line. |
|
static boolean |
matches(Pattern aPattern,
String aText)
Return true only if aText is non-null, and matches aPattern. |
|
static Boolean |
nullMeansFalse(Boolean aBoolean)
Coerce a possibly-null Boolean value into Boolean.FALSE . |
|
static Boolean |
parseBoolean(String aBooleanAsText)
Parse text commonly used to denote booleans into a Boolean object. |
|
static String |
quote(Object aObject)
Call String.valueOf(Object) on aObject, and place the result in single quotes. |
|
static String |
removeQuotes(String aText)
Remove any initial or final quote characters from aText, either a single quote or a double quote. |
|
static String |
replace(String aInput,
String aOldText,
String aNewText)
Replace every occurrence of a fixed substring with substitute text. |
|
static
|
replaceIfNull(E aPossiblyNullItem,
E aReplacement)
If aPossiblyNullItem is null, then return aReplacement ; otherwise return aPossiblyNullItem. |
|
static
|
reverseMap(Map<K,V> aMap)
Reverse the keys and values in a Map. |
|
static boolean |
textHasContent(SafeText aText)
Return true only if aText is not null, and if its raw String is not empty after trimming. |
|
static boolean |
textHasContent(String aText)
Return true only if aText is not null, and is not empty after trimming. |
|
static String |
trimCurrency(String aCurrencyAmount,
String aDecimalSeparator)
Convert end-user input into a form suitable for BigDecimal . |
|
static String |
trimPossiblyNull(String aText)
If aText is null, return null; else return aText.trim(). |
|
static String |
withInitialCapital(String aText)
Ensure the initial character of aText is capitalized. |
|
static String |
withNoSpaces(String aText)
Ensure aText contains no spaces. |
Methods inherited from class Object |
---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
Method Detail |
---|
public static boolean isSuccess(int aNumEdits)
This method is intended for database operations.
public static boolean textHasContent(String aText)
String.trim()
.)
For checking argument validity, Args.checkForContent(java.lang.String)
should
be used instead of this method.
aText
- possibly-null.public static boolean textHasContent(SafeText aText)
String.trim()
.)
aText
- possibly-null.public static String trimPossiblyNull(String aText)
aText
- possibly-null.public static boolean isInRange(int aNumber, int aLow, int aHigh)
For checking argument validity, Args.checkForRange(int, int, int)
should
be used instead of this method.
aLow
- less than or equal to aHigh.public static boolean hasMaxDecimals(BigDecimal aAmount, int aMaxNumDecimalPlaces)
aAmount
- any amount, positive or negative..aMaxNumDecimalPlaces
- is 1 or more.public static boolean hasMaxDecimals(Decimal aAmount, int aMaxNumDecimalPlaces)
aAmount
- any amount, positive or negative..aMaxNumDecimalPlaces
- is 1 or more.public static boolean hasNumDecimals(BigDecimal aAmount, int aNumDecimals)
aNumDecimals
- is 0 or more.public static boolean hasNumDecimals(Decimal aAmount, int aNumDecimals)
aNumDecimals
- is 0 or more.public static Boolean parseBoolean(String aBooleanAsText)
Boolean
object.
The parameter passed to this method is first trimmed (if it is non-null), and then compared to the following Strings, ignoring case :
Boolean.TRUE
: 'true', 'yes', 'on'
Boolean.FALSE
: 'false', 'no', 'off'
Any other text will cause a RuntimeException. (Note that this behavior
is different from that of Boolean.valueOf(String)
).
(This method is clearly biased in favor of English text. It is hoped that this is not too inconvenient for the caller.)
aBooleanAsText
- possibly-null text to be converted into a Boolean
; if null, then the
return value is null.public static Boolean nullMeansFalse(Boolean aBoolean)
Boolean
value into Boolean.FALSE
.
This method is usually called in Model Object constructors that have two-state Boolean fields.
This method is supplied specifically for request parameters that may be missing from the request, during normal operation of the program.
Example : a form has a checkbox for 'yes, send me your newsletter', and the data is modeled has having two states -
true and false. If the checkbox is not checked , however, the browser will
likely not POST any corresponding request parameter - it will be null. In that case, calling this method
will coerce such null parameters into Boolean.FALSE
.
There are other cases in which data is modeled as having not two states, but three : true, false, and null. The null value usually means 'unknown'. In that case, this method should not be called.
public static final Pattern getPatternFromList(List<?> aList)
Pattern
corresponding to a List.
Example: if the List
contains "cat" and "dog", then the returned
Pattern will correspond to the regular expression "(cat|dog)".
aList
- is not empty, and contains objects whose toString()
value represents each item in the pattern.public static boolean isZeroMoney(BigDecimal aMoney)
public static boolean matches(Pattern aPattern, String aText)
Differs from Pattern.matches(java.lang.String, java.lang.CharSequence)
and String.matches(java.lang.String)
,
since the regex argument is a compiled Pattern
, not a
String.
public static boolean contains(Pattern aPattern, String aText)
public static <E> E replaceIfNull(E aPossiblyNullItem, E aReplacement)
Intended mainly for occasional use in Model Object constructors. It is used to coerce null items into a more appropriate default value.
public static String trimCurrency(String aCurrencyAmount, String aDecimalSeparator)
Convert end-user input into a form suitable for BigDecimal
.
The idea is to allow a wide range of user input formats for monetary amounts. For example, an amount may be input as '$1,500.00', 'U$1500.00', or '1500.00 U$'. These entries can all be converted into a BigDecimal by simply stripping out all characters except for digits and the decimal character.
Removes all characters from aCurrencyAmount which are not digits or aDecimalSeparator. Finally, if aDecimalSeparator is not a period (expected by BigDecimal) then it is replaced with a period.
aDecimalSeparator
- must have content, and must have length of 1.public static Logger getLogger(Class<?> aClass)
Logger
whose name follows a specific naming convention.
The conventional logger names used by WEB4J are taken as aClass.getPackage().getName().
Logger names appearing in the logging.properties config file must match the names returned by this method.
If an application requires an alternate naming convention, then an alternate implementation can be easily constructed. Alternate naming conventions might account for :
public static String quote(Object aObject)
String.valueOf(Object)
on aObject, and place the result in single quotes.
This method is a bit unusual in that it can accept a null argument : if aObject is null, it will return 'null'.
This method reduces errors from leading and trailing spaces, by placing single quotes around the returned text. Such leading and trailing spaces are both easy to create and difficult to detect (a bad combination).
Note that such quotation is likely needed only for String data, since trailing or leading spaces will not occur for other types of data.
public static String removeQuotes(String aText)
This method will not trim the text passed to it. Furthermore, it will examine only the very first character and the very last character. It will remove the first or last character, but only if they are a single quote or a double quote.
If aText has no content, then it is simply returned by this method, as is, including possibly-null values.
aText
- is possibly null, and is not trimmed by this methodpublic static String withInitialCapital(String aText)
Does not trim aText.
aText
- has content.public static String withNoSpaces(String aText)
Along with withInitialCapital(String)
, this method is useful for
mapping request parameter names into corresponding getXXX methods.
For example, the text 'Email Address' and 'emailAddress'
can both be mapped to a method named 'getEmailAddress()', by using :
String methodName = "get" + Util.withNoSpaces(Util.withInitialCapital(name));
aText
- has contentpublic static String replace(String aInput, String aOldText, String aNewText)
This method is distinct from String.replaceAll(java.lang.String, java.lang.String)
, since it does not use a
regular expression.
aInput
- may contain substring aOldText; satisfies textHasContent(String)
aOldText
- substring which is to be replaced; possibly empty, but never nullaNewText
- replacement for aOldText; possibly empty, but never nullpublic static String logOnePerLine(Collection<?> aCollection)
For the Collection containing
[null, "Zebra", "aardvark", "Banana", "", "aardvark", new BigDecimal("5.00")],
the return value is :
(7) { '' '5.00' 'aardvark' 'aardvark' 'Banana' 'null' 'Zebra' }
The text for each item is generated by calling quote(java.lang.Object)
, and by appending a new line.
As well, this method reports the total number of items, and places items in alphabetical order (ignoring case). (The iteration order of the Collection passed by the caller will often differ from the order of items presented in the return value.)
public static String logOnePerLine(Collection<?> aCollection, int aIndentLevel)
logOnePerLine(Collection)
, but with specified indentation level.
aIndentLevel
- greater than or equal to 1, acts as multiplier for a
"standard" indentation level of two spaces.public static String logOnePerLine(Map<?,?> aMap)
For a Map containing
["b"="blah", "a"=new BigDecimal(5.00), "Z"=null, null=new Integer(3)],
the return value is :
(4) { 'a' = '5.00' 'b' = 'blah' 'null' = '3' 'Z' = 'null' }
The text for each key and value is generated by calling quote(java.lang.Object)
, and
appending a new line after each entry.
As well, this method reports the total number of items, and places items in alphabetical order of their keys (ignoring case). (The iteration order of the Map passed by the caller will often differ from the order of items in the return value.)
An attempt is made to suppress the emission of passwords. Values in a Map are presented as **** if the following conditions are all true :
String.valueOf(java.lang.Object)
applied to the key contains the word password or
credential (ignoring case)
public static Locale buildLocale(String aRawLocale)
Locale
object by parsing aRawLocale.
The format of aRawLocale follows the
language_country_variant style used by Locale
. The value is not checked against
Locale.getAvailableLocales()
.
public static TimeZone buildTimeZone(String aTimeZone)
TimeZone
corresponding to a given String
.
If the given String does not correspond to a known TimeZone id,
as determined by TimeZone.getAvailableIDs()
, then a
runtime exception is thrown. (This differs from the behavior of the
TimeZone
class itself, and is the reason why this method exists.)
public static String getArrayAsString(Object aArray)
The format of the returned String
is the same as
AbstractCollection.toString()
:
Thanks to Jerome Lacoste for improving the implementation of this method.
aArray
- is a possibly-null array whose elements are
primitives or objects. Arrays of arrays are also valid, in which case
aArray is rendered in a nested, recursive fashion.public static <K,V> Map<K,V> asMap(List<V> aList, Class<K> aClass, String aKeyMethodName)
This method exists because it is sometimes necessary to transform a List into a lookup table of some sort, using unique keys already present in the List data.
The List to be transformed contains objects having a method named aKeyMethodName, and which returns objects of class aKeyClass. Thus, data is extracted from each object to act as its key. Furthermore, the key must be unique. If any duplicates are detected, then an exception is thrown. This ensures that the returned Map will be the same size as the given List, and that no data is silently discarded.
The iteration order of the returned Map is identical to the iteration order of the input List.
public static <K,V> Map<V,K> reverseMap(Map<K,V> aMap)
This method exists because sometimes a lookup operation needs to be performed in a style opposite to an existing Map.
There is an unusual requirement on the Map argument: the map values must be unique. Thus, the returned Map will be the same size as the input Map. If any duplicates are detected, then an exception is thrown.
The iteration order of the returned Map is identical to the iteration order of the input Map.
|
Version 4.10.0 | ||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |