Utility helpers exposed to Velocity templates and server-side JavaScript as the formatter variable. Provides null tolerant type conversion, date and time arithmetic and formatting, number and currency formatting, string and HTML helpers, collection factories and a handful of small services such as random identifiers and translation lookups. A single instance is held in the Milton root context and injected into every template and script data model under the name formatter, so it carries no per request state. Most methods are annotated for GraalJS host access and are therefore callable from .mjs code as well as from Velocity and MVEL.

Group: Managers


Properties

PropertyReturnsDescription
baseWebsiteUrlStringScheme and domain of the website being served by the current request, such as https://www.example.com, with no trailing slash. Null when the request is not being served from a website root folder.
countryCodeOfOrgCountryCodeCountry code record for the current root folder organisation's country, resolved from its two letter ISO code. Null when there is no current root folder or the organisation has no country set.
countryCodesCountryCodesThe platform's country code lookup table, which maps between two letter and three letter ISO codes, country names and dialling codes.
cryptoCryptoImplThe platform's cryptography helper, which provides hashing, HMAC signing and symmetric encryption to templates and scripts.
currentDateServiceCurrentDateServiceThe platform's current date service, the single source of 'now' for the server, which tests can override to freeze or shift time.
currentRootFolderRootFolderRoot folder the current request is being served from, which is the website, admin or organisation root that determines the tenant and the resource tree. Null outside a request.
geoIPServiceGeoIPServiceThe platform's GeoIP service, which resolves an IP address to a country, region and city. Null when the server was built without one.
listResourceListCreates a new empty ResourceList. Identical to newList, and provided so templates can use property syntax.
nowDateCurrent date and time as seen by the server, taken from the platform's current date service rather than the system clock so that tests can control it.
onWebsitebooleanTrue when the current request is being served from a website rather than from the admin console.
portintPort that the current HTTP request arrived on, taken from the Host header, defaulting to 80 when there is no request or no header.
portStringStringPort suffix to append when building an absolute URL, such as :8080. Empty for the default ports 80 and 443 so that ordinary URLs do not carry a redundant port.
queryStringStringQuery string of the current request, rebuilt from its parameters and including the leading question mark. Empty when there is no request or the request has no parameters. Values are not re-encoded.
randomGuidStringA freshly generated random UUID in its standard hyphenated string form, for use as a unique identifier.
repoAppServiceRepoAppServiceLazily resolves the repo app service from the Milton context and caches it on this instance.
securebooleanTrue when the current request should be treated as HTTPS, either because it arrived on port 443 or 8443, because the request itself reports HTTPS, or because the current tenant organisation has force HTTPS switched on.
yearStartDateMidnight on the first day of January of the current year, in the server's default timezone.

Methods

debug(Object obs) · newNarrative() · toString(Object o) · toBool(Object o) · toBool(Object o, boolean defaultVal) · toDecimal(Object o, Object places) · toDecimal(Object o, int places, String roundMode) · toDoubleSafe(Object o) · toDouble(Object o) · toDouble(Object o, boolean withNulls) · toInteger(Object o) · toInteger(Object o, boolean withNulls) · toLong(Object o) · toLongSafe(Object o) · toLong(Object oVal, boolean withNulls) · toPath(String s) · getFileName(String s) · getYear(Object o) · getMonth(Object o) · getDayOfMonth(Object o) · getHour(Object o) · getHour(Object o, String timezone) · getMinute(Object o) · getDayOfWeek(Object o) · getDayOfWeekName(Object o) · formatDate(Object o) · formatDateWithLocale(Object o, String localeId) · formatDate(Object o, String timezone) · formatTime(Object o) · formatTime(Object o, String timezone) · formatTimeLong(Object o, String timezone) · formatDateLong(Object o) · formatDateLong(Object o, String timezone) · formatDateTime(Object o) · formatDateWithPattern(Object o, String pattern) · getFirstOfMonth(Object month) · getFirstOfMonth(Object month, String timeZone) · newDate(Object year, Object month, Object day) · calcNextBirthday(Object date) · formatDateTime(Object o, String timezone) · formatDateISO8601(Object o) · formatDateISO8601(Object o, String timezone) · formatAge(Object o) · formatAge(Object o, boolean withTrans) · formatMinsAsDuration(Object o) · formatMinsAsDuration(Object o, boolean numeric) · pad2(long l) · pad(long l, int length) · padWith(String padChar, Object rawVal, int length) · getDateTime(Object o) · getDateTime(Object o, String timezoneId) · toPercent(Object num, Object div) · toPercent(Object num, Object div, int decimalPlaces) · toPercent(Object num, Object div, boolean appendSymbol, boolean withBlanks) · toPercent(Object num, Object div, boolean appendSymbol, boolean withBlanks, int decimalPlaces) · format(Object o) · stripExt(String s) · fileExt(String fileName) · gt(Object val1, Object val2) · gte(Object val1, Object val2) · lte(Object val1, Object val2) · lt(Object val1, Object val2) · eq(Object val1, Object val2) · not(Object o) · htmlEncode(Object ob) · htmlAttEncode(String s2) · htmlAttDecode(String s2) · percentDecode(String s) · percentDecodeSafe(String s) · percentEncode(String s) · between(Object oVal, Object oStart, Object oFinish) · toDate(Object oVal) · toSqlDate(Object oVal) · toSqlTimestamp(Object oVal) · toJodaDate(Object oVal) · parseDateWithPattern(String dateS, String pattern) · parseDateWithPattern(String dateS, String pattern, String timezone) · toHtmlInputValue(String value) · toPlain(String html) · toPlain(String html, boolean includeNewLines) · generateTextFromHtml(String html) · getNow() · getYearStart() · yearStart(Date dt) · monthStart(Date dt, int month) · monthStart(Date dt) · yearEnd() · yearEnd(Date dt) · monthEnd(Date dt, int month) · monthEnd(Date dt) · durationSecs(Object start, Object finish) · durationHours(Object start, Object finish) · durationMins(Object start, Object finish) · durationDays(Object start, Object finish) · durationYears(Object start, Object finish) · getMonthName(Object o) · getMonthName(int i) · getCurrentDateService() · ifEqual(String ifEqual, String ifNotEqual, Object o1, Object o2) · isEqual(Object o1, Object o2) · isNotEqual(Object o1, Object o2) · ifNull(Object val, Object defaultVal) · ifEmpty(Object val, Object defaultVal) · ifTrue(Object bb, Object o1, Object o2) · ifFalse(Object bb, Object o1, Object o2) · newList() · getList() · parseDate(String s) · parseTime(Object o) · sdf(boolean hasTime) · toFloat(Object val) · toBigDecimalSafe(Object val) · toBigDecimal(Object val) · toBigDecimal(Object o, Integer decimals) · calc(ResourceList list) · where(String mvelExpr, ResourceList list) · checked(Object o) · selected(Object o) · checkbox(String name, Object oChecked) · checkbox(String id, String name, Object oChecked) · checkbox(Object oId, String name, Object oChecked, Object oValue) · call(Object o) · bsswitch(Object oId, String name, Object oChecked, Object oValue) · radioEq(String id, String name, String currentValue, String value) · radioEq(String id, String name, String currentValue, String value, String className) · radio(String id, String name, Object oChecked, String value) · radio(String id, String name, Object oChecked, String value, String className) · option(Relational value, Object currentValue) · option(Object value, Object oText, Object currentValue) · option(Object value, Object oText, Object currentValue, Object dataIdValue) · select(String name, Map<Object,Object> data) · select(String name, Object currentVal, Map<Object,Object> data) · select(String id, String name, String htmlClass, Object currentVal, Map<Object,Object> data) · getPort() · isSecure() · getPortString() · profilePicHref(Profile p) · toCsvArgs(String s) · toCsv(Iterable list) · toLineOfVals(Iterable list, String seperator) · toProperties(Map<Object,Object> map) · toCsv(String[] list) · toCsv(Object list) · fromCsv(Object o) · toJson(Object val) · toJson(Object val, int indent) · parseJson(String jsonStr) · parseJson(String jsonStr, boolean throwException) · addDays(Date now, Integer days) · addMilliseconds(Date now, Integer milliseconds) · addYears(Date now, Integer years) · addMonths(Date now, Integer months) · addDays(Object now, Object days) · getDaysBetween(Object from, Object to) · addSeconds(Date now, int seconds) · addMinutes(Date now, int mins) · addHours(Date now, int hours) · getBaseWebsiteUrl() · getBaseWebsiteUrl(Website w) · getCleanedRootDomain(String domainName) · getDomainName(Website w) · getDomainName(Website w, boolean useVersion) · getDomainName(Website w, boolean useVersion, boolean includePort) · getKademiDomainName(Website w, boolean useVersion, boolean includePort) · isNotNull(Object o) · isNull(Object o) · getVersionId(WebsiteBranchResource rf) · daysBetween(Date from, Date to) · endofDay(Date dt) · endOfDay(Date dt) · endofDay(Date dt, String timezone) · endOfDay(Date dt, String timezone) · startOfDay(Date dt) · startOfDay(Date dt, String timezone) · truncate(String s, int max) · truncateToEnd(String s, int max) · newReadonlyList(List list) · newStack() · newArrayList() · newCommonList() · newCommonList(Collection from) · newArrayList(Object[] arr) · newMap() · newSet() · newMapBuilder() · formatBytes(Object o) · formatSecsAsDuration(Object o) · formatCurrency(Object o) · formatCurrency(Object o, String unitSymbol, String unitPosition, Integer numberOfDecimal) · formatCurrency(Object o, Boolean leadingZeros) · formatDecimal(Object o, Integer numberDecimals) · formatMaxDecimals(Object o, Integer numberDecimals) · getStartOfWeek(Date dt) · capitalizeString(Object o) · getCountryCodes() · getCountryCodeOfOrg() · sortByProperty(List list, String propertyName) · sortReverse(List list) · sort(List list) · toggleParamVal(String paramName, String val) · toggleParamVal(String paramName, String val, boolean uniqueParam) · paramSelected(String paramName, String value, String active) · addQueryParam(String href, String paramName, Object paramVal) · getQueryString() · addNum(Object from, Object addAmount) · split(String s, String sep) · split(String s) · splitByAnything(String s) · toList(Object arr) · formatNumeric(Object o, String format) · formatNumeric(Object o) · formatNumericNoDecimal(Object o) · isNumeric(Object o) · isType(Object source, String className) · getSimpleType(Object source) · toBase64String(Object o) · toBase64UrlString(Object o) · fromBase64AsString(String base64) · fromBase64AsByteArray(String base64) · toBigInteger(String val, int radix) · joinByteArray(byte[] b1, byte[] b2) · copyFromArray(byte[] arr, int from, int to) · copyFromArray(char[] arr, int from, int to) · byteArrayToHexString(byte[] bytes) · getCrypto() · getGeoIPService() · parseHtml(String html) · formatJodaDate(Object date, String pattern) · formatJodaDate(Object date, String pattern, String timeZone) · formatAsCleanId(String title) · cleanUserId(String userId) · formatPhoneNumber(Object obj, Object phone) · formatPhoneNumber(Object obj, Object phone, String format) · textFromHtml(String htmlContents) · propertyOfObject(Object o1, Object o2) · newTextOptionType(Object placeholder) · newListOptionBuilder() · toPlainEmail(Object o) · textToHtml(String text) · getRandomGuid() · formatUnits(Object o) · encodeAsHtmlEntities(String s) · firstNotNull(Object vals) · firstNotNull2(Object vals) · safeGet(List list, int pos) · safeGet(Object[] array, int pos) · cleanString(Object o) · cleanString(Object o, boolean makePlain) · containsDangerous(String dirtyComment) · paginator() · paginator(int defaultPageSize) · translate(String sourceType, String sourceId, String field, String langCode) · translate(String sourceType, String sourceId, String field) · translate(String sourceType, String sourceId) · translate(Translatable source, String field) · translate(String sourceText) · asUser(Object oUser) · asGroup(Object oGroup) · asWebsite(Object oWebsite) · formatDateWithHyphens(Date dt) · deCamelise(String camelCase) · findDayOnOrBefore(int dayIndex, Date dt) · isEmpty(Object o) · isNotEmpty(Object o) · foreach(Object iterable, BiConsumer consumer) · foreach(Object iterable, ScriptObjectMirror r) · _foreach(Object[] arr, BiConsumer r) · _foreach(Iterable it, BiConsumer r) · breakForeach() · stringJoin(List<String> list, String separator) · parseDateISO8601(String s) · dateTimePattern(String context) · datePattern(String context) · andClause(Object a, Object b) · orClause(Object a, Object b) · parseExtraFieldDef(String name, String fieldDef) · formatToCleanHtml(String original) · parseSearch(String q) · newExtraField(String name, boolean required) · getCurrentRootFolder() · randomInt(Object oRange) · randomHex(int numDigits) · randomAlpha(int numChars) · randomAlpha(int numChars, String excludedCharacters) · normalizeString(String s) · toRanges(Collection originalList, int partitionSize) · splitList(Collection src, int partitionSize) · newTable(String id) · newFormContext() · newFormContext(Map<String,String> params) · newSearchProperties(Integer startPos, Integer pageSize) · newSearchProperties(Integer startPos, Integer pageSize, String orderBy, String orderDir) · newStringBuilder() · newMembershipList() · isImage(String newName, String contentType) · lowest(Object vals) · highest(Object vals) · obfuscateEmail(String email) · convertMapToParamString(Map<String,String> params) · parseParamStringToMap(String params) · link(Object o) · link(Object o, String cls) · link(String href, String text, String cls) · calcGaussianDecay(double elapsedDurationActual, double standardDev, double multiplier) · docsHtml(Object target) · docsText(Object target) · supplyInStopWatch(String name, Supplier r) · runInStopWatch(String name, Runnable r) · lapStopWatch(String name) · replaceText(String source, String findText, String replaceWith) · replaceAllText(String source, String findText, String replaceWith) · checkPathTraversal(String inputString) · toMap(Object source) · toMap(List list, String keyPropName) · standardiseTimezoneId(String timezoneId)

