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/Time Operations#


Methods for converting between date formats, handling date ranges, and timezone operations.

MethodDescriptionParametersReturns
isDateInRangeChecks if a date falls within a specified rangeDate date, Date fromDate, Date toDateboolean
dateToHTMLDateConverts Date to HTML date formatDate x / Date x, String format / Date x, TimeZone tzString
dateToHTMLTimeConverts Date to HTML time formatDate x / Date x, TimeZone tzString
dateToHTMLDateRangeCreates HTML date range stringDate x, Date y / Date x, Date y, TimeZone tzString
dateToHTMLDateTimeRangeCreates HTML datetime range stringDate x, Date y / Date x, Date y, TimeZone tzString
dateToHTMLTimeRangeCreates HTML time range stringDate x, Date yString
dateToJDBCConverts Date to JDBC formatDate xString
dateToShortJDBCConverts Date to short JDBC formatDate xString
dateToShortJDBCForQueryConverts Date to short JDBC format for queriesDate xString
jdbcToDateConverts JDBC string to DateString dDate
jdbcDateToHtmlConverts JDBC date to HTMLString jdbcdateString
dateToJSTimeConverts Date to JavaScript time formatDate xString
dateToPrettyHTMLDateConverts Date to pretty HTML formatDate x / Date x, TimeZone tzString
dateToLongPrettyHTMLDateConverts Date to long pretty HTML formatDate xString
dateToPrettyHTMLDate2Alternative pretty HTML date formatDate xString
dateToGoogleDateConverts Date to Google date formatDate xString
dateToYearExtracts year from DateDate xString
dateToIntTimeConverts Date to integer timeDate xint
dateToDayViewDateConverts Date for day viewDate xString
dateToLongHTMLDateRangeCreates long HTML date rangeDate x, Date yString
htmlToDateConverts HTML date string to DateString d / Date rDateDate
htmlDateTimeToDateConverts HTML datetime string to DateString dDate
googleDateToDateConverts Google date string to DateString dDate
htmlDateToHTMLTimeConverts HTML date to HTML timeDate xString
shortDateToLuceneDateConverts short date to Lucene formatString dString
pidmsToDateConverts PIDMS format to DateString dDate
getMonthNameGets month name by numberint xString
getShortMonthNameGets short month nameint month / String monthString
getNextMonthNameGets next month nameint monthString
getPreviousMonthNameGets previous month nameint xString
getNextMonthNumberGets next month numberint monthint
getPreviousMonthNumberGets previous month numberint monthint
getMonthFromNowGets current month namenoneString
addDateAdds time to dateDate date, int amount, int fieldDate
addDaysAdds days to dateDate date, int amountDate
compareDatesCompares two datesDate date1, Date date2 / String stringDate1, String stringDate2int
getCurrentDateGets current datenoneDate
nowGets current date/timenoneDate
getActualYearGets current yearnoneString
getEventDateRangeGets event date range stringDate date1, Date date2String
elapsedTimeToStringConverts milliseconds to time stringlong millisecondsString
parseDateParses date string with formatString possibleDate, String formatDate

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.

