Handy functions exposes to rendering logic for formatting.


Properties

Name Returns Notes Example
now Date Get the current date and time
yearStart Date Returns the date of the first day of the current year
currentDateService CurrentDateService
list ResourceList Just create a new list, same as newList()
port int Attempts to find the port of the current request, defaults to 80
portString String Returns empty string if the current request is on port 80, otherwise returns the port number prefixed with a colon, eg :8080
baseWebsiteUrl String
countryCodes CountryCodes
countryCodeOfOrg CountryCode
queryString String Returns the querystring of the current request. This is the question mark and everything following it
crypto CryptoImpl Get an instance of the CryptoImpl class
geoIPService GeoIPService Get an instance of the GeoIPService class
randomGuid String Calculate a random UUID
currentRootFolder RootFolder Return the current root folder

Methods

Name Returns Notes Example
newNarrative ( ) Narrative Create an instance of Narrtive, for use with services that use this interface to report complex messages to users
toString ( o ) String Null safe method, returns empty string if the value is null
toBool ( o ) Boolean Convert just about anything truthy to a Boolean, or return null if its blank
Collections return true if they are non-empty
Strings return true if they are "true" or "yes" or "1"
Integers are true if not equal to zero
toDecimal ( o, places ) BigDecimal Convert just about anything to a BigDecimal
toDoubleSafe ( o ) Double
toDouble ( o ) Double Convert just about anything to a Double precision number If null returns zero.
toInteger ( o ) Integer Attempt to convert to an Integer, where nulls are returned as zero
toLong ( o ) Long Attempt to convert anythiong to a Long number. Defaults to zero, so will never return null
toLong ( oVal, withNulls ) Long Attempt to convert to a Long number, optionally represent empty values either as null or zero
toPath ( s ) Path Convert the given string to a Path object, like /a/b/c
getFileName ( s ) String Get the last path segment (ie the file name) from a path string
getYear ( o ) int Convert the given object to a date and return the year portion
getMonth ( o ) int Convert to a date and return the month component, one indexed!! Also attempts a 3 letter starts with, so will return 1 for Jan, January, etc, and 12 for dec, DECEMBER, etc
getDayOfMonth ( o ) int Convert to a date and then return the day of the month (1 indexed)
getHour ( o ) int Convert to a date and return the hour component
getMinute ( o ) int Convert to a date and return the minute component
getDayOfWeek ( o ) int Returns the day of the week, 1 being Sunday and 7 being Saturday
getDayOfWeekName ( o ) String Get the day of the week name, 1 = Sunday, 7 = Saturday
formatDate ( o ) String Outputs the date part only (not time)
formatDateWithLocale ( o, localeId ) String
formatDate ( o, timezone ) String Get a date only representation of the given date like object, using the given timezone
formatTime ( o ) String Output the time in short format for the give timezone
formatTime ( o, timezone ) String Output the time in short format for the give timezone
formatTimeLong ( o, timezone ) String Output the time in long format for the give timezone
formatDateLong ( o ) String Outputs the date and time in a long format
formatDateLong ( o, timezone ) String Get a long date and time representation of the given value, using the given timezone
formatDateTime ( o ) String Outputs date and time short in a compact format
formatDateWithPattern ( o, pattern ) String Outputs date with given pattern
getFirstOfMonth ( month, timeZone ) Date Outputs a date object with the first day of the specified month in the current year
newDate ( year, month, day ) Date
calcNextBirthday ( date ) Date Given a user's birthdate, calculate their next birthday
formatDateTime ( o, timezone ) String
formatDateISO8601 ( o ) String Output an ISO8601 representation of the given date like value, for the timezone of the servers This is useful for using with timeago
formatDateISO8601 ( o, timezone ) String Output an ISO8601 representation of the given date like value, for the given timezone This is useful for using with timeago
formatAge ( o ) String Returns a user friendly description of the age of the date. Eg "4 minutes ago"
formatMinsAsDuration ( o ) String For a given value which is some number of minutes, generate a user friendly representation as a duration, eg "1 hour"
formatMinsAsDuration ( o, numeric ) String Given a value which can be parsed to a Long, return it formatted as a human readable duration such as 12:30 (12 mins, 30 seconds) or 12 mins, 3 hrs 20
pad2 ( l ) String
pad ( l, length ) String
getDateTime ( o ) DateTime Returns a DateTime, not adjusted for any timezone
getDateTime ( o, timezoneId ) DateTime Returns a Jodatime DateTime object that can be easily manipulated
toPercent ( num, div ) String Format as a percentage, including a percentage symbol and where blank/null values result in a blank output
toPercent ( num, div, appendSymbol, withBlanks ) String
format ( o ) String Format as a date, if its a date. Otherwise as a string
stripExt ( s ) String Removes the file extension if present Eg file1.swf -> file1 file1 -> file1
fileExt ( fileName ) String Returns the file extension, if there is one.
gt ( val1, val2 ) boolean True if val1 is greater then val2 will do string conversions
gte ( val1, val2 ) boolean True if val1 is greater then val2 will do string conversions
lte ( val1, val2 ) boolean True if val1 is less then or equal val2
lt ( val1, val2 ) boolean True if val1 is less then val2
eq ( val1, val2 ) boolean
not ( o ) Boolean Just for convenience, accepts any truthy parameter which is converted to Boolean and then negated
htmlEncode ( s ) String Makes the given string suitable for rendering in HTML. Symbols like angle brackets will be encoded so they can be displayed
htmlAttEncode ( s2 ) String Modifies the given value so that it is suitable for use in HTML attributes This is a lossy conversion, in that multiple unencoded strings might encode to the same att value '"' ([^<&"] | Reference)* '"' | "'" ([^<&'] | Reference)* "'" So, you can't have: the same character that opens/closes the attribute value (either ' or ") a naked ampersand (& must be &) a left angle bracket (< must be <)
htmlAttDecode ( s2 ) String Just reverses htmlAttEncode, which encodes specific characters not legal for html attributes
percentDecode ( s ) String Decode percentage encoded paths. Eg a%20b -> a b
percentEncode ( s ) String
between ( oVal, oStart, oFinish ) boolean Returns true if the given value is between the start and finish dates, or the respective values are null. Ie if start date is null and finish date is given it will only check that the value is less then the finish date Values are converted using the joda time converters
toDate ( oVal ) Date
toSqlDate ( oVal ) Date
toJodaDate ( oVal ) DateTime
parseDateWithPattern ( dateS, pattern ) Date
parseDateWithPattern ( dateS, pattern, timezone ) Date
toPlain ( html ) String For a given piece of HTML, remove HTML tags (fairly crude)
getNow ( ) Date Get the current date and time
yearStart ( dt ) Date Returns the date of the first day of the year of the given date
monthStart ( dt, month ) Date Get the date/time of the first instant of the given month in the year indicated by the given date. The month is zero indexed, ie 0=January This is for the timezone set on the current organisation if there is one
monthStart ( dt ) Date Return the datetime of the start of thee month of the given date
yearEnd ( ) Date Get the date/time of the last instant of the current year.
yearEnd ( dt ) Date Get the date/time of the last instant of the given year indicated by the given date.
monthEnd ( dt, month ) Date Get the date/time of the last instant of the given month in the year indicated by the given date. The month is zero indexed, ie 0=January This is for the timezone set on the current organisation if there is one
durationSecs ( start, finish ) long Get the duration from the start to the finish date in seconds.
durationHours ( start, finish ) long Get the duration from the start to the finish date in seconds.
durationMins ( start, finish ) long
durationDays ( start, finish ) long
getMonthName ( i ) String Returns the long month name (eg January) for the given zero-indexed month, where 0 is January
getCurrentDateService ( ) CurrentDateService
ifEqual ( ifEqual, ifNotEqual, o1, o2 ) String If o1 is equal to o2, then output the ifEqual parameter, otherwise the ifNoteEqual parameter This is a nullsafe comparison
isEqual ( o1, o2 ) boolean Because sometimes JS == doesnt work
isNotEqual ( o1, o2 ) boolean
ifNull ( val, defaultVal ) Object Convenience method for when you want a value or some default if the value is null. If the first param is null, or if it is an empty string, then return the second param
ifTrue ( bb, o1, o2 ) Object This just permits simple templating syntax for basic conditional values Eg:
  • $item.text
  • ifFalse ( bb, o1, o2 ) Object
    newList ( ) ResourceList Just create a new list that you can add to
    getList ( ) ResourceList Just create a new list, same as newList()
    parseDate ( s ) Date
    sdf ( hasTime ) DateFormat
    toBigDecimal ( o, decimals ) BigDecimal
    calc ( list ) Calc Create a new calculator, which can do heaps of cool stuff
    where ( mvelExpr, list ) ResourceList Filter a list with a MVEL expression
    checked ( o ) String Convenience method to return the word "checked" if the passed argument is true'ish
    selected ( o ) String Convenience method to return the word "selected" if the passed argument is true'ish
    checkbox ( name, oChecked ) String
    checkbox ( id, name, oChecked ) String
    checkbox ( oId, name, oChecked, oValue ) String
    call ( o ) String Just a convenience method to use with velocity when you want to evaluate a function but not produce any output, eg using $list.add(..)
    bsswitch ( oId, name, oChecked, oValue ) String Normal checkbox, but optimised for bootstrap switch
    radioEq ( id, name, currentValue, value ) String Generate radio button HTML where you have the currently selected value of the input and the value that this input represents
    radioEq ( id, name, currentValue, value, className ) String Generate radio button HTML where you have the currently selected value of the input and the value that this input represents
    radio ( id, name, oChecked, value ) String Generate a radio button where you have a boolean value which indicates if this radion is currently checked/selected
    radio ( id, name, oChecked, value, className ) String Generate a radio button where you have a boolean value which indicates if this radion is currently checked/selected
    option ( value, oText, currentValue ) String Generate an option element
    select ( name, data ) String Generate a select box with the given options
    select ( name, currentVal, data ) String Generaet a select box with the given options and value
    select ( id, name, htmlClass, currentVal, data ) String Generaet a select box
    getPort ( ) int Attempts to find the port of the current request, defaults to 80
    isSecure ( ) boolean Returns true if the current http request was issued on ports 443 or 8443
    getPortString ( ) String Returns empty string if the current request is on port 80, otherwise returns the port number prefixed with a colon, eg :8080
    profilePicHref ( p ) String Deprecated, please use templating instead
    toCsv ( list ) String
    toProperties ( map ) String Convert the map entries to a string, in the form of a line for each pair, and each pair seperated by "="
    Eg
    a=b
    c=d
    toCsv ( list ) String
    toJson ( val ) String
    parseJson ( jsonStr ) Object
    addDays ( now, days ) Date Return a date which has the given number of days added (or subtracted if negative) to the given date
    addYears ( now, years ) Date
    addDays ( now, days ) Date Return a date which has the given number of days added (or subtracted if negative) to the given date
    getDaysBetween ( from, to ) List
    addMinutes ( now, mins ) Date
    getDomainName ( w ) String
    isNotNull ( o ) boolean
    isNull ( o ) boolean
    getVersionId ( rf ) String
    daysBetween ( from, to ) List List the dates between the given dates, including at least the from date
    endofDay ( dt ) Date Deprecated - use DateManagerV1.with(..) Return the time of the end of the given day, ie 23:59 Null safe
    endOfDay ( dt ) Date Deprecated - use DateManagerV1.with(..)
    endofDay ( dt, timezone ) Date Deprecated - use DateManagerV1.with(..)
    endOfDay ( dt, timezone ) Date Deprecated - use DateManagerV1.with(..)
    startOfDay ( dt ) Date Deprecated - use DateManagerV1.with(..) Return the time of the start of the given day, ie 00:00 Null safe Applies the organisation timezone
    startOfDay ( dt, timezone ) Date Deprecated - use DateManagerV1.with(..)
    truncate ( s, max ) String Returns a truncated string with a maximum length of max, followed by 3 fullstops if its truncated
    newArrayList ( ) ArrayList Just creates a new List which you can use in templating for adding objects of any type
    newCommonList ( ) CommonList Returns an instance of a Kademi CommonList, which is just like an ArrayList but with more methods that do cool things. Is the base class for ResourceList
    newMap ( ) LinkedHashMap Just creates a new map you can use in templating. Preserves insertion order.
    newSet ( ) LinkedHashSet Just create a new set, which you can use in templating. Preserves insertion order.
    newMapBuilder ( ) MapBuilder Just creates a new map builder you can use in templating.
    formatBytes ( o ) String Convert the given object to a user friendly description of the size, assuming the value is in bytes. If the value is a Resource it will take the content length Eg 300 B, 5 KB, 3 MB
    formatSecsAsDuration ( o ) String Format the given number of seconds as a user friendly duration, eg 20 secs, 5 minutes, 4 hours
    formatCurrency ( o ) String Use a decimal formatter to format to 2 decimal places, suitable for displaying many currencies
    formatCurrency ( o, leadingZeros ) String Use a decimal formatter to format to 2 decimal places, suitable for displaying many currencies
    formatDecimal ( o, numberDecimals ) String Use a decimal formatter to format to X decimal places, suitable for displaying many currencies.
    getStartOfWeek ( dt ) Date Returns the date of the first day of the week which the given date is in. This considers the first day of the week to be Monday. If you want it to be Sunday just do addDays(-1)
    capitalizeString ( o ) String
    sortByProperty ( list, propertyName ) List Sort the list by a property name
    sortReverse ( list ) List
    sort ( list ) List Sort a list by its natural comparable
    toggleParamVal ( paramName, val ) String Returns a string which contains all request parameters, but with a particular value toggled, ie added or removed, to the named parameter Toggled parameters are comma seperated lists of values For example, a request to ?categories=A,B&tags=C,D, if you toggleParamVal("tags,"C") that will return categories=A,B&tags=D
    toggleParamVal ( paramName, val, uniqueParam ) String Returns a string which contains all request parameters, but with a particular value toggled, ie added or removed, to the named parameter Toggled parameters are comma seperated lists of values For example, a request to ?categories=A,B&tags=C,D, if you toggleParamVal("tags,"C") that will return categories=A,B&tags=D
    addQueryParam ( href, paramName, paramVal ) String Adds a request name/value pair to a href. Be sure that the param name and value are percentEncoded if needed
    addNum ( from, addAmount ) Integer
    split ( s, sep ) String
    split ( s ) String
    splitByAnything ( s ) String Splits the given string by semi-colon, comma, space or newline
    toList ( arr ) List Just converts an array to a List
    formatNumeric ( o, format ) String Display as a number, including comma seperated. Uses a format pattern like #,###.00 For more options see DecimalFormat WARNING: When using with templating language you need to be VERY CAREFUL about delimiting hashes, because they are templating identifiers
    formatNumeric ( o ) String Uses the default pattern of #,###,###.00
    formatNumericNoDecimal ( o ) String
    isNumeric ( o ) boolean
    isType ( source, className ) boolean Returns true if the given object has the java class with the given simple name Eg formatter.isType(lead, "Lead");
    toBase64String ( o ) String Convert an object to an Base64 encoded string
    toBase64UrlString ( o ) String
    fromBase64AsString ( base64 ) String
    fromBase64AsByteArray ( base64 ) byte
    joinByteArray ( b1, b2 ) byte
    copyFromArray ( arr, from, to ) byte
    copyFromArray ( arr, from, to ) char
    getCrypto ( ) CryptoImpl Get an instance of the CryptoImpl class
    getGeoIPService ( ) GeoIPService Get an instance of the GeoIPService class
    parseHtml ( html ) Jerry Parses HTML and returns a Document object. This uses the Jerry API which is very similar to JQuery - http://jodd.org/doc/jerry/
    formatJodaDate ( date, pattern ) String Converts the given date object to a Joda DateTime, and then formats it with the supplied Joda pattern Eg "dd/MM/YYYY HH:mm:ss" See http://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormat.html
    formatJodaDate ( date, pattern, timeZone ) String Converts the given date object to a Joda DateTime, and then formats it with the supplied Joda pattern Eg "dd/MM/YYYY HH:mm:ss" See http://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormat.html
    formatAsCleanId ( title ) String Returns a value suitable for use as an identifier, ie does not contain spaces or special characters. Spaces are converted
    cleanUserId ( userId ) String
    formatPhoneNumber ( obj, phone ) String Formats a phone number in the E164 format using default rules.
    textFromHtml ( htmlContents ) String Remove html tags, returning plain text suitable for display
    newTextOptionType ( placeholder ) TextOptionType Creates a new TextOptionType
    newListOptionBuilder ( ) ListOptionTypeBuilder Creates a new ListOptionBuilder Template Example:
                            
    toPlainEmail ( o ) String Parse an email address and returns the plain email address.
    $formatter.toPlainEmail('"Joe Bloggs" \')
     returns "joe@bloggs.com"
    textToHtml ( text ) String Returns a html representation of the given text. This will transform newlines into
    tags
    getRandomGuid ( ) String Calculate a random UUID
    formatUnits ( o ) String Converts to a number, and then rounds and abbreviates with a metric suffix Eg 3123 is "3k"
    encodeAsHtmlEntities ( s ) String
    firstNotNull ( vals ) String
    safeGet ( list, pos ) Object
    safeGet ( array, pos ) Object
    cleanString ( o ) String
    containsDangerous ( dirtyComment ) boolean
    paginator ( ) Paginator Create and return a new paginator
    paginator ( defaultPageSize ) Paginator
    translate ( sourceType, sourceId, field, langCode ) String
    translate ( sourceType, sourceId, field ) String
    translate ( sourceType, sourceId ) String
    translate ( source, field ) String
    translate ( sourceText ) String
    asUser ( oUser ) Profile
    asGroup ( oGroup ) Group
    asWebsite ( oWebsite ) Website
    deCamelise ( camelCase ) String A sweet method to transform camel case strings like firstName into something more human friendly like First name
    findDayOnOrBefore ( dayIndex, dt ) Date Find the first day of the given day name prior to or equal to the given date
    isEmpty ( o ) boolean Returns true if the given object is semantically empty. This means its null, or its an empty list, or its a blank string. Note that a numeric value of zero is NOT considered empty
    isNotEmpty ( o ) boolean
    foreach ( it, r ) void
    foreach ( it, r ) void
    foreach ( arr, r ) void
    stringJoin ( list, separator ) String To join string in template with a separator ie address line 1, address line 2, city, state, country Remove empty element to avoid duplicated separators
    parseDateISO8601 ( s ) Date
    dateTimePattern ( context ) String Return the date/time format pattern for the given context. The context currently can be 'js' or 'java'
    datePattern ( context ) String
    andClause ( a, b ) boolean Get result of "AND" operation with two params
    orClause ( a, b ) boolean Get result of "OR" operation with two params
    parseExtraFieldDef ( name, fieldDef ) ExtraField Returns a ExtraField object, constructed from the field name, and a string containing extra field parameters in the standard extrafield format
    formatToCleanHtml ( original ) String Clean up the HTML (ie change line breaks to BRs) and change url's to links, ie a tags
    parseSearch ( q ) KSearchQuery
    newExtraField ( name, required ) ExtraField
    randomInt ( oRange ) int
    randomHex ( numDigits ) String Returns a random hex string with the given number of digits
    randomAlpha ( numChars ) String Returns a random alpha-numeric string with the given number of chars
    normalizeString ( s ) String
    toRanges ( originalList, partitionSize ) List Calculate ranges with the given maximum size for the given list Each item is a Pair which is the start and finish index for each range. See also splitList() if you want the list broken into sublists
    newTable ( id ) TableViewMetaBuilder Create a new TableViewMetaBuilder, which can be used with the standardTable macro
    newFormContext ( ) FormContext Creates a new FormContext which wraps the current request parameters, and provides safe access, ie null-safe and cleaned with OWASP rules
    newSearchProperties ( startPos, pageSize ) SearchProperties
    newStringBuilder ( ) StringBuilder Create a StringBuilder which is a mutable representation of a string
    newMembershipList ( ) MembershipList Returns a new MembershipList object
    isImage ( newName, contentType ) boolean Returns true if the name and/or content type indicate an image file
    lowest ( vals ) Object For a given list of items (as varargs), return the lowest value
    highest ( vals ) Object For a given list of items (as varargs), return the highest value
    obfuscateEmail ( email ) String
    convertMapToParamString ( params ) String Generates a string representation of the given map of name value params (which must also be all strings)
    parseParamStringToMap ( params ) Map Parses a string representation (created with convertMapToParamString) back into a map of name/value pairs
    link ( o, cls ) String
    link ( href, text, cls ) String
    calcGaussianDecay ( elapsedDurationActual, standardDev, multiplier ) double
    docsHtml ( target ) String
    docsText ( target ) String
    To get full access to the Kademi Hub existing customers can login here, or new customers can register here.