debug(Object obs)

Returns: void

Writes the given values to the server log at info level, prefixed with 'debug:'. Intended as a quick trace aid while developing a template or script; it produces no output in the rendered page.

ParameterDescription
obsthe values to log

newNarrative()

Returns: Narrative

Creates a new empty Narrative, the collector object that several services use to report a step by step explanation of a complex operation back to the caller.

toString(Object o)

Returns: String

Null safe conversion to a trimmed string. Returns an empty string for null and for any value that isEmpty considers empty, decodes a byte array using the platform default charset, and otherwise returns the value's own toString with surrounding whitespace removed.

ParameterDescription
othe value to convert, may be null

toBool(Object o)

Returns: Boolean

Converts almost anything truthy to a Boolean, or returns null when the value is null or blank. Booleans pass through, an Integer is true when it is not zero, a collection is true when it is not empty, and a string is true when it is 'true', 'yes' or '1' ignoring case and surrounding whitespace. Any other type raises a runtime exception.

ParameterDescription
othe value to interpret as a boolean, may be null

toBool(Object o, boolean defaultVal)

Returns: boolean

Converts almost anything truthy to a boolean using the same rules as the single argument toBool, falling back to the given default when the value is null or blank.

ParameterDescription
othe value to interpret as a boolean, may be null
defaultValthe value to return when the input is null or an empty string

toDecimal(Object o, Object places)

Returns: BigDecimal

Converts almost any numeric value to a BigDecimal scaled to the given number of decimal places, rounding half up when rounding is needed.

ParameterDescription
othe value to convert, may be null
placesthe number of decimal places, itself converted with toInteger

toDecimal(Object o, int places, String roundMode)

Returns: BigDecimal

Converts almost any numeric value to a BigDecimal at the given number of decimal places, applying the named java.math.RoundingMode when rounding is needed. Accepts BigDecimal, Double, Float, Integer, Long, a numeric string and the search aggregation types KSingleValue and KBucket. Null and an empty string convert to zero, a non-numeric string raises a runtime exception, and an unrecognised rounding mode logs a warning and returns null.

ParameterDescription
othe value to convert, may be null
placesthe number of decimal places to scale to
roundModethe RoundingMode name such as CEILING, DOWN, UP, HALF_UP, HALF_DOWN or HALF_EVEN, blank for HALF_UP

toDoubleSafe(Object o)

Returns: Double

Converts a value to a Double in the same way as toDouble, but returns null instead of throwing when the value cannot be converted.

ParameterDescription
othe value to convert, may be null

toDouble(Object o)

Returns: Double

Converts almost any numeric value to a Double. Empty and null inputs become zero rather than null, a boolean becomes one or zero, a NaN Double becomes zero, and a non-numeric string raises a runtime exception.

ParameterDescription
othe value to convert, may be null

toDouble(Object o, boolean withNulls)

Returns: Double

Converts almost any numeric value to a Double, choosing whether empty or unconvertible input comes back as null or as zero. With withNulls set, an empty value, a non-numeric string and an unsupported type all return null instead of returning zero or throwing.

ParameterDescription
othe value to convert, may be null
withNullstrue to return null for empty or unconvertible input, false to return zero or throw

toInteger(Object o)

Returns: Integer

Converts almost anything to an Integer by delegating to toLong and narrowing the result, so null and empty values become zero rather than null. Beware that values outside the int range wrap.

ParameterDescription
othe value to convert, may be null

toInteger(Object o, boolean withNulls)

Returns: Integer

Converts almost anything to an Integer by delegating to toLong and narrowing the result, choosing whether empty input comes back as null or as zero.

ParameterDescription
othe value to convert, may be null
withNullstrue to return null for empty or unconvertible input, false to return zero or throw

toLong(Object o)

Returns: Long

Converts almost anything to a Long, treating null and empty values as zero so the result is never null. A Date converts to its epoch milliseconds, a boolean to one or zero, and an unsupported type raises a runtime exception.

ParameterDescription
othe value to convert, may be null

toLongSafe(Object o)

Returns: Long

Converts almost anything to a Long without throwing, returning null when the value is empty or cannot be converted.

ParameterDescription
othe value to convert, may be null

toLong(Object oVal, boolean withNulls)

Returns: Long

Converts almost anything to a Long, choosing whether empty values come back as null or as zero. Handles Long, Integer, Number, BigDecimal, Double and Float including NaN and infinity, Date as epoch milliseconds, Boolean as one or zero, the search types KSingleValue, KBucket and KSearchHitField, a POI RichTextString, the first element of an object array, and strings including 'true', 'false', 'null' and decimal forms.

ParameterDescription
oValthe value to convert, may be null
withNullstrue to return null for empty or unconvertible input, false to return zero or throw

toPath(String s)

Returns: Path

Parses a slash separated path string such as /a/b/c into a Milton Path object, returning the root path for a null input.

ParameterDescription
sthe path string to parse, may be null

getFileName(String s)

Returns: String

Returns the last segment of a slash separated path, which for a file path is the file name including its extension.

ParameterDescription
sthe path string, may be null

getYear(Object o)

Returns: int

Returns the four digit year of the given Date, read in the server's default timezone. Returns zero for null or for a value that is not a java.util.Date.

ParameterDescription
othe date to read, may be null

getMonth(Object o)

Returns: int

Returns the one indexed month of the given value, so January is 1 and December is 12. A string is matched on its first three letters ignoring case, so 'jan', 'January' and 'JANUARY' all give 1. Returns -1 for null and zero for a value that is neither a recognised month name nor a Date.

ParameterDescription
oa Date or a month name, may be null

getDayOfMonth(Object o)

Returns: int

Returns the one indexed day of the month of the given Date, read in the server's default timezone. Returns zero for null or for a value that is not a java.util.Date.

ParameterDescription
othe date to read, may be null

getHour(Object o)

Returns: int

Returns the hour of the day on a 24 hour clock for the given Date, read in the server's default timezone. Returns zero for null or for a value that is not a java.util.Date.

ParameterDescription
othe date to read, may be null

getHour(Object o, String timezone)

Returns: int

Returns the hour of the day on a 24 hour clock for the given Date, read in the named timezone. Returns zero for null or for a value that is not a java.util.Date.

ParameterDescription
othe date to read, may be null
timezonethe Joda timezone id such as Pacific/Auckland, null to use the date's own zone

getMinute(Object o)

Returns: int

Returns the minute within the hour of the given Date, read in the server's default timezone. Returns zero for null or for a value that is not a java.util.Date.

ParameterDescription
othe date to read, may be null

getDayOfWeek(Object o)

Returns: int

Returns the day of the week of the given date like value using the java.util.Calendar numbering, where Sunday is 1 and Saturday is 7. The value is first coerced with toDate.

ParameterDescription
othe date like value to read

getDayOfWeekName(Object o)

Returns: String

Returns the English name of the day of the week, such as Monday. Accepts either a date like value, which is resolved with getDayOfWeek, or an Integer already using the Calendar numbering where Sunday is 1 and Saturday is 7.

ParameterDescription
oa date like value, or an Integer day of week from 1 for Sunday to 7 for Saturday

formatDate(Object o)

Returns: String

Formats the date part only of a date like value, using the short date style of the current organisation's locale and falling back to dd/MM/yyyy when the organisation has no locale set. The time part is discarded.

ParameterDescription
othe date like value to format, may be null

formatDateWithLocale(Object o, String localeId)

Returns: String

Formats the date part only of a date like value using the short date style of the given locale, falling back to dd/MM/yyyy when no locale is supplied.

ParameterDescription
othe date like value to format, may be null
localeIdan IETF language tag such as en-NZ, blank to use the dd/MM/yyyy fallback

formatDate(Object o, String timezone)

Returns: String

Formats the date part only of a date like value as dd/MM/yyyy, after shifting it into the named timezone.

ParameterDescription
othe date like value to format, may be null
timezonethe Joda timezone id such as Pacific/Auckland, null to leave the date in its own zone

formatTime(Object o)

Returns: String

Formats the time part only of a date like value in the short style of the current tenant organisation's timezone.

ParameterDescription
othe date like value to format, may be null

formatTime(Object o, String timezone)

Returns: String

Formats the time part only of a date like value in the short style, after shifting it into the named timezone.

ParameterDescription
othe date like value to format, may be null
timezonethe Joda timezone id such as Pacific/Auckland

formatTimeLong(Object o, String timezone)

Returns: String

Formats the time part only of a date like value in the long style, which includes seconds and the timezone name, after shifting it into the named timezone.

ParameterDescription
othe date like value to format, may be null
timezonethe Joda timezone id such as Pacific/Auckland

formatDateLong(Object o)

Returns: String

Formats a date like value as a long date and time, such as 4 March 2026 10:15:30 NZDT, in the server's default timezone.

ParameterDescription
othe date like value to format, may be null

formatDateLong(Object o, String timezone)

Returns: String

Formats a date like value as a long date and time, after shifting it into the named timezone. Falls back to the server's default timezone when no timezone is given.

ParameterDescription
othe date like value to format, may be null
timezonethe Joda timezone id such as Pacific/Auckland, null to use the server default

formatDateTime(Object o)

Returns: String

Formats a date like value compactly as both date and time, in the current organisation's timezone and short locale style, falling back to dd/MM/yyyy HH:mm when the organisation has no locale set.

ParameterDescription
othe date like value to format, may be null

formatDateWithPattern(Object o, String pattern)

Returns: String

Formats a date like value with an arbitrary Joda date pattern, in the current organisation's timezone. An empty pattern falls back to dd/MM/yyyy.

ParameterDescription
othe date like value to format, may be null
patterna Joda DateTimeFormat pattern such as EEE d MMM yyyy, empty for dd/MM/yyyy

getFirstOfMonth(Object month)

Returns: Date

Returns midnight on the first day of the given month within the current year, in the server's default timezone.

ParameterDescription
monththe zero indexed month, where January is 0 and December is 11

getFirstOfMonth(Object month, String timeZone)

Returns: Date

Returns midnight on the first day of the given month within the current year, calculated in the named timezone. Note that the month is zero indexed, so January is 0 and December is 11, and that the milliseconds field is not cleared.

ParameterDescription
monththe zero indexed month, where January is 0 and December is 11
timeZonethe timezone id to calculate in, null to use the server default

newDate(Object year, Object month, Object day)

Returns: Date