MethodDescriptionParametersReturns
escapeSingleQuotesEscapes single quotes in stringString fixmeString
escapeDoubleQuotesEscapes double quotes in stringString fixmeString
escapeQuotesEscapes both single and double quotesString fixmeString
escapeHTMLSpecialCharsEscapes HTML special charactersString valueStString
escapeUnicodeCharsForHTMLEscapes Unicode characters for HTMLString valueStString
escapeHTMLCodeFromJSONEscapes HTML code from JSONString jsonString
htmlLineBreakConverts line breaks to HTML breaksString originalString
fixBreaksFixes line break formattingString fixmeString
replaceReplaces text in stringString original, String from, String toString
formatterFormats string by replacing patternsString original, String from, String toString
replaceStringBufferReplaces text in StringBufferStringBuffer original, String from, String toStringBuffer
formatterStringBufferFormats StringBuffer by replacing patternsStringBuffer original, String from, String toStringBuffer
capitalizeCapitalizes first letterString s / Object sString
prettyStringReturns string or empty if nullString text / String text, String alternateTextString
prettyShortenStringPretty shortens string to max lengthString text, int maxLengthString
shortenStringShortens string to specified lengthString s, int lString
truncatifyTruncates string with ellipsisString x / String x, int lenString
truncFullFull truncation of stringString x, int lenString
similarStringsChecks if strings are similarString a, String bboolean
webifyStringMakes string web-safeString xString
xmlifyStringMakes string XML-safeString xString
htmlifyStringMakes string HTML-safeString xString
httpifyStringMakes string HTTP-safeString xString
csvifyStringMakes string CSV-safeString xString
javaScriptifyMakes string JavaScript-safeString xString
javaScriptifyVariableMakes string safe for JS variablesString xString
wrapLinesWraps lines at specified widthString original, int wrapString
stripUnicodeStrips Unicode charactersString xString
inStringChecks if string contains substringString haystack, String needleboolean
dayifyConverts string to day formatString xString
convertToNumbersConverts string to numbers onlyString stString
convertToFolderNameConverts string to valid folder nameString stString
encodeURLURL encodes stringString urlString
decodeURLURL decodes stringString urlString
encodeURIComponentEncodes URI componentString uriString
concatConcatenates two stringsString string1, String string2String
concatenateConcatenates multiple objectsObject... objectsString
concatenateWithNullsConcatenates including nullsObject... objectsString
listToStringConverts list to stringString stringListString
toCamelCaseConverts string to camelCaseString fieldNameString
xmlEscapeEscapes XML charactersString descriptionString
makeXmlSafeMakes string XML-safeString unsafeStringString
makeHtmlSafeMakes string HTML-safeString unsafeStringString
makeHtmlSafeDontConvertNewLinesHTML-safe without converting newlinesString unsafeStringString
simplifyExtendedAsciiCharactersSimplifies extended ASCII charsString unsafeStringString
makePdfSafeMakes string PDF-safeString unsafeStringString
makeJavaSafeMakes string Java-safeString unsafeStringString
makeUnixSafeMakes string Unix-safeString unsafeStringString
removeCharactersRemoves specified charactersString unsafeString, String charactersToRemoveString
padToLengthPads string to specified lengthString baseString, int finalLength / with String padStringString
padToLengthLLeft-pads string to lengthString baseString, int finalLengthString
getClassNameGets class name from objectObject sourceString
toCommaDelimitedStringConverts list to comma-delimited stringList<E> arliString
espaceForVelocityEscapes string for VelocityString textString
specialSplitSplits string with text qualifiersString text, String delim, String textQualifierString[]

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.

MethodDescriptionParametersReturns
isValidEmailValidates email address formatString email / Object emailboolean
isValidURLValidates URL formatString urlboolean
isValidStrictURLStrict URL validationString urlStringboolean
isValidDotCMSPathValidates dotCMS path formatString pathboolean
isIntChecks if string is integerString intStringboolean
isSetChecks if value is set (not null/empty)Various typesboolean
isNotSetChecks if value is not setVarious typesboolean
isEmptyChecks if value is emptyVarious typesboolean
isSetCrumbChecks if breadcrumb is setString xboolean
isSetHTMLChecks if HTML content is setString xboolean
hasValueChecks if selected values contain valueString selectedValues, String valueboolean
isUrlLiveChecks if URL is live/accessibleString url, Host host / String url, String hostIdboolean
isUrlPreviewChecks if URL is in preview modeString url, Host host / String url, String hostIdboolean
isLongChecks if string represents a long numberString longStringboolean
isNumericChecks if string contains only numeric charactersString strboolean
containsChecks if first string contains second stringString string1, String string2boolean

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.

