UtilMethods
UtilMethods is a helper class providing many different methods that handle, verify or format many data structures — such as getting, evaluating, and comparing strings; dates and times; and a variety of other object types.
All methods below are invoked via $UtilMethods
. For example, $UtilMethods.mod(20,8)
returns 4
, which can then be used either for rendering or further processing.
Before using UtilMethods, make sure you are familiar with more standard tool sets:
- Date Handling: Date viewtool
- Arithmetic Operations: MathTool
Date/Time Operations#
Methods for converting between date formats, handling date ranges, and timezone operations.
Method | Description | Parameters | Returns |
---|---|---|---|
isDateInRange | Checks if a date falls within a specified range | Date date, Date fromDate, Date toDate | boolean |
dateToHTMLDate | Converts Date to HTML date format | Date x / Date x, String format / Date x, TimeZone tz | String |
dateToHTMLTime | Converts Date to HTML time format | Date x / Date x, TimeZone tz | String |
dateToHTMLDateRange | Creates HTML date range string | Date x, Date y / Date x, Date y, TimeZone tz | String |
dateToHTMLDateTimeRange | Creates HTML datetime range string | Date x, Date y / Date x, Date y, TimeZone tz | String |
dateToHTMLTimeRange | Creates HTML time range string | Date x, Date y | String |
dateToJDBC | Converts Date to JDBC format | Date x | String |
dateToShortJDBC | Converts Date to short JDBC format | Date x | String |
dateToShortJDBCForQuery | Converts Date to short JDBC format for queries | Date x | String |
jdbcToDate | Converts JDBC string to Date | String d | Date |
jdbcDateToHtml | Converts JDBC date to HTML | String jdbcdate | String |
dateToJSTime | Converts Date to JavaScript time format | Date x | String |
dateToPrettyHTMLDate | Converts Date to pretty HTML format | Date x / Date x, TimeZone tz | String |
dateToLongPrettyHTMLDate | Converts Date to long pretty HTML format | Date x | String |
dateToPrettyHTMLDate2 | Alternative pretty HTML date format | Date x | String |
dateToGoogleDate | Converts Date to Google date format | Date x | String |
dateToYear | Extracts year from Date | Date x | String |
dateToIntTime | Converts Date to integer time | Date x | int |
dateToDayViewDate | Converts Date for day view | Date x | String |
dateToLongHTMLDateRange | Creates long HTML date range | Date x, Date y | String |
htmlToDate | Converts HTML date string to Date | String d / Date rDate | Date |
htmlDateTimeToDate | Converts HTML datetime string to Date | String d | Date |
googleDateToDate | Converts Google date string to Date | String d | Date |
htmlDateToHTMLTime | Converts HTML date to HTML time | Date x | String |
shortDateToLuceneDate | Converts short date to Lucene format | String d | String |
pidmsToDate | Converts PIDMS format to Date | String d | Date |
getMonthName | Gets month name by number | int x | String |
getShortMonthName | Gets short month name | int month / String month | String |
getNextMonthName | Gets next month name | int month | String |
getPreviousMonthName | Gets previous month name | int x | String |
getNextMonthNumber | Gets next month number | int month | int |
getPreviousMonthNumber | Gets previous month number | int month | int |
getMonthFromNow | Gets current month name | none | String |
addDate | Adds time to date | Date date, int amount, int field | Date |
addDays | Adds days to date | Date date, int amount | Date |
compareDates | Compares two dates | Date date1, Date date2 / String stringDate1, String stringDate2 | int |
getCurrentDate | Gets current date | none | Date |
now | Gets current date/time | none | Date |
getActualYear | Gets current year | none | String |
getEventDateRange | Gets event date range string | Date date1, Date date2 | String |
elapsedTimeToString | Converts milliseconds to time string | long milliseconds | String |
parseDate | Parses date string with format | String possibleDate, String format | Date |
Date Format Conversion Methods#
isDateInRange(Date date, Date fromDate, Date toDate)
Determines whether a given date falls within the specified date range. The method automatically adjusts the fromDate
to start of day (00:00:00) and toDate
to end of day (23:59:59) for accurate range checking.
dateToHTMLDate(Date x [, String format] [, TimeZone tz])
Converts a Java Date object to HTML-compatible date string format. Supports custom formatting patterns and timezone conversion. When no format is specified, uses default HTML date format.
dateToHTMLTime(Date x [, TimeZone tz])
Formats a Date object as an HTML time string. Optionally accepts a timezone parameter for proper time zone conversion.
Date Range Methods#
dateToHTMLDateRange(Date x, Date y [, TimeZone tz])
Creates a formatted date range string from two Date objects. If the dates are the same, returns a single date. Otherwise, returns a formatted range like "01/15/2023 - 01/20/2023".
dateToHTMLDateTimeRange(Date x, Date y [, TimeZone tz])
Similar to dateToHTMLDateRange but includes time information in the formatted output.
Database Integration Methods#
dateToJDBC(Date x)
Converts a Java Date object to JDBC-compatible string format for database storage and retrieval operations.
dateToShortJDBC(Date x)
Creates a shortened JDBC date format, typically used for date-only fields without time components.
dateToShortJDBCForQuery(Date x)
Specialized JDBC date formatting optimized for use in SQL WHERE
clauses and query parameters.
jdbcToDate(String d)
Parses a JDBC-formatted date string back to a Java Date object for application use.
Month and Year Utilities#
getMonthName(int x)
Returns the full month name for a given month number (1-12).
getShortMonthName(int month)
Returns abbreviated month names (e.g., "Jan", "Feb", "Mar").
getNextMonthName(int month)
/ getPreviousMonthName(int month)
Calculates and returns the name of the next or previous month, handling year rollovers automatically.
String Manipulation#
Methods for string processing, formatting, escaping, and transformation operations.
Method | Description | Parameters | Returns |
---|---|---|---|
escapeSingleQuotes | Escapes single quotes in string | String fixme | String |
escapeDoubleQuotes | Escapes double quotes in string | String fixme | String |
escapeQuotes | Escapes both single and double quotes | String fixme | String |
escapeHTMLSpecialChars | Escapes HTML special characters | String valueSt | String |
escapeUnicodeCharsForHTML | Escapes Unicode characters for HTML | String valueSt | String |
escapeHTMLCodeFromJSON | Escapes HTML code from JSON | String json | String |
htmlLineBreak | Converts line breaks to HTML breaks | String original | String |
fixBreaks | Fixes line break formatting | String fixme | String |
replace | Replaces text in string | String original, String from, String to | String |
formatter | Formats string by replacing patterns | String original, String from, String to | String |
replaceStringBuffer | Replaces text in StringBuffer | StringBuffer original, String from, String to | StringBuffer |
formatterStringBuffer | Formats StringBuffer by replacing patterns | StringBuffer original, String from, String to | StringBuffer |
capitalize | Capitalizes first letter | String s / Object s | String |
prettyString | Returns string or empty if null | String text / String text, String alternateText | String |
prettyShortenString | Pretty shortens string to max length | String text, int maxLength | String |
shortenString | Shortens string to specified length | String s, int l | String |
truncatify | Truncates string with ellipsis | String x / String x, int len | String |
truncFull | Full truncation of string | String x, int len | String |
similarStrings | Checks if strings are similar | String a, String b | boolean |
webifyString | Makes string web-safe | String x | String |
xmlifyString | Makes string XML-safe | String x | String |
htmlifyString | Makes string HTML-safe | String x | String |
httpifyString | Makes string HTTP-safe | String x | String |
csvifyString | Makes string CSV-safe | String x | String |
javaScriptify | Makes string JavaScript-safe | String x | String |
javaScriptifyVariable | Makes string safe for JS variables | String x | String |
wrapLines | Wraps lines at specified width | String original, int wrap | String |
stripUnicode | Strips Unicode characters | String x | String |
inString | Checks if string contains substring | String haystack, String needle | boolean |
dayify | Converts string to day format | String x | String |
convertToNumbers | Converts string to numbers only | String st | String |
convertToFolderName | Converts string to valid folder name | String st | String |
encodeURL | URL encodes string | String url | String |
decodeURL | URL decodes string | String url | String |
encodeURIComponent | Encodes URI component | String uri | String |
concat | Concatenates two strings | String string1, String string2 | String |
concatenate | Concatenates multiple objects | Object... objects | String |
concatenateWithNulls | Concatenates including nulls | Object... objects | String |
listToString | Converts list to string | String stringList | String |
toCamelCase | Converts string to camelCase | String fieldName | String |
xmlEscape | Escapes XML characters | String description | String |
makeXmlSafe | Makes string XML-safe | String unsafeString | String |
makeHtmlSafe | Makes string HTML-safe | String unsafeString | String |
makeHtmlSafeDontConvertNewLines | HTML-safe without converting newlines | String unsafeString | String |
simplifyExtendedAsciiCharacters | Simplifies extended ASCII chars | String unsafeString | String |
makePdfSafe | Makes string PDF-safe | String unsafeString | String |
makeJavaSafe | Makes string Java-safe | String unsafeString | String |
makeUnixSafe | Makes string Unix-safe | String unsafeString | String |
removeCharacters | Removes specified characters | String unsafeString, String charactersToRemove | String |
padToLength | Pads string to specified length | String baseString, int finalLength / with String padString | String |
padToLengthL | Left-pads string to length | String baseString, int finalLength | String |
getClassName | Gets class name from object | Object source | String |
toCommaDelimitedString | Converts list to comma-delimited string | List<E> arli | String |
espaceForVelocity | Escapes string for Velocity | String text | String |
specialSplit | Splits string with text qualifiers | String text, String delim, String textQualifier | String[] |
Text Escaping and Safety Methods#
escapeHTMLSpecialChars(String valueSt)
Escapes special HTML characters (&
, <
, >
, "
, '
) to their HTML entity equivalents, making the string safe for HTML output.
escapeQuotes(String fixme)
Escapes both single and double quotes in a string by adding backslashes, useful for preparing strings for JavaScript or SQL contexts.
javaScriptify(String x)
Prepares a string for safe inclusion in JavaScript code by escaping quotes, line breaks, and other special characters.
String Formatting and Conversion#
capitalize(String s)
Capitalizes the first letter of a string while leaving the rest unchanged. Handles null values gracefully.
truncatify(String x [, int len])
Truncates a string to a specified length, adding ellipsis ("...") if the string was shortened. Default length varies by implementation.
webifyString(String x)
Converts a string to be web-safe by removing or replacing characters that might cause issues in URLs or web contexts.
URL and Encoding Methods#
encodeURL(String url)
/ decodeURL(String url)
Provides URL encoding and decoding functionality using standard percent-encoding rules.
encodeURIComponent(String uri)
Encodes a string to be safe for use as a URI component, similar to JavaScript's encodeURIComponent function.
Advanced String Operations#
specialSplit(String text, String delim, String textQualifier)
Sophisticated string splitting that respects text qualifiers (like quotes in CSV), allowing proper parsing of delimited data with embedded delimiters.
similarStrings(String a, String b)
Determines if two strings are similar using comparison algorithms, useful for fuzzy matching or duplicate detection.
Data Validation#
Methods for validating email addresses, URLs, file paths, and other data formats.
Method | Description | Parameters | Returns |
---|---|---|---|
isValidEmail | Validates email address format | String email / Object email | boolean |
isValidURL | Validates URL format | String url | boolean |
isValidStrictURL | Strict URL validation | String urlString | boolean |
isValidDotCMSPath | Validates dotCMS path format | String path | boolean |
isInt | Checks if string is integer | String intString | boolean |
isSet | Checks if value is set (not null/empty) | Various types | boolean |
isNotSet | Checks if value is not set | Various types | boolean |
isEmpty | Checks if value is empty | Various types | boolean |
isSetCrumb | Checks if breadcrumb is set | String x | boolean |
isSetHTML | Checks if HTML content is set | String x | boolean |
hasValue | Checks if selected values contain value | String selectedValues, String value | boolean |
isUrlLive | Checks if URL is live/accessible | String url, Host host / String url, String hostId | boolean |
isUrlPreview | Checks if URL is in preview mode | String url, Host host / String url, String hostId | boolean |
isLong | Checks if string represents a long number | String longString | boolean |
isNumeric | Checks if string contains only numeric characters | String str | boolean |
contains | Checks if first string contains second string | String string1, String string2 | boolean |
Email and URL Validation#
isValidEmail(String email)
Validates email address format using regular expression pattern matching. Checks for proper structure including @ symbol, domain format, and valid characters.
isValidURL(String url)
Performs basic URL format validation using pattern matching for common URL structures including http, https, and ftp protocols.
isValidStrictURL(String urlString)
Provides more rigorous URL validation using Java's URI class, ensuring both scheme and host are present and properly formatted.
Path and File Validation#
isValidDotCMSPath(String path)
Validates paths according to dotCMS internal path notation rules:
- Must start with forward slash (
/
) - No empty segments or double slashes
- No trailing slashes except for root
- Valid characters for folder and asset names
Data Presence Checks#
isSet(...)
/ isNotSet(...)
Comprehensive null and emptiness checking for various data types including Strings, Collections, Arrays, Dates, and Objects. The isSet
method returns true if the value is not null and not empty, while isNotSet
returns the opposite.
isEmpty(...)
Specifically checks for empty conditions, distinguishing between null and empty states for different data types.
Content Validation#
isSetHTML(String x)
Specialized validation for HTML content, checking not just for null/empty but also for meaningful HTML content.
hasValue(String selectedValues, String value)
Checks if a specific value exists within a delimited string of selected values, useful for form processing and multi-select scenarios.
isLong(String longString)
Validates whether a string can be parsed as a long integer value.
isNumeric(String str)
Determines if a string contains only numeric characters (digits and optionally a minus sign).
contains(String string1, String string2)
Simple containment check to determine if the first string contains the second string as a substring.
File Operations#
Methods for handling file extensions, names, validation, and file system operations.
Method | Description | Parameters | Returns |
---|---|---|---|
isImage | Checks if file is an image | String fileName | boolean |
isVectorImage | Checks if file is vector image | String fileExtension | boolean |
getFileExtension | Gets file extension | String fileName | String |
getFileExtensionIgnoreCase | Gets file extension (case-insensitive) | String fileName | String |
getFileName | Extracts filename from path | String x | String |
fileName | Gets filename from URI | URI uri | String |
validateFileName | Validates filename format | String fileName | String |
getValidFileName | Gets valid filename or throws exception | String fileName | String |
getValidDirectoryName | Gets valid directory name | String phrase | String |
cleanFileSystemPathURI | Cleans filesystem path URI | String path | String |
File Type Detection#
isImage(String fileName)
Determines if a file is an image based on its extension. Checks against common image file extensions including jpg, jpeg, png, gif, bmp, and others.
isVectorImage(String fileExtension)
Specifically checks if a file extension represents a vector image format (svg, eps, ai, dxf).
File Name Processing#
getFileExtension(String fileName)
/ getFileExtensionIgnoreCase(String fileName)
Extracts the file extension from a filename. The case-insensitive version normalizes the extension to lowercase for consistent processing.
getFileName(String x)
Extracts just the filename portion from a full file path, removing directory information.
fileName(URI uri)
Extracts filename from a URI object, with fallback logic for cases where standard path extraction fails.
File Name Validation and Cleaning#
validateFileName(String fileName)
Validates a filename according to filesystem rules and throws IllegalArgumentException
if invalid. Checks for illegal characters and reserved names.
getValidFileName(String fileName)
Similar to validateFileName
but returns a cleaned/valid version of the filename instead of throwing an exception.
getValidDirectoryName(String phrase)
Converts a phrase into a valid directory name by removing or replacing invalid characters and ensuring compliance with filesystem rules.
cleanFileSystemPathURI(String path)
Cleans and normalizes filesystem path URIs, handling various path formats and encoding issues.
HTML/Web Processing#
Methods for HTML processing, JavaScript preparation, and web-related string operations.
Method | Description | Parameters | Returns |
---|---|---|---|
htmlLineBreak | Converts line breaks to HTML | String original | String |
htmlifyString | Makes string HTML-safe | String x | String |
httpifyString | Makes string HTTP-safe | String x | String |
javaScriptify | Makes string JavaScript-safe | String x | String |
javaScriptifyVariable | Makes string safe for JS variables | String x | String |
webifyString | Makes string web-safe | String x | String |
xmlifyString | Makes string XML-safe | String x | String |
escapeHTMLSpecialChars | Escapes HTML special characters | String valueSt | String |
escapeHTMLCodeFromJSON | Escapes HTML in JSON | String json | String |
makeHtmlSafe | Makes string HTML-safe | String unsafeString | String |
makeHtmlSafeDontConvertNewLines | HTML-safe without newline conversion | String unsafeString | String |
getURL | Gets content from URL | String URI | StringBuffer |
getPageChannel | Gets page channel from URI | String uri | String |
HTML Processing#
htmlLineBreak(String original)
Converts standard line breaks (\n
, \r\n
) to HTML <br>
tags for proper display in web browsers.
htmlifyString(String x)
Comprehensive HTML safety processing including entity encoding, script tag handling, and content sanitization.
makeHtmlSafe(String unsafeString)
/ makeHtmlSafeDontConvertNewLines(String unsafeString)
Advanced HTML sanitization with options for preserving or converting line breaks. Handles XSS prevention and content safety.
JavaScript Processing#
javaScriptify(String x)
Prepares strings for embedding in JavaScript code by escaping quotes, line breaks, and special characters that could break JavaScript syntax.
javaScriptifyVariable(String x)
Specialized processing for JavaScript variable names, ensuring compliance with JavaScript identifier rules.
Web Safety Operations#
webifyString(String x)
General web safety processing including URL encoding, special character handling, and format normalization for web contexts.
httpifyString(String x)
HTTP-specific string processing for headers, parameters, and other HTTP protocol elements.
Content Retrieval#
getURL(String URI)
Fetches content from a specified URL and returns it as a StringBuffer. Includes connection handling and error management.
Collection/Array Utilities#
Methods for handling collections, arrays, and list operations.
Method | Description | Parameters | Returns |
---|---|---|---|
join | Joins array elements with separator | String[] strArray, String separator / with boolean empty / List<String> strList, String separator | String |
isSet | Checks if collection/array is set | Collection<?> collection / Map<?,?> map / Object[] array | boolean |
isNotSet | Checks if collection/array is not set | Collection<?> collection | boolean |
randomList | Randomizes list order | List<Object> list / List<Object> list, int number | List<Object> |
arrayToArrayList | Converts array to ArrayList | Object[] oldArray | ArrayList |
arrayToString | Converts array to string | long[] array / ArrayList array / Object[] array / Enumeration array | String |
toCommaDelimitedString | Converts list to comma-delimited string | List<E> arli | String |
specialSplit | Advanced string splitting | Reader reader, char delim, char textQualifier | List<String[]> |
Array and List Joining#
join(String[] strArray, String separator [, boolean empty])
Joins array elements with a specified separator. The boolean parameter controls behavior for empty arrays - when true and array is empty, returns "EMPTY".
join(List<String> strList, String separator)
List version of the join operation, combining all list elements with the specified separator string.
Collection Validation#
isSet(Collection<?> collection)
/ isSet(Map<?,?> map)
/ isSet(Object[] array)
Validates whether collections, maps, or arrays contain elements. Returns true only if the collection is not null and not empty.
List Randomization#
randomList(List<Object> list [, int number])
Randomizes the order of elements in a list. The optional number parameter limits the result to a specific number of random elements.
Array Conversion Utilities#
arrayToArrayList(Object[] oldArray)
Converts a standard Java array to an ArrayList for easier manipulation.
arrayToString(...)
Multiple overloaded methods for converting different array types (long[], ArrayList, Object[], Enumeration) to string representations.
Advanced Parsing#
specialSplit(Reader reader, char delim, char textQualifier)
Advanced CSV-style parsing that reads from a Reader and handles text qualifiers, useful for processing delimited files with embedded separators.
Number Formatting#
Methods for formatting numbers, currencies, percentages, and memory sizes.
Method | Description | Parameters | Returns |
---|---|---|---|
dollarFormat | Formats number as currency | float f | String |
toPriceFormat | Formats as price | double price / float price | String |
toPercentageFormat | Formats as percentage | double weight / float weight | String |
toWeightFormat | Formats as weight | double weight / float weight | String |
toXNumberFormat | Formats number with decimals | double number, int decimals | String |
prettyByteify | Formats bytes in human-readable form | long memory | String |
prettyMemory | Formats memory size | long memory | String |
formatId | Formats ID with specific pattern | long bjuId | String |
multiply | Multiplies two numbers | Number num1, Number num2 | Number |
Currency and Price Formatting#
dollarFormat(float f)
Formats a float value as a dollar amount with appropriate currency symbols and decimal places.
toPriceFormat(double price)
/ toPriceFormat(float price)
Formats numeric values as prices with proper decimal handling and currency display conventions.
Percentage and Weight Formatting#
toPercentageFormat(double weight)
/ toPercentageFormat(float weight)
Converts decimal values to percentage format with %
symbol and appropriate precision.
toWeightFormat(double weight)
/ toWeightFormat(float weight)
Formats numeric values as weights with appropriate units and decimal precision.
Memory and Byte Formatting#
prettyByteify(long memory)
/ prettyMemory(long memory)
Converts byte values to human-readable format using appropriate units (B
, KB
, MB
, GB
, TB
) with proper scaling.
Custom Number Formatting#
toXNumberFormat(double number, int decimals)
Flexible number formatting with configurable decimal places for precise numeric display.
Security#
Methods for obfuscation, input sanitization, and security-related operations.
Method | Description | Parameters | Returns |
---|---|---|---|
obfuscateEmail | Obfuscates email using JavaScript | String email | String |
obfuscateEmailHref | Creates obfuscated email link | String email | String |
obfuscateEmailHrefClass | Obfuscated email link with CSS class | String email, String className | String |
obfuscateCreditCard | Obfuscates credit card number | String ccnum | String |
obfuscateString | Obfuscates string with specified size | String toOfuscate, int size | String |
makeHtmlSafe | Makes string HTML-safe | String unsafeString | String |
makeJavaSafe | Makes string Java-safe | String unsafeString | String |
makeUnixSafe | Makes string Unix-safe | String unsafeString | String |
makePdfSafe | Makes string PDF-safe | String unsafeString | String |
sqlify | Makes string SQL-safe | String fixme | String |
Email Obfuscation#
obfuscateEmail(String email)
Creates JavaScript-based email obfuscation to prevent email harvesting by bots while maintaining functionality for users.
obfuscateEmailHref(String email)
/ obfuscateEmailHrefClass(String email, String className)
Generates obfuscated mailto links using JavaScript, with optional CSS class support for styling.
Data Obfuscation#
obfuscateCreditCard(String ccnum)
Masks credit card numbers showing only the last few digits for security display purposes.
obfuscateString(String toOfuscate, int size)
General string obfuscation with configurable visible character count.
Content Safety#
makeHtmlSafe(String unsafeString)
Comprehensive HTML sanitization to prevent XSS attacks and ensure safe content display.
makeJavaSafe(String unsafeString)
/ makeUnixSafe(String unsafeString)
/ makePdfSafe(String unsafeString)
Platform-specific string sanitization for different execution environments.
Velocity Template#
Methods specifically for Velocity template processing and context handling.
Method | Description | Parameters | Returns |
---|---|---|---|
evaluateVelocity | Evaluates Velocity template string | String vtl, Context ctx | String |
pushVelocityContext | Pushes new Velocity context | Context ctx | Context |
popVelocityContext | Pops Velocity context | VelocityContext vctx | Context |
getVelocityTemplate | Gets Velocity template | String liveUrl | Template |
espaceForVelocity | Escapes string for Velocity | String text | String |
evaluateVelocity(String vtl, Context ctx)
Processes a Velocity template string with the provided context, returning the rendered output.
pushVelocityContext(Context ctx)
/ popVelocityContext(VelocityContext vctx)
Manages Velocity context stack operations for nested template processing and variable scope control.
getVelocityTemplate(String liveUrl)
Retrieves and returns a Velocity Template object from the specified URL for processing.
espaceForVelocity(String text)
Prepares text content for safe inclusion in Velocity templates by escaping special Velocity syntax characters.
Comparison and Equality Operations#
Methods for comparing values and checking equality with null safety.
Method | Description | Parameters | Returns |
---|---|---|---|
equal | Null-safe equality comparison | Object first, Object second | boolean |
notEqual | Null-safe inequality comparison | Object first, Object second | boolean |
different | Alias for notEqual | Object first, Object second | boolean |
compare | Compares integers | int first, int second | int |
compare | Compares long values | long first, long second | int |
compare | Compares Comparable objects | Comparable first, Comparable second | int |
compareIgnoreCase | Case-insensitive string comparison | String first, String second | int |
compareVersions | Compares version strings | String v1, String v2 | boolean |
equal(Object first, Object second)
Provides null-safe equality checking. Returns true if both objects are null or if first.equals(second)
. This prevents NullPointerException when comparing potentially null objects.
compare(...)
methods
Family of comparison methods that return standard comparison integers: -1
for less-than, 0
for equal, 1
for greater-than relationships.
compareVersions(String v1, String v2)
Specialized version string comparison that handles dotCMS version formats including preview versions. Returns true if v1 is greater than v2.
Parsing and Type Conversion#
Methods for safely parsing strings to various data types and converting between types.
Method | Description | Parameters | Returns |
---|---|---|---|
parseLong | Safely parses string to long | String possibleLong, long backupValue | long |
parseDouble | Safely parses string to double | String possibleDouble, double backupValue | double |
parseDirtyDouble | Extracts double from mixed content | String num | double |
getInt | Safely extracts int from Integer | Integer integer, int fallThroughValue | int |
toMap | Converts object properties to map | Object obj | Map<String, Object> |
toString | Converts object to string | Object obj / int num / long num | String |
convertListToHashMap | Converts list to hash map | List<E> arli, String methodToInvoke, Class T | HashMap<T, E> |
parseLong(String possibleLong, long backupValue)
Attempts to parse a string as a long value. If parsing fails, returns the provided backup value instead of throwing an exception.
parseDirtyDouble(String num)
Extracts a double value from a string that may contain non-numeric characters, useful for parsing currency or formatted numbers.
toMap(Object obj)
Uses reflection to convert an object's simple properties (primitives, strings, dates) into a Map representation.
System and Configuration#
Methods for system operations, configuration access, and HTTP request handling.
Method | Description | Parameters | Returns |
---|---|---|---|
getStringFromReader | Reads string content from Reader | Reader rd | String |
getVersionInfoType | Gets version info class type | String type | Class |
getVersionableClass | Gets versionable class by table name | String tableName | Class |
removeBrowserCache | Sets no-cache HTTP headers | HttpServletResponse response | void |
getParameterMap | Extracts parameter map from request | HttpServletRequest req | Map<String,Object> |
isPortFree | Checks if network port is available | int pp | boolean |
isESPortFree | Checks if Elasticsearch port is free | String host, int port | boolean |
getStackTrace | Gets stack trace as string | Throwable throwable | String |
closeDbSilently | Closes database connections silently | none | void |
isAdminMode | Checks if request is in admin mode | HttpServletRequest request, HttpServletResponse response | boolean |
getDefaultCompany | Gets default company instance | none | Company |
getTemporaryDirPath | Gets temporary directory path | none | String |
trimCharArray | Trims whitespace from char array | char[] myArray | char[] |
getStackTrace(Throwable throwable)
Converts a Throwable's stack trace to a string representation, useful for logging and error reporting.
isPortFree(int pp)
/ isESPortFree(String host, int port)
Network connectivity utilities for checking port availability, particularly useful for system configuration and health checks.
removeBrowserCache(HttpServletResponse response)
Sets appropriate HTTP headers to prevent browser caching of responses.
Mathematical Operations#
Methods for mathematical calculations and number operations.
Method | Description | Parameters | Returns |
---|---|---|---|
mod | Calculates modulo operation | Integer x, Integer y | int |
multiply | Multiplies two Number objects | Number num1, Number num2 | Number |
random | Generates random integer | int maxValue / int minValue, int maxValue | int |
getRandomNumber | Generates random number in range | int maxRange | int |
mod(Integer x, Integer y)
Calculates the modulo (remainder) of x divided by y, useful for cyclic operations and mathematical calculations.
multiply(Number num1, Number num2)
Intelligently multiplies two Number objects of potentially different types (Double, Float, Long, Integer), returning the appropriate Number type.
random(...)
methods
Generate random integers within specified ranges, useful for randomization operations in templates.
Base64 Encoding#
Methods for Base64 encoding and decoding operations.
Method | Description | Parameters | Returns |
---|---|---|---|
base64Encode | Encodes string to Base64 | String incomingString | String |
base64Decode | Decodes Base64 to string | String incomingString | String |
base64Encode(String incomingString)
Converts a string to its Base64 encoded representation, useful for data transmission and storage.
base64Decode(String incomingString)
Decodes a Base64 encoded string back to its original form.
Additional Utility Methods#
Various helper methods that don't fit into the main categories but provide useful functionality.
Method | Description | Parameters | Returns |
---|---|---|---|
get | Gets value with supplier fallback | T instance, Supplier<T> supplier | T |
getUserFullName | Gets user's full name | String userId | String |
getUserEmailAddress | Gets user's email address | String userId | String |
getUserEmail | Gets user email from User object | User user | String |
getCharsetConfiguration | Gets charset configuration | none | String |
getTimeList | Gets list of times | int start, int duration | List |
getCookieValue | Gets cookie value by name | Cookie[] cookies, String cookieName | String |
getCookie | Gets cookie by name | Cookie[] cookies, String cookieName | Cookie |
getShippingTypeName | Gets shipping type name | int shippingType | String |
getPaymentTypeName | Gets payment type name | int paymentType | String |
doubleQuoteIt | Wraps string in double quotes | String word | String |
pluralize | Creates plural form with count | long num, String word | String |
expandArray | Expands array with new slots | Object[] small, int numNewSlots / long[] small, int numNewSlots | Object[] / long[] |
shortstring | Smart text shortening | String text, int maxNumberOfChars, boolean includeEllipsis | String |
formatId | Formats ID with zero padding | long bjuId | String |
getDotCMSStackTrace | Gets dotCMS-specific stack trace | none | String |
isSetOrGet | Conditional value getter | T toEvaluate, T defaultValue | T |
exceedsMaxLength | Checks if value exceeds max length | T value, int maxLength | boolean |
extractUserIdOrNull | Safely extracts user ID | User user | String |
isLuceneQuery | Validates Lucene query syntax | String query | boolean |