Builds a Date at midnight on the given year, month and day, calculated in the current root folder organisation's timezone where one is set. Note that the month is zero indexed, so January is 0 and December is 11.

ParameterDescription
yearthe four digit year, coerced with toInteger
monththe zero indexed month, where January is 0 and December is 11
daythe day of the month, coerced with toInteger

calcNextBirthday(Object date)

Returns: Date

Works out the next occurrence of a birthday. Accepts a Profile, a ProfileBean or any date like value, takes the day and month from it and returns that anniversary in the current year, or in the following year if this year's has already passed.

ParameterDescription
datea Profile, a ProfileBean or any date like value holding the birth date

formatDateTime(Object o, String timezone)

Returns: String

Formats a date like value as dd/MM/yyyy HH:mm after shifting it into the named timezone. Falls back to the organisation aware single argument formatDateTime when no timezone is given.

ParameterDescription
othe date like value to format, may be null
timezonethe Joda timezone id such as Pacific/Auckland, null to use the organisation's timezone and locale

formatDateISO8601(Object o)

Returns: String

Formats a date like value as an ISO 8601 timestamp in the server's timezone. Useful for feeding client side relative time widgets such as timeago.

ParameterDescription
othe date like value to format, may be null

formatDateISO8601(Object o, String timezone)

Returns: String

Formats a date like value as an ISO 8601 timestamp after shifting it into the named timezone. Useful for feeding client side relative time widgets such as timeago.

ParameterDescription
othe date like value to format, may be null
timezonethe Joda timezone id such as Pacific/Auckland, blank to use the server timezone

formatAge(Object o)

Returns: String

Renders how long ago a date like value was in words, for example '4 minutes ago' or 'yesterday', without applying translation.

ParameterDescription
othe date like value to describe, may be null

formatAge(Object o, boolean withTrans)

Returns: String

Renders how long ago a date like value was, or how far in the future it is, in words such as 'Just now', '4 minutes ago', 'a day ago' or 'in 3 weeks'. With withTrans set, each phrase is wrapped in a translation lookup span so the client side translator can replace it.

ParameterDescription
othe date like value to describe, may be null
withTranstrue to wrap each phrase in a translation lookup span, false for plain text

formatMinsAsDuration(Object o)

Returns: String

Renders a number of minutes as a numeric duration in hours and minutes, such as 1:30 for ninety minutes.

ParameterDescription
oa value convertible to a number of minutes, may be null

formatMinsAsDuration(Object o, boolean numeric)

Returns: String

Renders a number of minutes as a duration, either numerically as 1:30 or in words as 45mins, 1hr 30 or 3hrs 20.

ParameterDescription
oa value convertible to a number of minutes, may be null
numerictrue for the hours:minutes form, false for the abbreviated words form

pad2(long l)

Returns: String

Renders a number as at least two characters, padding with a leading zero, so 7 becomes 07. Numbers of two or more digits are left unchanged.

ParameterDescription
lthe number to pad

pad(long l, int length)

Returns: String

Renders a number padded with leading zeros to the given width, so pad(2, 3) gives 002. Numbers already at or over the width are left unchanged.

ParameterDescription
lthe number to pad
lengththe minimum number of characters in the result, maximum 20

padWith(String padChar, Object rawVal, int length)

Returns: String

Renders any value as a string with the given character repeated on the left until it reaches the requested width. The value is first rendered with format. Widths above 20 raise a runtime exception.

ParameterDescription
padCharthe character to pad with, such as 0 or a space
rawValthe value to render and pad, may be null
lengththe minimum number of characters in the result, maximum 20

getDateTime(Object o)

Returns: DateTime

Coerces a value into a Joda DateTime without adjusting the timezone. Accepts an existing DateTime, a Milton Resource whose modified date is used, a date string parsed with parseDate, and anything else the Joda DateTime constructor accepts such as a Date or an epoch millisecond value. Null, an empty string and similar empty values return null.

ParameterDescription
othe value to coerce, may be null

getDateTime(Object o, String timezoneId)

Returns: DateTime

Coerces a value into a Joda DateTime in the named timezone, giving a mutable friendly date object for further arithmetic. Accepts a DateTime, a Date, an epoch millisecond Long, or a dd/MM/yyyy string. The timezone id is first normalised by standardiseTimezoneId.

ParameterDescription
othe value to coerce, may be null
timezoneIdthe timezone id to interpret and present the value in, blank to use the server default

toPercent(Object num, Object div)

Returns: String

Divides one number by another and renders the result as a whole number percentage with a trailing percent symbol. A blank or zero divisor, or a blank numerator, gives an empty string.

ParameterDescription
numthe numerator
divthe divisor

toPercent(Object num, Object div, int decimalPlaces)

Returns: String

Divides one number by another and renders the result as a percentage with a trailing percent symbol, to two decimal places. Note that the decimalPlaces argument is currently ignored and two places are always used.

ParameterDescription
numthe numerator
divthe divisor
decimalPlacesthe requested number of decimal places, currently ignored

toPercent(Object num, Object div, boolean appendSymbol, boolean withBlanks)

Returns: String

Divides one number by another and renders the result as a whole number percentage, with control over the percent symbol and over how blank inputs are handled.

ParameterDescription
numthe numerator
divthe divisor
appendSymboltrue to append a percent symbol to a non-blank result
withBlankstrue to return an empty string when the numerator or divisor is blank, false to return zero instead

toPercent(Object num, Object div, boolean appendSymbol, boolean withBlanks, int decimalPlaces)

Returns: String

Divides one number by another and renders the result as a percentage, with control over the percent symbol, blank handling and precision. With decimalPlaces of zero the calculation is done in whole numbers, otherwise it is done in floating point and rounded to two decimal places.

ParameterDescription
numthe numerator
divthe divisor
appendSymboltrue to append a percent symbol to a non-blank result
withBlankstrue to return an empty string when the numerator or divisor is blank or zero, false to return zero instead
decimalPlaceszero for a whole number result, any other value for a result rounded to two decimal places

format(Object o)

Returns: String

Renders any value as a display string, choosing a sensible representation for its type. Strings are trimmed, a BigDecimal is rendered in plain notation, a Date uses formatDate, byte and char arrays are decoded, a BaseEntity uses its formatted name, a list or JSON array becomes a comma separated list, and anything else is parsed as a number where possible or falls back to its own toString.

ParameterDescription
othe value to render, may be null

stripExt(String s)

Returns: String

Removes the file extension from a file name if there is one, so file1.swf becomes file1 and file1 is returned unchanged.

ParameterDescription
sthe file name, may be null

fileExt(String fileName)

Returns: String

Returns the file extension of a file name, without the dot, or an empty string when there is none.

ParameterDescription
fileNamethe file name, may be null

gt(Object val1, Object val2)

Returns: boolean

Numeric greater than comparison that coerces both operands with toDouble, so numeric strings compare correctly. A null first operand is never greater, and a non-null first operand is always greater than a null second operand.

ParameterDescription
val1the left hand value, may be null
val2the right hand value, may be null

gte(Object val1, Object val2)

Returns: boolean

Numeric greater than or equal comparison that coerces both operands with toDouble, so numeric strings compare correctly.

ParameterDescription
val1the left hand value, may be null
val2the right hand value, may be null

lte(Object val1, Object val2)

Returns: boolean

Numeric less than or equal comparison that coerces both operands with toDouble, so numeric strings compare correctly.

ParameterDescription
val1the left hand value, may be null
val2the right hand value, may be null

lt(Object val1, Object val2)

Returns: boolean

Numeric less than comparison that coerces both operands with toDouble, so numeric strings compare correctly. A null first operand is never less, and a non-null first operand is always less than a null second operand.

ParameterDescription
val1the left hand value, may be null
val2the right hand value, may be null

eq(Object val1, Object val2)

Returns: boolean

Numeric equality comparison that coerces both operands with toDouble, so 1, '1' and 1.0 all compare equal. Two nulls are equal, and a null is never equal to a non-null.

ParameterDescription
val1the left hand value, may be null
val2the right hand value, may be null

not(Object o)

Returns: Boolean

Negates any truthy value, coercing it to a Boolean first. Returns null when the value cannot be interpreted as true or false.

ParameterDescription
othe value to negate, may be null

htmlEncode(Object ob)

Returns: String

Escapes a value so it is safe to render inside HTML text, converting characters such as angle brackets and ampersands into entities. Only character sequences are escaped; any other type is returned via its own toString unchanged.

ParameterDescription
obthe value to encode, may be null. Only CharSequence values are escaped

htmlAttEncode(String s2)

Returns: String

Escapes a value so it is safe to place inside a quoted HTML attribute, converting ampersands, angle brackets and both quote characters into entities. The conversion is lossy, so several different inputs can encode to the same attribute value.

ParameterDescription
s2the value to encode, may be null

htmlAttDecode(String s2)

Returns: String

Reverses htmlAttEncode, turning the ampersand, angle bracket and double quote entities back into their literal characters. Note that the single quote entity written by htmlAttEncode is not decoded.

ParameterDescription
s2the encoded attribute value, may be null

percentDecode(String s)

Returns: String

Decodes a percent encoded URL path, so a%20b becomes 'a b'.

ParameterDescription
sthe percent encoded path, may be null

percentDecodeSafe(String s)

Returns: String

Decodes a percent encoded URL path in the same way as percentDecode, but returns null instead of throwing when the input is malformed.

ParameterDescription
sthe percent encoded path, may be null

percentEncode(String s)

Returns: String

Percent encodes a string so it is safe to use as a URL path segment, so 'a b' becomes a%20b.

ParameterDescription
sthe text to encode, may be null

between(Object oVal, Object oStart, Object oFinish)

Returns: boolean

Tests whether a date like value falls within a date range, where either bound may be omitted. A null start means 'no lower bound' and a null finish means 'no upper bound', so passing only a finish checks that the value is not after it. All three values are coerced with getDateTime, and a value that cannot be read as a date returns false.

ParameterDescription
oValthe date like value to test
oStartthe inclusive start of the range, null for no lower bound
oFinishthe inclusive end of the range, null for no upper bound

toDate(Object oVal)

Returns: Date

Coerces a value into a java.util.Date. Accepts an existing Date, a Joda DateTime, a ZonedDateTime, a Long or Integer of epoch milliseconds, and a date string which is parsed with parseDate. Any other type returns null.

ParameterDescription
oValthe value to coerce, may be null

toSqlDate(Object oVal)

Returns: Date

Coerces a value into a java.sql.Date, for passing as a parameter to a native SQL query.

ParameterDescription
oValthe value to coerce, may be null

toSqlTimestamp(Object oVal)

Returns: Timestamp

Coerces a value into a java.sql.Timestamp, keeping the time of day, for passing as a parameter to a native SQL query.

ParameterDescription
oValthe value to coerce, may be null

toJodaDate(Object oVal)

Returns: DateTime

Coerces a value into a Joda DateTime in the server's default timezone, by way of toDate.

ParameterDescription
oValthe value to coerce, may be null

parseDateWithPattern(String dateS, String pattern)

Returns: Date

Parses a date string against an explicit Joda pattern, interpreting it in the current organisation's timezone.

ParameterDescription
dateSthe date text to parse, may be blank
patterna Joda DateTimeFormat pattern such as dd/MM/yyyy HH:mm, blank to fall back to parseDate

parseDateWithPattern(String dateS, String pattern, String timezone)

Returns: Date

Parses a date string against an explicit Joda pattern, interpreting it in the named timezone. The text is first tidied with cleanString. A blank pattern falls back to the general purpose parseDate, and a parse failure raises a runtime exception.

ParameterDescription
dateSthe date text to parse, may be blank
patterna Joda DateTimeFormat pattern such as dd/MM/yyyy HH:mm, blank to fall back to parseDate
timezonethe timezone id to interpret the text in, blank for the server default

toHtmlInputValue(String value)

Returns: String

Escapes a value so it can be placed in the value attribute of an HTML input for editing, by converting double quotes to an entity.

ParameterDescription
valuethe value to escape, may be null

toPlain(String html)

Returns: String

Strips HTML markup to leave plain text, turning block and line break tags into newlines. The conversion is deliberately crude: it replaces a fixed set of tags rather than parsing the document.