MethodDescriptionParametersReturns
isImageChecks if file is an imageString fileNameboolean
isVectorImageChecks if file is vector imageString fileExtensionboolean
getFileExtensionGets file extensionString fileNameString
getFileExtensionIgnoreCaseGets file extension (case-insensitive)String fileNameString
getFileNameExtracts filename from pathString xString
fileNameGets filename from URIURI uriString
validateFileNameValidates filename formatString fileNameString
getValidFileNameGets valid filename or throws exceptionString fileNameString
getValidDirectoryNameGets valid directory nameString phraseString
cleanFileSystemPathURICleans filesystem path URIString pathString

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.

MethodDescriptionParametersReturns
htmlLineBreakConverts line breaks to HTMLString originalString
htmlifyStringMakes string HTML-safeString xString
httpifyStringMakes string HTTP-safeString xString
javaScriptifyMakes string JavaScript-safeString xString
javaScriptifyVariableMakes string safe for JS variablesString xString
webifyStringMakes string web-safeString xString
xmlifyStringMakes string XML-safeString xString
escapeHTMLSpecialCharsEscapes HTML special charactersString valueStString
escapeHTMLCodeFromJSONEscapes HTML in JSONString jsonString
makeHtmlSafeMakes string HTML-safeString unsafeStringString
makeHtmlSafeDontConvertNewLinesHTML-safe without newline conversionString unsafeStringString
getURLGets content from URLString URIStringBuffer
getPageChannelGets page channel from URIString uriString

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.

MethodDescriptionParametersReturns
joinJoins array elements with separatorString[] strArray, String separator / with boolean empty / List<String> strList, String separatorString
isSetChecks if collection/array is setCollection<?> collection / Map<?,?> map / Object[] arrayboolean
isNotSetChecks if collection/array is not setCollection<?> collectionboolean
randomListRandomizes list orderList<Object> list / List<Object> list, int numberList<Object>
arrayToArrayListConverts array to ArrayListObject[] oldArrayArrayList
arrayToStringConverts array to stringlong[] array / ArrayList array / Object[] array / Enumeration arrayString
toCommaDelimitedStringConverts list to comma-delimited stringList<E> arliString
specialSplitAdvanced string splittingReader reader, char delim, char textQualifierList<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.

MethodDescriptionParametersReturns
dollarFormatFormats number as currencyfloat fString
toPriceFormatFormats as pricedouble price / float priceString
toPercentageFormatFormats as percentagedouble weight / float weightString
toWeightFormatFormats as weightdouble weight / float weightString
toXNumberFormatFormats number with decimalsdouble number, int decimalsString
prettyByteifyFormats bytes in human-readable formlong memoryString
prettyMemoryFormats memory sizelong memoryString
formatIdFormats ID with specific patternlong bjuIdString
multiplyMultiplies two numbersNumber num1, Number num2Number

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.

MethodDescriptionParametersReturns
obfuscateEmailObfuscates email using JavaScriptString emailString
obfuscateEmailHrefCreates obfuscated email linkString emailString
obfuscateEmailHrefClassObfuscated email link with CSS classString email, String classNameString
obfuscateCreditCardObfuscates credit card numberString ccnumString
obfuscateStringObfuscates string with specified sizeString toOfuscate, int sizeString
makeHtmlSafeMakes string HTML-safeString unsafeStringString
makeJavaSafeMakes string Java-safeString unsafeStringString
makeUnixSafeMakes string Unix-safeString unsafeStringString
makePdfSafeMakes string PDF-safeString unsafeStringString
sqlifyMakes string SQL-safeString fixmeString

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.

MethodDescriptionParametersReturns
evaluateVelocityEvaluates Velocity template stringString vtl, Context ctxString
pushVelocityContextPushes new Velocity contextContext ctxContext
popVelocityContextPops Velocity contextVelocityContext vctxContext
getVelocityTemplateGets Velocity templateString liveUrlTemplate
espaceForVelocityEscapes string for VelocityString textString

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.