ParameterDescription
htmlthe HTML to flatten, may be null

toPlain(String html, boolean includeNewLines)

Returns: String

Strips HTML markup to leave plain text, with control over whether block and line break tags become newlines or are simply removed. Handles br, hr, p, div, b, strong, i, h1, h2 and h3, and replaces the non-breaking space and ampersand entities.

ParameterDescription
htmlthe HTML to flatten, may be null
includeNewLinestrue to turn block and line break tags into newlines, false to drop all line breaks

generateTextFromHtml(String html)

Returns: String

Extracts the readable text from an HTML document by removing its tags, then trims the result. Unlike toPlain this parses the markup rather than replacing a fixed set of tags.

ParameterDescription
htmlthe HTML to extract text from, may be null

getNow()

Returns: Date

Current date and time as seen by the server, taken from the platform's current date service rather than the system clock so that tests can control it.

getYearStart()

Returns: Date

Midnight on the first day of January of the current year, in the server's default timezone.

yearStart(Date dt)

Returns: Date

Midnight on 1 January of the year that the given date falls in, calculated in the current organisation's timezone.

ParameterDescription
dtthe date whose year is wanted, may be null

monthStart(Date dt, int month)

Returns: Date

The first instant of the given month within the year that the given date falls in, calculated in the current organisation's timezone where one is set. The month is zero indexed, so 0 is January and 11 is December.

ParameterDescription
dtthe date whose year is used, may be null
monththe zero indexed month, where January is 0 and December is 11

monthStart(Date dt)

Returns: Date

The first instant of the month that the given date falls in, calculated in the current organisation's timezone where one is set.

ParameterDescription
dtthe date whose month is wanted

yearEnd()

Returns: Date

The last instant of the current year, that is 31 December at 23:59:59.999, in the current organisation's timezone.

yearEnd(Date dt)

Returns: Date

The last instant of the year that the given date falls in, that is 31 December at 23:59:59.999, in the current organisation's timezone.

ParameterDescription
dtthe date whose year is wanted

monthEnd(Date dt, int month)

Returns: Date

The last instant of the given month within the year that the given date falls in, that is the final day at 23:59:59.999, calculated in the current organisation's timezone where one is set. The month is zero indexed, so 0 is January and 11 is December.

ParameterDescription
dtthe date whose year is used
monththe zero indexed month, where January is 0 and December is 11

monthEnd(Date dt)

Returns: Date

The last instant of the month that the given date falls in, that is the final day at 23:59:59.999, in the current organisation's timezone where one is set.

ParameterDescription
dtthe date whose month is wanted, may be null

durationSecs(Object start, Object finish)

Returns: long

Number of whole seconds between two date like values. A finish that is before the start gives a negative result.

ParameterDescription
startany value convertible to a date with toJodaDate
finishany value convertible to a date with toJodaDate

durationHours(Object start, Object finish)

Returns: long

Number of whole hours between two date like values, truncated rather than rounded.

ParameterDescription
startany value convertible to a date with toJodaDate
finishany value convertible to a date with toJodaDate

durationMins(Object start, Object finish)

Returns: long

Number of whole minutes between two date like values, truncated rather than rounded.

ParameterDescription
startany value convertible to a date with toJodaDate, may be null
finishany value convertible to a date with toJodaDate, may be null

durationDays(Object start, Object finish)

Returns: long

Number of whole 24 hour days between two date like values, truncated rather than rounded. This is elapsed time, not a count of calendar day boundaries crossed.

ParameterDescription
startany value convertible to a date with toDate, may be null
finishany value convertible to a date with toDate, may be null

durationYears(Object start, Object finish)

Returns: long

Number of whole years between two date like values, calculated as elapsed days divided by 365 and so ignoring leap years.

ParameterDescription
startany value convertible to a date with toDate, may be null
finishany value convertible to a date with toDate, may be null

getMonthName(Object o)

Returns: String

Returns the English month name, such as January, for a date like value or a month name fragment, resolved with getMonth.

ParameterDescription
oa Date or a month name, may be null

getMonthName(int i)

Returns: String

Returns the full English month name for a zero indexed month number, where 0 is January and 11 is December.

ParameterDescription
ithe zero indexed month number

getCurrentDateService()

Returns: CurrentDateService

The platform's current date service, the single source of 'now' for the server, which tests can override to freeze or shift time.

ifEqual(String ifEqual, String ifNotEqual, Object o1, Object o2)

Returns: String

Null safe conditional that returns one of two strings depending on whether the two values are equal. Values of the same class are compared with equals, otherwise their string forms are compared, and two nulls count as equal.

ParameterDescription
ifEqualthe text to return when the values are equal
ifNotEqualthe text to return when the values differ
o1the first value to compare, may be null
o2the second value to compare, may be null

isEqual(Object o1, Object o2)

Returns: boolean

Null safe equality test using the Java equals method, useful from JavaScript where the double equals operator does not compare host objects reliably. Two nulls count as equal.

ParameterDescription
o1the first value to compare, may be null
o2the second value to compare, may be null

isNotEqual(Object o1, Object o2)

Returns: boolean

Null safe inequality test, the negation of isEqual.

ParameterDescription
o1the first value to compare, may be null
o2the second value to compare, may be null

ifNull(Object val, Object defaultVal)

Returns: Object

Returns the given value, or a fallback when the value is null or an all whitespace string. Other empty values such as an empty collection are returned as they are; use ifEmpty if those should also fall back.

ParameterDescription
valthe preferred value, returned when it is not null and not a blank string
defaultValthe fallback value

ifEmpty(Object val, Object defaultVal)

Returns: Object

Returns the given value, or a fallback when the value is empty by the rules of isEmpty, which covers null, undefined, a blank string and an empty collection or map.

ParameterDescription
valthe preferred value, returned when it is not empty
defaultValthe fallback value

ifTrue(Object bb, Object o1, Object o2)

Returns: Object

Ternary conditional for template syntax that has none: returns the second argument when the first is truthy and the third when it is not. The condition is coerced with toBool, and a null or unparseable condition counts as false.

ParameterDescription
bbthe condition, coerced with toBool
o1the value to return when the condition is true
o2the value to return when the condition is false

ifFalse(Object bb, Object o1, Object o2)

Returns: Object

Inverted ternary conditional: returns the second argument when the condition is falsy and the third when it is truthy. The condition is coerced with toBool, and a null or unparseable condition counts as false.

ParameterDescription
bbthe condition, coerced with toBool
o1the value to return when the condition is false
o2the value to return when the condition is true

newList()

Returns: ResourceList

Creates a new empty ResourceList, the mutable list type used throughout templates, which adds sorting, filtering and aggregation helpers on top of a plain list.

getList()

Returns: ResourceList

Creates a new empty ResourceList. Identical to newList, and provided so templates can use property syntax.

parseDate(String s)

Returns: Date

Parses a date from a string, trying several formats in turn: a string of epoch milliseconds, an ISO style timestamp containing a T, dd/MM/yyyy HH:mm when the text contains a colon, yyyy-MM-dd when it contains a hyphen, and otherwise dd/MM/yyyy. Text containing a time is interpreted in the current organisation's timezone.

ParameterDescription
sthe date text to parse, may be blank

parseTime(Object o)

Returns: Date

Parses a time of day in the 12 hour hh:mm am or pm form, returning it as a Date on the epoch day.

ParameterDescription
othe time text to parse, rendered with toString first

sdf(boolean hasTime)

Returns: DateFormat

Returns the shared thread local SimpleDateFormat for the platform's standard date patterns, either dd/MM/yyyy HH:mm or dd/MM/yyyy. The returned formatter belongs to the calling thread, so do not hold on to it or share it between threads.

ParameterDescription
hasTimetrue for the date and time pattern, false for the date only pattern

toFloat(Object val)

Returns: Float

Converts almost any numeric value to a Float, returning null rather than zero when the value is empty or cannot be converted.

ParameterDescription
valthe value to convert, may be null

toBigDecimalSafe(Object val)

Returns: BigDecimal

Converts a value to a BigDecimal in the same way as toBigDecimal, but returns null instead of throwing when the value cannot be converted.

ParameterDescription
valthe value to convert, may be null

toBigDecimal(Object val)

Returns: BigDecimal

Converts a value to a BigDecimal without changing its scale. A non-numeric string raises a runtime exception, and null or a blank string returns null.

ParameterDescription
valthe value to convert, may be null

toBigDecimal(Object o, Integer decimals)

Returns: BigDecimal

Converts a value to a BigDecimal, optionally rounding it half up to a fixed number of decimal places. Accepts BigDecimal, Integer, Long, Float, Double and a string in the grouped '#,##0.0#' form. A non-numeric string raises a runtime exception, and null, a blank string or an unhandled type returns null.

ParameterDescription
othe value to convert, may be null
decimalsthe number of decimal places to round to, null to keep the value's own scale

calc(ResourceList list)

Returns: Calc

Creates a Calc over the given list, the calculator object that provides filtering, grouping, summing and other aggregation over a ResourceList.

ParameterDescription
listthe list to calculate over

where(String mvelExpr, ResourceList list)

Returns: ResourceList

Filters a list with an MVEL boolean expression, keeping only the items for which the expression is true. The expression is evaluated once per item, so this is proportional to the size of the list.

ParameterDescription
mvelExprthe MVEL boolean expression to test each item with
listthe list to filter

checked(Object o)

Returns: String

Returns the HTML attribute word 'checked' when the given value is truthy, and an empty string otherwise, for use inside an input tag.

ParameterDescription
othe value to test, coerced with toBool

selected(Object o)

Returns: String

Returns the HTML attribute word 'selected' when the given value is truthy, and an empty string otherwise, for use inside an option tag.

ParameterDescription
othe value to test, coerced with toBool

checkbox(String name, Object oChecked)

Returns: String

Renders a checkbox input with the value 'true', together with the hidden companion field that lets the server tell an unticked box apart from a missing one. The companion field is named after the checkbox with a _checkbox suffix.

ParameterDescription
namethe form field name
oCheckedtruthy if the box should start ticked, coerced with toBool

checkbox(String id, String name, Object oChecked)

Returns: String

Renders a checkbox input with the value 'true' and the given HTML id, together with the hidden companion field named after the checkbox with a _checkbox suffix.

ParameterDescription
idthe HTML id to put on the checkbox
namethe form field name
oCheckedtruthy if the box should start ticked, coerced with toBool

checkbox(Object oId, String name, Object oChecked, Object oValue)

Returns: String

Renders a checkbox input with an explicit submitted value and HTML id, together with the hidden companion field. The hidden field is named after the checkbox with a _checkbox suffix and submits 'false', so the server sees a value whether or not the box is ticked.

ParameterDescription
oIdthe HTML id to put on the checkbox, may be null
namethe form field name
oCheckedtruthy if the box should start ticked, coerced with toBool
oValuethe value submitted when the box is ticked, may be null

call(Object o)

Returns: String

Swallows the result of an expression so it produces no output, for Velocity templates where you want the side effect of a call such as adding to a list without printing its return value.

ParameterDescription
othe already evaluated expression whose result is discarded

bsswitch(Object oId, String name, Object oChecked, Object oValue)

Returns: String

Renders a checkbox styled as a Bootstrap on and off switch, with the green and red colour attributes the switch plugin looks for, together with the hidden companion field named after the checkbox with a _checkbox suffix.

ParameterDescription
oIdthe HTML id to put on the checkbox, may be null
namethe form field name
oCheckedtruthy if the switch should start on, coerced with toBool
oValuethe value submitted when the switch is on, may be null

radioEq(String id, String name, String currentValue, String value)

Returns: String

Renders a radio button that is ticked when the property's current value equals the value this button represents, saving the caller from doing the comparison.

ParameterDescription
idthe HTML id to assign to the input
namethe form field name of the property being set
currentValuethe property's current value, may be null
valuethe value this radio button represents

radioEq(String id, String name, String currentValue, String value, String className)

Returns: String

Renders a radio button with a CSS class, ticked when the property's current value equals the value this button represents.

ParameterDescription
idthe HTML id to assign to the input
namethe form field name of the property being set
currentValuethe property's current value, may be null
valuethe value this radio button represents
classNamethe value for the class attribute, may be null

radio(String id, String name, Object oChecked, String value)

Returns: String

Renders a radio button, taking the ticked state directly as a truthy value rather than comparing values.

ParameterDescription
idthe HTML id to assign to the input, may be null
namethe form field name
oCheckedtruthy if this radio button should be ticked, coerced with toBool
valuethe value submitted when this radio button is chosen

radio(String id, String name, Object oChecked, String value, String className)

Returns: String

Renders a radio button with a CSS class, taking the ticked state directly as a truthy value rather than comparing values.

ParameterDescription
idthe HTML id to assign to the input, may be null
namethe form field name
oCheckedtruthy if this radio button should be ticked, coerced with toBool
valuethe value submitted when this radio button is chosen
classNamethe value for the class attribute, may be null

option(Relational value, Object currentValue)

Returns: String

Renders a select option for a database entity, using its row id as the option value. A Website is labelled with its title and domain name; any other entity is labelled with its title property.

ParameterDescription
valuethe entity the option represents
currentValuethe currently selected value, used to decide whether this option is marked selected

option(Object value, Object oText, Object currentValue)

Returns: String

Renders a select option with an explicit value and label, marked selected when the value matches the current value. The label is wrapped with a translation lookup class so it can be translated on the client.

ParameterDescription
valuethe value the option submits, an empty string is returned if this is null
oTextthe label text, falling back to the value when blank
currentValuethe currently selected value, used to decide whether this option is marked selected

option(Object value, Object oText, Object currentValue, Object dataIdValue)

Returns: String

Renders a select option with an explicit value, label and data-id attribute, marked selected when the value matches the current value. The label is wrapped with a translation lookup class so it can be translated on the client.

ParameterDescription
valuethe value the option submits, an empty string is returned if this is null
oTextthe label text, falling back to the value when blank
currentValuethe currently selected value, used to decide whether this option is marked selected
dataIdValuethe value for a data-id attribute on the option, omitted when null or blank

select(String name, Map<Object,Object> data)

Returns: String

Renders a select element whose options come from a map, with the map keys as option values and the map values as labels. No option is preselected.

ParameterDescription
namethe form field name
datathe option values mapped to their labels, may be null for an empty select

select(String name, Object currentVal, Map<Object,Object> data)

Returns: String

Renders a select element whose options come from a map, marking the option that matches the current value as selected.

ParameterDescription
namethe form field name
currentValthe currently selected value, may be null
datathe option values mapped to their labels, may be null for an empty select

select(String id, String name, String htmlClass, Object currentVal, Map<Object,Object> data)

Returns: String

Renders a select element with an HTML id and CSS class, whose options come from a map, marking the option that matches the current value as selected.

ParameterDescription
idthe HTML id to put on the select, omitted when null
namethe form field name, omitted when null
htmlClassthe value for the class attribute, omitted when null
currentValthe currently selected value, may be null
datathe option values mapped to their labels, may be null for an empty select

getPort()

Returns: int

Port that the current HTTP request arrived on, taken from the Host header, defaulting to 80 when there is no request or no header.

isSecure()

Returns: boolean

True when the current request should be treated as HTTPS, either because it arrived on port 443 or 8443, because the request itself reports HTTPS, or because the current tenant organisation has force HTTPS switched on.

getPortString()

Returns: String

Port suffix to append when building an absolute URL, such as :8080. Empty for the default ports 80 and 443 so that ordinary URLs do not carry a redundant port.

profilePicHref(Profile p)

Returns: String

Returns the URL of a profile's photo, falling back to the default avatar image when the profile has no photo. Superseded by the profile templating helpers.

ParameterDescription
pthe profile whose photo is wanted, may be null

toCsvArgs(String s)

Returns: String

Joins the given strings into a single comma separated line, for callers that have loose arguments rather than a list.

ParameterDescription
sthe values to join

toCsv(Iterable list)

Returns: String

Joins the items of any iterable into a single comma separated line, skipping nulls. Values are not quoted or escaped, so this is not safe for values that contain commas.

ParameterDescription
listthe items to join, may be null

toLineOfVals(Iterable list, String seperator)

Returns: String

Joins the items of any iterable into a single line with the given separator between them, skipping nulls. Values are not quoted or escaped.

ParameterDescription
listthe items to join, may be null
seperatorthe text to place between items

toProperties(Map<Object,Object> map)

Returns: String

Renders a map as a properties style block, one key equals value pair per line. Keys and values are rendered with format, and neither is escaped.

ParameterDescription
mapthe entries to render, may be null or empty

toCsv(String[] list)

Returns: String

Joins an array of strings into a single comma separated line, skipping nulls. Values are not quoted or escaped.

ParameterDescription
listthe values to join, may be null

toCsv(Object list)

Returns: String

Joins a value into a comma separated line when it is a list, and otherwise falls back to the value's own toString.

ParameterDescription
listthe list or single value to render, may be null

fromCsv(Object o)

Returns: List<String>

Splits a comma separated string into a list, trimming each item and dropping the blanks. The input is first tidied with cleanString.

ParameterDescription
othe comma separated text, may be null

toJson(Object val)

Returns: String

Serialises any value to compact JSON using the platform's JSON writer, which understands the platform entities and honours the IgnoreJsonProperty annotation.

ParameterDescription
valthe value to serialise, may be null

toJson(Object val, int indent)

Returns: String

Serialises any value to indented, human readable JSON using the platform's JSON writer.

ParameterDescription
valthe value to serialise, may be null
indentthe number of spaces to indent each nesting level by

parseJson(String jsonStr)

Returns: Object

Parses JSON text into a JSONObject or JSONArray that templates and scripts can read. Malformed JSON raises a runtime exception; use the two argument form to get null instead.

ParameterDescription
jsonStrthe JSON text to parse, may be blank

parseJson(String jsonStr, boolean throwException)

Returns: Object

Parses JSON text into a JSONObject or JSONArray, with control over whether malformed input throws or simply yields null.

ParameterDescription
jsonStrthe JSON text to parse, may be blank
throwExceptiontrue to let a parse failure propagate, false to log it and return null

addDays(Date now, Integer days)

Returns: Date

Returns a new date the given number of days after the one supplied, or before it when the number is negative. The original date is not modified.

ParameterDescription
nowthe starting date, may be null
daysthe number of days to add, negative to subtract, null to leave the date unchanged

addMilliseconds(Date now, Integer milliseconds)

Returns: Date

Returns a new date the given number of milliseconds after the one supplied, or before it when the number is negative.

ParameterDescription
nowthe starting date, may be null
millisecondsthe number of milliseconds to add, negative to subtract, null to leave the date unchanged

addYears(Date now, Integer years)

Returns: Date

Returns a new date the given number of years after the one supplied, or before it when the number is negative. Calendar arithmetic is used, so 29 February shifts to 28 February in a non-leap year.

ParameterDescription
nowthe starting date, may be null
yearsthe number of years to add, negative to subtract, null to leave the date unchanged

addMonths(Date now, Integer months)

Returns: Date

Returns a new date the given number of months after the one supplied, or before it when the number is negative. Calendar arithmetic is used, so a day of month that does not exist in the target month is clamped to the last day of that month.

ParameterDescription
nowthe starting date, may be null
monthsthe number of months to add, negative to subtract, null to leave the date unchanged

addDays(Object now, Object days)

Returns: Date

Returns a new date the given number of days after the one supplied, coercing both arguments first so a date string and a numeric string can be passed straight from a template.

ParameterDescription
nowanything convertible to a date with toDate
daysanything convertible to a number with toInteger, negative to subtract

getDaysBetween(Object from, Object to)

Returns: List<Date>

Builds the list of days from one date up to but not including another, each at the start of its day. Both bounds are coerced with toDate. The list grows with the size of the range, so avoid it for very wide ranges.

ParameterDescription
fromthe first day of the range, inclusive
tothe day the range stops at, exclusive

addSeconds(Date now, int seconds)

Returns: Date

Returns a new date the given number of seconds after the one supplied, or before it when the number is negative.

ParameterDescription
nowthe starting date
secondsthe number of seconds to add, negative to subtract

addMinutes(Date now, int mins)

Returns: Date

Returns a new date the given number of minutes after the one supplied, or before it when the number is negative.

ParameterDescription
nowthe starting date
minsthe number of minutes to add, negative to subtract

addHours(Date now, int hours)

Returns: Date

Returns a new date the given number of hours after the one supplied, or before it when the number is negative.

ParameterDescription
nowthe starting date
hoursthe number of hours to add, negative to subtract

getBaseWebsiteUrl()

Returns: String

Scheme and domain of the website being served by the current request, such as https://www.example.com, with no trailing slash. Null when the request is not being served from a website root folder.

getBaseWebsiteUrl(Website w)

Returns: String

Builds the scheme and domain for the given website, such as https://www.example.com, with no trailing slash. The scheme follows the force HTTPS setting on the website's live branch.

ParameterDescription
wthe website to build the URL for, may be null

getCleanedRootDomain(String domainName)

Returns: String

Reduces a host name to its registrable root domain, so shop.example.co.nz becomes example.co.nz. Any trailing dot is removed first, and the public suffix list is used to decide where the root begins.

ParameterDescription
domainNamethe host name to reduce

getDomainName(Website w)

Returns: String

Primary domain name of the given website, including the port suffix when the server is not on a default port.

ParameterDescription
wthe website whose domain is wanted, may be null

getDomainName(Website w, boolean useVersion)

Returns: String

Domain name of the given website, including the port suffix, optionally resolved against the website's live branch so that a version specific host name is returned.

ParameterDescription
wthe website whose domain is wanted, may be null
useVersiontrue to resolve the domain against the website's live branch

getDomainName(Website w, boolean useVersion, boolean includePort)

Returns: String

Domain name of the given website, with control over branch resolution and whether the port suffix is appended.

ParameterDescription
wthe website whose domain is wanted, may be null
useVersiontrue to resolve the domain against the website's live branch
includePorttrue to append the port suffix when the server is not on a default port

getKademiDomainName(Website w, boolean useVersion, boolean includePort)

Returns: String

Kademi hosted domain name of the given website, that is the platform's own host name for it rather than any custom domain the customer has attached.

ParameterDescription
wthe website whose domain is wanted, may be null
useVersiontrue to resolve the domain against the website's live branch
includePorttrue to append the port suffix when the server is not on a default port

isNotNull(Object o)

Returns: boolean

True when the given value is present, that is anything isNull does not treat as missing. As well as a Java null this rejects a JavaScript undefined and a JSON null.

ParameterDescription
othe value to test, may be null

isNull(Object o)

Returns: boolean

True when the given value counts as missing, which covers a Java null, an empty string, a JSON null and the JavaScript undefined and null values that reach the server from a script engine.

ParameterDescription
othe value to test, may be null

getVersionId(WebsiteBranchResource rf)

Returns: String

Builds the cache busting version token to embed in theme asset URLs. It combines the running server version with the content hash of the website's theme directory, so a theme change invalidates browser caches without a server release.

ParameterDescription
rfthe website branch resource whose theme is hashed, may be any resource

daysBetween(Date from, Date to)

Returns: List<LocalDate>

Lists the days from one date up to but not including another as Joda LocalDate values. When the two dates fall on the same day the result still holds that one day. The list grows with the size of the range.

ParameterDescription
fromthe first day of the range, inclusive
tothe day the range stops at, exclusive

endofDay(Date dt)

Returns: Date

Returns the last instant of the day the given date falls in, that is 23:59:59.999, in the current organisation's timezone. Null safe.

ParameterDescription
dtthe date whose day end is wanted, may be null

endOfDay(Date dt)

Returns: Date

Returns the last instant of the day the given date falls in, that is 23:59:59.999, in the current organisation's timezone. An alias for endofDay. Null safe.

ParameterDescription
dtthe date whose day end is wanted, may be null

endofDay(Date dt, String timezone)

Returns: Date

Returns the last instant of the day the given date falls in, that is 23:59:59.999, calculated in the named timezone. Null safe.

ParameterDescription
dtthe date whose day end is wanted, may be null
timezonethe timezone id to calculate in, blank to use the server default

endOfDay(Date dt, String timezone)

Returns: Date

Returns the last instant of the day the given date falls in, that is 23:59:59.999, calculated in the named timezone. An alias for endofDay. Null safe.