MethodDescriptionParametersReturns
equalNull-safe equality comparisonObject first, Object secondboolean
notEqualNull-safe inequality comparisonObject first, Object secondboolean
differentAlias for notEqualObject first, Object secondboolean
compareCompares integersint first, int secondint
compareCompares long valueslong first, long secondint
compareCompares Comparable objectsComparable first, Comparable secondint
compareIgnoreCaseCase-insensitive string comparisonString first, String secondint
compareVersionsCompares version stringsString v1, String v2boolean

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.

MethodDescriptionParametersReturns
parseLongSafely parses string to longString possibleLong, long backupValuelong
parseDoubleSafely parses string to doubleString possibleDouble, double backupValuedouble
parseDirtyDoubleExtracts double from mixed contentString numdouble
getIntSafely extracts int from IntegerInteger integer, int fallThroughValueint
toMapConverts object properties to mapObject objMap<String, Object>
toStringConverts object to stringObject obj / int num / long numString
convertListToHashMapConverts list to hash mapList<E> arli, String methodToInvoke, Class THashMap<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.

MethodDescriptionParametersReturns
getStringFromReaderReads string content from ReaderReader rdString
getVersionInfoTypeGets version info class typeString typeClass
getVersionableClassGets versionable class by table nameString tableNameClass
removeBrowserCacheSets no-cache HTTP headersHttpServletResponse responsevoid
getParameterMapExtracts parameter map from requestHttpServletRequest reqMap<String,Object>
isPortFreeChecks if network port is availableint ppboolean
isESPortFreeChecks if Elasticsearch port is freeString host, int portboolean
getStackTraceGets stack trace as stringThrowable throwableString
closeDbSilentlyCloses database connections silentlynonevoid
isAdminModeChecks if request is in admin modeHttpServletRequest request, HttpServletResponse responseboolean
getDefaultCompanyGets default company instancenoneCompany
getTemporaryDirPathGets temporary directory pathnoneString
trimCharArrayTrims whitespace from char arraychar[] myArraychar[]

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.

MethodDescriptionParametersReturns
modCalculates modulo operationInteger x, Integer yint
multiplyMultiplies two Number objectsNumber num1, Number num2Number
randomGenerates random integerint maxValue / int minValue, int maxValueint
getRandomNumberGenerates random number in rangeint maxRangeint

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.

MethodDescriptionParametersReturns
base64EncodeEncodes string to Base64String incomingStringString
base64DecodeDecodes Base64 to stringString incomingStringString

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.

MethodDescriptionParametersReturns
getGets value with supplier fallbackT instance, Supplier<T> supplierT
getUserFullNameGets user's full nameString userIdString
getUserEmailAddressGets user's email addressString userIdString
getUserEmailGets user email from User objectUser userString
getCharsetConfigurationGets charset configurationnoneString
getTimeListGets list of timesint start, int durationList
getCookieValueGets cookie value by nameCookie[] cookies, String cookieNameString
getCookieGets cookie by nameCookie[] cookies, String cookieNameCookie
getShippingTypeNameGets shipping type nameint shippingTypeString
getPaymentTypeNameGets payment type nameint paymentTypeString
doubleQuoteItWraps string in double quotesString wordString
pluralizeCreates plural form with countlong num, String wordString
expandArrayExpands array with new slotsObject[] small, int numNewSlots / long[] small, int numNewSlotsObject[] / long[]
shortstringSmart text shorteningString text, int maxNumberOfChars, boolean includeEllipsisString
formatIdFormats ID with zero paddinglong bjuIdString
getDotCMSStackTraceGets dotCMS-specific stack tracenoneString
isSetOrGetConditional value getterT toEvaluate, T defaultValueT
exceedsMaxLengthChecks if value exceeds max lengthT value, int maxLengthboolean
extractUserIdOrNullSafely extracts user IDUser userString
isLuceneQueryValidates Lucene query syntaxString queryboolean