ParameterDescription
dtthe date whose day end is wanted, may be null
timezonethe timezone id to calculate in, blank to use the server default

startOfDay(Date dt)

Returns: Date

Returns the first instant of the day the given date falls in, that is midnight, in the current organisation's timezone. Null safe.

ParameterDescription
dtthe date whose day start is wanted, may be null

startOfDay(Date dt, String timezone)

Returns: Date

Returns the first instant of the day the given date falls in, that is midnight, calculated in the named timezone. Null safe.

ParameterDescription
dtthe date whose day start is wanted, may be null
timezonethe timezone id to calculate in, blank to use the server default

truncate(String s, int max)

Returns: String

Shortens a string to at most the given number of characters, appending three full stops when anything was cut off. Strings already within the limit are returned unchanged.

ParameterDescription
sthe text to shorten, may be null
maxthe maximum length before the ellipsis is added

truncateToEnd(String s, int max)

Returns: String

Shortens a string to at most the given number of characters by trimming from the front, so the end of the text is what survives.

ParameterDescription
sthe text to shorten, may be null
maxthe maximum length of the result

newReadonlyList(List list)

Returns: List

Wraps a list so it cannot be modified, copying it into the platform's killable list type first so that its contents are released when the request ends. A null input gives an empty read only list.

ParameterDescription
listthe list to wrap, may be null

newStack()

Returns: Stack

Creates a new empty Stack, a small last in first out collection that only allows pushing and popping at the head.

newArrayList()

Returns: ArrayList

Creates a new empty list that a template or script can add any type of object to. The list is a killable list, so its contents are released when the request ends.

newCommonList()

Returns: CommonList

Creates a new empty CommonList, which behaves like an ArrayList but adds sorting, filtering and aggregation helpers. It is the base class of ResourceList.

newCommonList(Collection from)

Returns: CommonList

Creates a CommonList holding a copy of the given collection. A CommonList behaves like an ArrayList but adds sorting, filtering and aggregation helpers.

ParameterDescription
fromthe collection to copy the initial items from

newArrayList(Object[] arr)

Returns: ArrayList

Creates a new list holding the elements of the given array. The list is a killable list, so its contents are released when the request ends.

ParameterDescription
arrthe array whose elements are copied into the list

newMap()

Returns: LinkedHashMap

Creates a new empty map that a template or script can put entries into. Insertion order is preserved, and the contents are released when the request ends.

newSet()

Returns: LinkedHashSet

Creates a new empty set that a template or script can add to. Insertion order is preserved, and the contents are released when the request ends.

newMapBuilder()

Returns: MapBuilder

Creates a new MapBuilder, which builds a map with chained put calls so a whole map can be written as a single expression in a template.

formatBytes(Object o)

Returns: String

Renders a byte count in human readable units, such as 300 B, 5 kB or 3 MB, using powers of 1000. A Milton resource is rendered from its content length.

ParameterDescription
oa byte count or a resource whose content length is used, may be null

formatSecsAsDuration(Object o)

Returns: String

Renders a number of seconds as a rough duration, showing seconds under five minutes, minutes under three hours, and whole hours beyond that.

ParameterDescription
oa value convertible to a number of seconds, may be null

formatCurrency(Object o)

Returns: String

Formats an amount for display as money, using the current locale's grouping and decimal separators and two decimal places, without a currency symbol.

ParameterDescription
othe amount to format, may be null

formatCurrency(Object o, String unitSymbol, String unitPosition, Integer numberOfDecimal)

Returns: String

Formats an amount to a fixed number of decimal places and attaches a unit symbol on the chosen side, for currencies or for made up units such as points.

ParameterDescription
othe amount to format, may be null
unitSymbolthe symbol to attach, such as a dollar sign or pts, blank for none
unitPosition'before' to place the symbol in front of the amount, anything else to place it after
numberOfDecimalthe number of decimal places, null for two

formatCurrency(Object o, Boolean leadingZeros)

Returns: String

Formats an amount for display as money with grouped thousands and two decimal places, optionally dropping the decimal part altogether.

ParameterDescription
othe amount to format, may be null
leadingZerosfalse to cut the decimal point and everything after it, true or null to keep two decimal places

formatDecimal(Object o, Integer numberDecimals)

Returns: String

Formats a number with grouped thousands and exactly the given number of decimal places, padding with zeros where needed.

ParameterDescription
othe number to format, may be null
numberDecimalsthe number of decimal places, null or zero for a whole number

formatMaxDecimals(Object o, Integer numberDecimals)

Returns: String

Formats a number with at most the given number of decimal places, rounding half up and then stripping any trailing zeros, so a whole number prints without a decimal point.

ParameterDescription
othe number to format, may be null
numberDecimalsthe maximum number of decimal places, null to keep the value's own scale

getStartOfWeek(Date dt)

Returns: Date

Returns midnight on the Monday of the week that the given date falls in. Weeks are taken to start on Monday, so for a Sunday start call addDays with minus one on the result. Note that seconds and milliseconds are not cleared.

ParameterDescription
dtthe date whose week is wanted, may be null

capitalizeString(Object o)

Returns: String

Upper cases the first character of a value's string form and leaves the rest as it is, so 'hello world' becomes 'Hello world'.

ParameterDescription
othe value to capitalise, may be null

getCountryCodes()

Returns: CountryCodes

The platform's country code lookup table, which maps between two letter and three letter ISO codes, country names and dialling codes.

getCountryCodeOfOrg()

Returns: CountryCode

Country code record for the current root folder organisation's country, resolved from its two letter ISO code. Null when there is no current root folder or the organisation has no country set.

sortByProperty(List list, String propertyName)

Returns: List

Returns a copy of the list sorted by a bean property, reading the property by name from each item and comparing null safely. The original list is not modified. Any error is logged and the original list is returned unsorted.

ParameterDescription
listthe list to sort, may be null
propertyNamethe name of the bean property to sort on, may be null

sortReverse(List list)

Returns: List

Returns a copy of the list with the items in the opposite order. The original list is not modified.

ParameterDescription
listthe list to reverse, may be null

sort(List list)

Returns: List

Returns a copy of the list sorted by the items' own natural ordering. The original list is not modified, and every item must be comparable.

ParameterDescription
listthe list to sort, may be null

toggleParamVal(String paramName, String val)

Returns: String

Rebuilds the current request's query string with one value added to or removed from a named parameter, for building faceted filter links. Multi-valued parameters are held as comma separated lists, so toggling C out of tags=C,D on a request with categories=A,B gives categories=A,B and tags=D.

ParameterDescription
paramNamethe name of the parameter to toggle a value within
valthe value to add when it is absent and remove when it is present

toggleParamVal(String paramName, String val, boolean uniqueParam)

Returns: String

Rebuilds the current request's query string with one value toggled in a named parameter, or with the parameter replaced outright. Parameter names and values that fail the platform's parameter cleaning check are dropped from the result.

ParameterDescription
paramNamethe name of the parameter to toggle a value within
valthe value to add when it is absent and remove when it is present
uniqueParamtrue to make the parameter hold only this value, false to treat it as a comma separated list

paramSelected(String paramName, String value, String active)

Returns: String

Returns the given active text when a value is present in a comma separated request parameter, and an empty string otherwise. Pairs with toggleParamVal to mark the currently chosen facets, usually by emitting a CSS class.

ParameterDescription
paramNamethe request parameter to look in
valuethe value to look for
activethe text to return when the value is present

addQueryParam(String href, String paramName, Object paramVal)

Returns: String

Appends a name and value pair to a URL, choosing a question mark or an ampersand depending on whether the URL already has a query string. Neither the name nor the value is encoded, so percent encode them yourself if they may contain reserved characters.

ParameterDescription
hrefthe URL to append to, may be null
paramNamethe parameter name, already encoded if needed
paramValthe parameter value, already encoded if needed, null for an empty value

getQueryString()

Returns: String

Query string of the current request, rebuilt from its parameters and including the leading question mark. Empty when there is no request or the request has no parameters. Values are not re-encoded.

addNum(Object from, Object addAmount)

Returns: Integer

Adds two values as integers, coercing each with toInteger so numeric strings can be passed straight from a template.

ParameterDescription
fromthe base value
addAmountthe amount to add, negative to subtract

split(String s, String sep)

Returns: String[]

Splits a string on the given separator into an array, trimming each part and dropping the blanks. A null or the literal text 'undefined' gives an empty array.

ParameterDescription
sthe text to split, may be null
septhe separator, null for a comma

split(String s)

Returns: String[]

Splits a comma separated string into an array, trimming each part and dropping the blanks.

ParameterDescription
sthe text to split, may be null

splitByAnything(String s)

Returns: String[]

Splits a string on any run of semicolons, commas, spaces or newlines, which suits free text lists such as a pasted set of email addresses.

ParameterDescription
sthe text to split, may be null

toList(Object arr)

Returns: List

Converts almost any sequence into a Java List that templates and scripts can iterate. Handles Java arrays and collections, a Nashorn script array, a GraalJS array, iterator or callable that yields one, and returns an existing list unchanged. A value that is not a sequence raises a runtime exception. Iterating a script value yields to the Governor on each element so long conversions stay interruptible.

ParameterDescription
arrthe array, collection or script sequence to convert, may be null

formatNumeric(Object o, String format)

Returns: String

Formats a number with an arbitrary DecimalFormat pattern, such as #,###.00 for grouped thousands and two decimal places. Take care in Velocity templates, where the hash character starts a directive and must be escaped.

ParameterDescription
oa Double or anything convertible to one with toDouble, may be null
formata java.text.DecimalFormat pattern

formatNumeric(Object o)

Returns: String

Formats a number with grouped thousands and two decimal places, using the pattern #,###,###.00.

ParameterDescription
oa Double or anything convertible to one with toDouble, may be null

formatNumericNoDecimal(Object o)

Returns: String

Formats a number with grouped thousands and no decimal places, using the pattern #,###,###.

ParameterDescription
oa Double or anything convertible to one with toDouble, may be null

isNumeric(Object o)

Returns: boolean

True when the given value can be converted to a number by toLong, which is the platform's test for 'is this numeric'. Note that null and an empty string convert to zero and so count as numeric.

ParameterDescription
othe value to test, may be null

isType(Object source, String className)

Returns: boolean

True when the given object's Java class has the given simple name, for example isType(lead, 'Lead'). Hibernate proxies are unwrapped first so a lazily loaded entity is matched on its real class.

ParameterDescription
sourcethe object to test, may be null
classNamethe simple class name to match, without the package

getSimpleType(Object source)

Returns: String

Returns the simple Java class name of the given object, without its package, which is handy for logging or for branching on the type of a value from a script.

ParameterDescription
sourcethe object to inspect, may be null

toBase64String(Object o)

Returns: String

Encodes a byte array or a string as standard Base64. A string is encoded using the platform default charset.

ParameterDescription
othe byte array or string to encode

toBase64UrlString(Object o)

Returns: String

Encodes a byte array or a string as URL safe Base64, which uses minus and underscore in place of plus and slash and omits the padding, so the result can be dropped straight into a URL.

ParameterDescription
othe byte array or string to encode

fromBase64AsString(String base64)

Returns: String

Decodes standard Base64 text back to a string, using the platform default charset.

ParameterDescription
base64the Base64 text to decode, may be blank

fromBase64AsByteArray(String base64)

Returns: byte[]

Decodes standard Base64 text back to the raw bytes, for binary content that is not text.

ParameterDescription
base64the Base64 text to decode

toBigInteger(String val, int radix)

Returns: BigInteger

Parses the string form of an arbitrarily large integer written in the given number base into a BigInteger, for example base 16 for hexadecimal. A string that is not a valid number in that base raises a runtime exception.

ParameterDescription
valthe number text to parse
radixthe number base the text is written in, such as 10 or 16

joinByteArray(byte[] b1, byte[] b2)

Returns: byte[]

Concatenates two byte arrays into a new array, with the contents of the first followed by the contents of the second.

ParameterDescription
b1the leading bytes
b2the trailing bytes

copyFromArray(byte[] arr, int from, int to)

Returns: byte[]

Copies a slice out of a byte array into a new array. The start index is inclusive and the end index is exclusive, and an end index beyond the array is padded with zeros.

ParameterDescription
arrthe array to copy from
fromthe index to start at, inclusive
tothe index to stop at, exclusive

copyFromArray(char[] arr, int from, int to)

Returns: char[]

Copies a slice out of a char array into a new array. The start index is inclusive and the end index is exclusive, and an end index beyond the array is padded with null characters.

ParameterDescription
arrthe array to copy from
fromthe index to start at, inclusive
tothe index to stop at, exclusive

byteArrayToHexString(byte[] bytes)

Returns: String

Renders raw bytes as lower case hexadecimal, two characters per byte, which is the usual way to show a hash or signature.

ParameterDescription
bytesthe bytes to render

getCrypto()

Returns: CryptoImpl

The platform's cryptography helper, which provides hashing, HMAC signing and symmetric encryption to templates and scripts.

getGeoIPService()

Returns: GeoIPService

The platform's GeoIP service, which resolves an IP address to a country, region and city. Null when the server was built without one.

parseHtml(String html)

Returns: Jerry

Parses HTML into a Jerry document, a jQuery style API for walking and querying the markup with CSS selectors. Any parse error is logged and null is returned rather than thrown.

ParameterDescription
htmlthe HTML to parse, may be null

formatJodaDate(Object date, String pattern)

Returns: String

Coerces a value to a date and formats it with an arbitrary Joda pattern such as dd/MM/YYYY HH:mm:ss, in the date's own timezone.

ParameterDescription
datethe date like value to format, may be null
patterna Joda DateTimeFormat pattern

formatJodaDate(Object date, String pattern, String timeZone)

Returns: String

Coerces a value to a date, shifts it into the named timezone and formats it with an arbitrary Joda pattern such as dd/MM/YYYY HH:mm:ss.

ParameterDescription
datethe date like value to format, may be null
patterna Joda DateTimeFormat pattern
timeZonethe timezone id to present the date in, blank to leave it in its own zone

formatAsCleanId(String title)

Returns: String

Turns a title into a path and identifier safe token by replacing spaces and special characters with hyphens and stripping any leading hyphens. Use it to derive a stable name or anchor from human entered text.

ParameterDescription
titlethe text to convert, may be blank

cleanUserId(String userId)

Returns: String

Strips a user id down to letters, digits and underscores, dropping every other character. A null input raises a runtime exception.

ParameterDescription
userIdthe user id to clean

formatPhoneNumber(Object obj, Object phone)

Returns: String

Formats a phone number into the E164 international form, such as a plus sign followed by the country code and number with no spaces. The country to interpret a local number against can be given directly or taken from an organisation.

ParameterDescription
objan Organisation, an OrgData or an ISO two letter country code such as NZ, AU or US, whose country is used as the region
phonethe phone number to format; a number already in international form ignores the country

formatPhoneNumber(Object obj, Object phone, String format)

Returns: String

Formats a phone number into a chosen standard form. The country to interpret a local number against can be given directly or taken from an organisation, and an unrecognised format name falls back to E164.

ParameterDescription
objan Organisation, an OrgData or an ISO two letter country code such as NZ, AU or US, whose country is used as the region
phonethe phone number to format; a number already in international form ignores the country
formatone of E164, INTERNATIONAL, NATIONAL or RFC3966, defaulting to E164

textFromHtml(String htmlContents)

Returns: String

Strips the markup from an HTML document and returns the readable text, suitable for a plain text email body or a search index.

ParameterDescription
htmlContentsthe HTML to flatten, may be null

propertyOfObject(Object o1, Object o2)

Returns: Object

Reads a named property from an object by reflection, so a template can look up a field whose name is only known at runtime. Nested paths such as 'profile.name' are supported.

ParameterDescription
o1the object to read from, may be null
o2the property name or dotted property path, rendered with format

newTextOptionType(Object placeholder)

Returns: TextOptionType

Creates a free text option type for a mail merge or field definition, with the given placeholder shown in the editor.

ParameterDescription
placeholderthe placeholder text to show, rendered with format

newListOptionBuilder()

Returns: ListOptionTypeBuilder

Creates a builder for a list option type, used to declare a fixed set of choices for a field. Add each choice with addOption, giving its stored value and its display title, then call build to get the option type.

toPlainEmail(Object o)

Returns: String

Extracts the bare email address from an address that may carry a display name, so a value like 'Joe Bloggs joe at bloggs.com' in angle bracket form yields just the address part.

ParameterDescription
othe address to parse, rendered with format

textToHtml(String text)

Returns: String

Wraps plain text in HTML, turning each line into its own paragraph element. Text that already looks like HTML, because it contains a paragraph or anchor tag, is returned unchanged. The text is not escaped.

ParameterDescription
textthe plain text to convert, may be blank

getRandomGuid()

Returns: String

A freshly generated random UUID in its standard hyphenated string form, for use as a unique identifier.

formatUnits(Object o)

Returns: String

Renders a number abbreviated with a metric suffix, so 3123 becomes 3.1k and 4500000 becomes 4.5m. Values under 3000 are shown in full, and the number of decimal places narrows as the magnitude grows.

ParameterDescription
othe number to abbreviate, may be null

encodeAsHtmlEntities(String s)

Returns: String

Escapes a string into HTML entities, converting every character that has a named entity as well as the markup characters.

ParameterDescription
sthe text to escape, may be null

firstNotNull(Object vals)

Returns: String

Returns the first of the given values that is not empty, rendered as a string. Emptiness is decided by isNotEmpty, so a blank string and an empty collection are both skipped.

ParameterDescription
valsthe candidate values in order of preference, may be null

firstNotNull2(Object vals)

Returns: Object

Returns the first of the given values that is not null, as the original object rather than as a string. Unlike firstNotNull this keeps the value's type and only skips values that isNull rejects.

ParameterDescription
valsthe candidate values in order of preference, may be null

safeGet(List list, int pos)

Returns: Object

Reads the item at the given index of a list without throwing when the index is out of range or the list is null.

ParameterDescription
listthe list to read from, may be null
posthe zero based index to read

safeGet(Object[] array, int pos)

Returns: Object

Reads the element at the given index of an array without throwing when the index is out of range or the array is null.

ParameterDescription
arraythe array to read from, may be null
posthe zero based index to read

cleanString(Object o)

Returns: String

Sanitises untrusted text with the platform's AntiSamy policy, dropping scripts and dangerous attributes while letting a safe subset of HTML elements through, then trims the result. Use this on anything a user typed before storing or displaying it.

ParameterDescription
othe untrusted value to sanitise, may be null

cleanString(Object o, boolean makePlain)

Returns: String

Sanitises untrusted text with the platform's AntiSamy policy, optionally flattening it to plain text first so that paragraphs, line breaks and headings are stripped as well rather than surviving the sanitiser.

ParameterDescription
othe untrusted value to sanitise, may be null
makePlaintrue to strip the remaining markup with toPlain before sanitising

containsDangerous(String dirtyComment)

Returns: boolean

True when the given text contains markup that the platform's AntiSamy policy would strip, so a caller can reject the input outright instead of silently sanitising it.

ParameterDescription
dirtyCommentthe untrusted text to inspect, may be null

paginator()

Returns: Paginator

Creates a Paginator, the helper that reads the page and page size request parameters and renders the paging controls for a listing.

paginator(int defaultPageSize)

Returns: Paginator

Creates a Paginator with an explicit default page size, used when the request does not name one.

ParameterDescription
defaultPageSizethe number of rows per page to use when the request does not specify

translate(String sourceType, String sourceId, String field, String langCode)

Returns: String

Looks up the stored translation of one field of one record, in a specific language. Translations are keyed by the source type, the record id and the field name.

ParameterDescription
sourceTypethe kind of record being translated, such as an entity name
sourceIdthe identifier of the record being translated
fieldthe name of the field being translated
langCodethe language code to translate into

translate(String sourceType, String sourceId, String field)

Returns: String

Looks up the stored translation of one field of one record, in the language of the current request.

ParameterDescription
sourceTypethe kind of record being translated, such as an entity name
sourceIdthe identifier of the record being translated
fieldthe name of the field being translated

translate(String sourceType, String sourceId)

Returns: String

Looks up the stored translation of a record's default field, in the language of the current request.

ParameterDescription
sourceTypethe kind of record being translated, such as an entity name
sourceIdthe identifier of the record being translated

translate(Translatable source, String field)

Returns: String

Looks up the stored translation of one field of a translatable record, taking the source type and id from the record itself.

ParameterDescription
sourcethe record to translate, which supplies its own source type and id
fieldthe name of the field being translated

translate(String sourceText)

Returns: String

Translates a literal piece of text into the language of the current request, matching on the text itself rather than on a record and field.

ParameterDescription
sourceTextthe text to translate

asUser(Object oUser)

Returns: Profile

Coerces a value into a Profile. Accepts a Profile, a user resource or admin user page, or a username string which is looked up in the current organisation. Looking up by username hits the database.

ParameterDescription
oUsera Profile, a user resource, or a username string, may be null

asGroup(Object oGroup)

Returns: Group

Coerces a value into a Group. Accepts a Group, a group management folder, or a group name string which is looked up in the current organisation. Looking up by name hits the database.

ParameterDescription
oGroupa Group, a group management folder, or a group name string, may be null

asWebsite(Object oWebsite)

Returns: Website

Coerces a value into a Website. Accepts a Website, a website root folder, a website or branch management folder, or a website name string which is looked up in the current organisation. Looking up by name hits the database.

ParameterDescription
oWebsitea Website, a website folder, or a website name string, may be null

formatDateWithHyphens(Date dt)

Returns: String

Formats a date as yyyy-MM-dd, the sortable hyphenated form used in file names and data exports.

ParameterDescription
dtthe date to format

deCamelise(String camelCase)

Returns: String

Turns a camel case identifier into a human readable label, so firstName becomes 'First name'. Handy for labelling fields whose names come from the data model.

ParameterDescription
camelCasethe camel case identifier, may be null

findDayOnOrBefore(int dayIndex, Date dt)

Returns: Date

Steps backwards from the given date to the most recent occurrence of a weekday, returning the date itself when it already falls on that day. The day index follows Joda numbering, where Monday is 1 and Sunday is 7, and any other value raises a runtime exception. The time of day is left as it was.

ParameterDescription
dayIndexthe target weekday, from 1 for Monday to 7 for Sunday
dtthe date to step back from

isEmpty(Object o)

Returns: boolean

True when the given value is semantically empty, which covers null, undefined, a blank string, and an empty list, map or array. A numeric zero and a false boolean are not empty.

ParameterDescription
othe value to test, may be null

isNotEmpty(Object o)

Returns: boolean

True when the given value has content, that is anything isEmpty does not treat as empty.

ParameterDescription
othe value to test, may be null

foreach(Object iterable, BiConsumer consumer)

Returns: void

Iterates over a collection, map, array or a count and calls the given function once per item. A map is iterated over its values, and an Integer or Long is treated as a count so the function is called with the numbers from zero up to it. The function receives the item and a loop context carrying the current index. Calling breakForeach from inside the function stops the loop early, and the loop yields to the Governor on each item so a long iteration stays interruptible.

ParameterDescription
iterablethe collection, map, array or count to iterate over
consumerthe function to call with each item and the loop context

foreach(Object iterable, ScriptObjectMirror r)

Returns: void

Iterates over a collection, map, array or a count and calls the given Nashorn script function once per item, with the item and a loop context carrying the current index. A function of any other type raises a runtime exception.

ParameterDescription
iterablethe collection, map, array or count to iterate over, may be null
rthe Nashorn script function to call with each item and the loop context

_foreach(Object[] arr, BiConsumer r)

Returns: void

Iterates over an array by copying it into a list and delegating to the iterable form, clearing any pending break flag first.

ParameterDescription
arrthe array to iterate over
rthe function to call with each element and the loop context

_foreach(Iterable it, BiConsumer r)

Returns: void

Iterates over anything iterable, calling the given function with each item and a loop context that carries the index and its own break flag. Yields to the Governor on each item, and always clears the thread local break flag on the way out so a break on the last item cannot leak into the next loop on the same thread.

ParameterDescription
itthe items to iterate over
rthe function to call with each item and the loop context

breakForeach()

Returns: void

Stops the innermost foreach loop on this thread at the end of the current item, the equivalent of a break statement inside the loop function.

stringJoin(List<String> list, String separator)

Returns: String

Joins a list of strings with a separator, dropping the null and empty entries first so an absent address line does not leave a doubled separator. Note that the list passed in is modified in place.

ParameterDescription
listthe values to join, modified in place to remove the empty entries
separatorthe text to place between values

parseDateISO8601(String s)

Returns: Date

Parses an ISO 8601 timestamp and returns it as a Date, presented in the current tenant organisation's timezone. Text that is not a valid ISO 8601 timestamp raises a runtime exception.

ParameterDescription
sthe ISO 8601 text to parse, may be blank

dateTimePattern(String context)

Returns: String

Returns the date and time format pattern the current organisation should use, in the syntax of the requested platform. Picks the US month first ordering or the day first ordering according to the organisation's date setting.

ParameterDescription
context'js' for a moment.js style pattern or 'java' for a Java pattern; anything else gives the Java day first pattern

datePattern(String context)

Returns: String

Returns the date only format pattern the current organisation should use, in the syntax of the requested platform. Picks the US month first ordering or the day first ordering according to the organisation's date setting.

ParameterDescription
context'js' for a moment.js style pattern or 'java' for a Java pattern; anything else gives the Java day first pattern

andClause(Object a, Object b)

Returns: boolean

Logical AND of two truthy values, each coerced with toBool. Note that both arguments are evaluated, and a value that toBool cannot interpret raises a runtime exception.

ParameterDescription
athe first value, coerced with toBool
bthe second value, coerced with toBool

orClause(Object a, Object b)

Returns: boolean

Logical OR of two truthy values, each coerced with toBool. Note that both arguments are evaluated, and a value that toBool cannot interpret raises a runtime exception.

ParameterDescription
athe first value, coerced with toBool
bthe second value, coerced with toBool

parseExtraFieldDef(String name, String fieldDef)

Returns: ExtraField

Builds an ExtraField definition from a field name and the platform's compact extra field definition syntax, which encodes the field type, whether it is required, and any option list.

ParameterDescription
namethe field name
fieldDefthe field definition in the standard extra field syntax

formatToCleanHtml(String original)

Returns: String

Turns user entered plain text into safe display HTML. Line breaks become break tags, the rest of the text is HTML escaped, and anything that looks like a URL is wrapped in a nofollow link that opens in a new tab.

ParameterDescription
originalthe plain text to convert

parseSearch(String q)

Returns: KSearchQuery

Parses a search expression written in the platform's query syntax into a KSearchQuery that can be run against the search index.

ParameterDescription
qthe search expression

newExtraField(String name, boolean required)

Returns: ExtraField

Creates an ExtraField definition with the given name, deriving its display label from the name by de-camelising it.

ParameterDescription
namethe field name, also used to derive the label
requiredtrue if a value must be supplied for the field

getCurrentRootFolder()

Returns: RootFolder

Root folder the current request is being served from, which is the website, admin or organisation root that determines the tenant and the resource tree. Null outside a request.

randomInt(Object oRange)

Returns: int

Returns a random whole number from zero up to but not including the given bound. A bound of zero or less raises a runtime exception. Not suitable for security purposes.

ParameterDescription
oRangethe exclusive upper bound, coerced with toInteger

randomHex(int numDigits)

Returns: String

Returns a random lower case hexadecimal string of the given length. Not suitable for security purposes; use the crypto helper for anything that must be unguessable.

ParameterDescription
numDigitsthe number of hexadecimal characters to return

randomAlpha(int numChars)

Returns: String

Returns a random alphanumeric string of the given length, useful for a code or a temporary name. Not suitable for security purposes.

ParameterDescription
numCharsthe number of characters to return

randomAlpha(int numChars, String excludedCharacters)

Returns: String

Returns a random alphanumeric string of the given length, leaving out any character listed in the exclusions. Useful for codes people have to read aloud, where characters such as O and 0 are best avoided.

ParameterDescription
numCharsthe number of characters to return
excludedCharactersthe characters to leave out, as a single string, may be empty

normalizeString(String s)

Returns: String

Strips accents and other combining marks from text and drops anything left that is not ASCII, so 'Muller' with an umlaut becomes plain 'Muller'. Useful for building comparison keys and identifiers.

ParameterDescription
sthe text to normalise, may be null

toRanges(Collection originalList, int partitionSize)

Returns: List<Pair<Integer,Integer>>

Splits the index space of a collection into ranges of at most the given size, each returned as a pair of start and finish indexes where the finish is exclusive. Use it to process a large collection in batches. See splitList for the variant that returns the sublists themselves.

ParameterDescription
originalListthe collection whose size sets the index space, may be null
partitionSizethe maximum number of items per range

splitList(Collection src, int partitionSize)

Returns: List<List>

Breaks a collection into consecutive sublists of at most the given size, for processing a large collection in batches.

ParameterDescription
srcthe collection to break up
partitionSizethe maximum number of items per sublist

newTable(String id)

Returns: TableViewMetaBuilder

Creates a builder for a table definition, which describes the columns, sorting and paging of a listing rendered by the standardTable macro.

ParameterDescription
idthe identifier for the table, used to key its client side state

newFormContext()

Returns: FormContext

Creates a FormContext over the current request's parameters, giving null safe reads that are cleaned to the platform's OWASP rules. Use it instead of reading raw request parameters.

newFormContext(Map<String,String> params)

Returns: FormContext

Creates a FormContext over an explicit map of parameters rather than the current request, which suits validating values that came from somewhere other than a form post.

ParameterDescription
paramsthe parameter names and values, null for an empty set

newSearchProperties(Integer startPos, Integer pageSize)

Returns: SearchProperties

Creates a SearchProperties holding the paging window to apply to a search or query.

ParameterDescription
startPosthe zero based index of the first row to return, null for the default
pageSizethe maximum number of rows to return, null for the default

newSearchProperties(Integer startPos, Integer pageSize, String orderBy, String orderDir)

Returns: SearchProperties

Creates a SearchProperties holding both the paging window and the sort order to apply to a search or query.

ParameterDescription
startPosthe zero based index of the first row to return, null for the default
pageSizethe maximum number of rows to return, null for the default
orderBythe name of the field to sort on
orderDirthe sort direction, ascending or descending

newStringBuilder()

Returns: StringBuilder

Creates an empty StringBuilder, a mutable string that a template or script can append to in a loop without building up garbage.

newMembershipList()

Returns: MembershipList

Creates an empty MembershipList, the collection used to gather group memberships before applying them to a profile.

isImage(String newName, String contentType)

Returns: boolean

True when a file looks like an image, judged from its file name extension and its content type.

ParameterDescription
newNamethe file name, may be null
contentTypethe declared content type, may be null

lowest(Object vals)

Returns: Object

Returns the smallest of the given values by their natural ordering, which means every value must be comparable with the others.

ParameterDescription
valsthe values to compare, given as an array or as loose arguments

highest(Object vals)

Returns: Object

Returns the largest of the given values by their natural ordering, which means every value must be comparable with the others.

ParameterDescription
valsthe values to compare, given as an array or as loose arguments

obfuscateEmail(String email)

Returns: String

Masks the middle of an email address so it can be shown to a user for recognition without disclosing the whole address.

ParameterDescription
emailthe address to mask, may be null

convertMapToParamString(Map<String,String> params)

Returns: String

Renders a map of string names and values as a single encoded parameter string, for storing a set of settings in one column or field. Read it back with parseParamStringToMap.

ParameterDescription
paramsthe names and values to encode

parseParamStringToMap(String params)

Returns: Map<String,String>

Parses a parameter string produced by convertMapToParamString back into a map of names and values.

ParameterDescription
paramsthe encoded parameter string, may be null

Returns: String

Renders an admin link to the given entity, with an icon and the entity's display name, choosing the right URL for its type.

ParameterDescription
othe entity to link to, may be null

Returns: String

Renders an admin link to the given entity with an icon and its display name, choosing the URL that matches its type. Understands profiles, organisations, sales data series, rewards and points buckets, org types, groups, voucher types and vouchers, products, SKUs and categories, blogs, websites, app and funnel repositories. Profile and website links point at the public facing URL instead when the request is being served from a website.

ParameterDescription
othe entity to link to, such as a Profile, ProfileBean, Organisation or OrgData, may be null
clsCSS class names to put on the anchor, may be null or empty

Returns: String

Renders an anchor with an explicit URL and label. The label is sanitised and flattened to plain text before it is written.

ParameterDescription
hrefthe URL for the anchor's href attribute
textthe link label, sanitised before rendering
clsCSS class names to put on the anchor, may be null or empty

calcGaussianDecay(double elapsedDurationActual, double standardDev, double multiplier)

Returns: double

Calculates a Gaussian decay factor for how much a value should be discounted as time passes, which is how the platform ages engagement and recency scores. The factor is one at zero elapsed time and falls towards zero as the elapsed time grows past the standard deviation.

ParameterDescription
elapsedDurationActualthe time that has elapsed, in whatever unit the standard deviation is expressed in
standardDevthe standard deviation, which sets how quickly the value decays
multiplierscaling factor applied to the decay curve

docsHtml(Object target)

Returns: String

Renders the developer reference for an object as HTML, listing the properties and methods it exposes to templates and scripts. Use it while developing to see what is available on a value.

ParameterDescription
targetthe object to document, may be null

docsText(Object target)

Returns: String

Renders the developer reference for an object as plain text, listing the properties and methods it exposes to templates and scripts. The plain text form suits logging and script consoles.

ParameterDescription
targetthe object to document, may be null

supplyInStopWatch(String name, Supplier r)

Returns: Object

Runs the given function inside a named stopwatch so its duration shows up in debug session performance reports, and returns whatever the function returned.

ParameterDescription
namethe label for the stopwatch entry
rthe function to time, null to time nothing

runInStopWatch(String name, Runnable r)

Returns: void

Runs the given block inside a named stopwatch so its duration shows up in debug session performance reports. Use supplyInStopWatch when the block has to return a value.

ParameterDescription
namethe label for the stopwatch entry
rthe block to time, null to time nothing

lapStopWatch(String name)

Returns: void

Records a lap against the stopwatch currently running on this thread, so a long operation can be broken into named phases in the performance report.

ParameterDescription
namethe label for the lap

replaceText(String source, String findText, String replaceWith)

Returns: String

Replaces every occurrence of a literal piece of text with another, treating the search text as plain characters rather than as a regular expression.

ParameterDescription
sourcethe text to search in, may be null
findTextthe literal text to look for
replaceWiththe text to put in its place

replaceAllText(String source, String findText, String replaceWith)

Returns: String

Repeatedly replaces a literal piece of text until none remains, which also catches occurrences that only appear after an earlier replacement. Take care: if the replacement itself contains the search text this never finishes.

ParameterDescription
sourcethe text to search in
findTextthe literal text to look for
replaceWiththe text to put in its place, which must not contain findText

checkPathTraversal(String inputString)

Returns: boolean

Checks that a user supplied path fragment cannot be used for a path traversal attack. The value must start with a letter or digit and must not contain a run of dots followed by a slash, a backslash or the end of the string. A blank value passes.

ParameterDescription
inputStringthe path fragment to check, may be blank

toMap(Object source)

Returns: Map<String,Object>

Copies any map into a plain insertion ordered map, which gives uniform handling of the different map types that reach the server from Nashorn and GraalJS. A value that is not a map raises a runtime exception.

ParameterDescription
sourcethe map to copy, may be null

toMap(List list, String keyPropName)

Returns: Map<String,Object>

Indexes a list into a map by reading one property from each item and using it as the key, so a list can be looked up by id or name. Items whose key is blank are skipped, and where two items share a key the later one wins.

ParameterDescription
listthe items to index, may be null or empty
keyPropNamethe name of the property on each item to use as the key

standardiseTimezoneId(String timezoneId)

Returns: String

Maps a timezone id onto the name the platform's date library recognises, currently rewriting Europe/Kyiv to Europe/Kiev. Any other id is returned unchanged.

ParameterDescription
timezoneIdthe timezone id to normalise, may be null
To get full access to the Kademi Hub existing customers can login here, or new customers can register here.