public final class

GeneralUtil

extends Object
java.lang.Object
   ↳ com.atlassian.confluence.util.GeneralUtil

Summary

Public Constructors
GeneralUtil()
Public Methods
static String alwaysMaskEmail(String emailAddress)
Masks an email address by replacing '@' with 'at' and '.' with 'dot'.
static String appendAmpsandOrQuestionMark(String str)
int arraySize(int[] array)
convenience method to allow us to determine the size of an int array a velocity file
static String base64Decode(String s)
static String base64Encode(String s)
static String checkPartnerDetails(License license, String buildPartnerName)
static String completeUrlEncode(String url)
A utility method to encode the given url for protocols which the CompleteURLEncoder supports.
static String constrainLength(String s, int length)
Truncate a string after n characters
static Map convertBeanToMap(Object bean)
static Date convertMailFormatDate(String date)
static Boolean convertToBoolean(Object obj)
static boolean convertToBoolean(Object bool, boolean defaultValue)
static Character convertToCharacter(Object obj)
static Integer convertToInteger(Object obj)
static String convertToString(Object obj)
static void copyDate(Calendar original, Calendar copy)
Takes two calendar objects and sets the Date of the second to the Date of the first.
static File createTempDirectoryInConfluenceTemp(String prefix)
static File createTempFile(String directory)
static String customGetPageUrl(AbstractPage page)
Need a special case of generalutils getpageurl that appends ? or ampersand smartly this is used to prefix url parameters that are appended after this path like: showcomments=true#addcomment
static String displayShortUrl(String url)
static String displayShortUrl(String url, int length)
static String doubleUrlEncode(String s)
static String escapeCDATA(String s)
static List escapeCommas(List toEscape)
Escape commas on each entry in the given list of strings.
static String escapeCommas(String toEscape)
Escapes commas and backslashes with leading backslashes.
static String escapeForHtmlAttribute(String s)
Escapes " and \ with a leading \ so that strings can't break out of double-quoted HTML attributes.
static String escapeForJavascript(String s)
Escapes ', " and \ with a leading \.
static String escapeXMLCharacters(String input)
Take a String which may contain or & and return an XML string containing entities
static String[] escapeXml(Object[] args)
Produces an array of XML escaped Strings from a list of Objects.
static String escapeXml(String stringToEscape)
static List filterNulls(Collection in)
Return a List with no null entries
static String findAndMaskEmail(String text, User currentUser)
static String format(String str)
static String format(Number number)
This method is deprecated. since 3.1 unused anywhere in the application.
static String format(Object obj)
static String formatDateFull(Date date)
static String formatLongTime(long time)
static Date getBuildDate()
static String getBuildDateString()
static String getBuildExcludedLocale()
static String getBuildNumber()
The build number of the currently running Confluence instance.
static String getBuildPartner()
static String getCharacterEncoding()
static String getCompactDuration(long time)
Returns the duration in a compact HH:mm:ss format.
static File getConfluenceTempDirectory()
static String getConfluenceTempDirectoryPath()
Checks if temp directory exists before returning the path.
static String getCookieValue(String key)
static ResourceBundle getDefaultResourceBundle()
static String getFormatDateSimple(Date date)
static Settings getGlobalSettings()
static I18NBean getI18n()
static String getIdBasedPageUrl(AbstractPage page)
Get page URL that is id based (i.e.
static ImageInfo getImageInfo(File pathToImage)
static String getNiceDuration(int minutes, int seconds)
static String getPageUrl(AbstractPage page)
static String getPageUrl(VersionHistorySummary summary)
long getPercentage(long numerator, long denom)
converts a fraction into a percentage
long getPercentage(String numeratorAsString, String denomAsString)
static <T> List<T> getRandomSubSet(List<T> list, int sizeOfSubset, Random random)
Returns a randomised subset of the list provided.
static String getRelativeTime(Date date)
This method is deprecated. since 2.7 use FriendlyDateFormatter
static String getStackTrace(Throwable t)
static Long getSystemStartupTime()
static String getUploadFileTooLargeMessage(String errorMessage)
if this error message is of the type: "java.io.IOException: Content Length Error" convert it to something nicer
static UserAccessor getUserAccessor()
static String getVersionNumber()
static String hackSingleQuotes(String s)
hack to make strings that contain singles compatible with javascript (which also uses single quotes denote strings)
static boolean hasTooManyUsers()
Check if the current installation has more active users than is allowed by the license
static String highlight(String content, String searchwords)
static String htmlEncode(String text)
static String htmlEncodeAndReplaceSpaces(String text)
static String htmlEscapeQuotes(String input)
Take a string and escape the quotes in it with \" and HTML escape them afterwards.
static boolean isAllAscii(String s)
static boolean isAllLettersOrNumbers(String s)
static boolean isDefaultUserProfilePicture(String username)
This method is deprecated. This method must not be used anymore, it is horribly inefficient. Rather use the ProfilePictureInfo: since it is never null, you can ask that object is the user has a default profile picture or not
static boolean isInLastDays(Date date, int maxDays)
static boolean isLicenseExpired()
static boolean isOutgoingMailConfigured()
static boolean isSafeTitleForFilesystem(String title)
This method is deprecated. Since Confluence 4.0. This was introduced in Confluence 3.0 but is no longer required.
static boolean isSafeTitleForUrl(String title)
Is "title" something we can safely put in a /foo/bar/title URL? Or should we reference this thing by ID just to be safe?
static boolean isSetupComplete()
static boolean isSuperUser(User user)
This method is deprecated. since 3.5 calls to the PermissionManager will ensure super-user checks are performed
static void loadDefaultProperties()
This method is deprecated. since 3.0 because it doesn't do anything
static String lookupDomainName(HttpServletRequest request)
Get the default domain name.
static String makeFlatSummary(String content, String query)
Create a summary of this content fragment given a query
static String makeFlatSummary(String content)
Create a summary of this content fragment.
static Summary makeSummary(String content)
Create a proper summary of this content fragment.
static Summary makeSummary(String content, String query)
Create a proper summary of this content fragment given a query
static String maskEmail(String emailAddress)
If configured, masks an email address to defeat the most simplistic spam bots.
static ConfluenceActionSupport newWiredConfluenceActionSupport()
static String personalSpaceUrl(String contextPath, String username)
static String plain2html(String text)
static String populateSimpleMessage(String template, List<String> values)

Populate the template String supplied using the given values.

static Map prefixAllMapKeys(String prefix, Map map)
Convert the supplied Map so that all of the keys in the Map are prefixed by the supplied String followed by a full stop.
static void profilePop(String s)
static void profilePush(String s)
static String rdfEncode(String s)
A fairly evil hack to work around CONF-10364.
static String replaceConfluenceHomeConstant(String in, String confHome)
static String replaceInvalidXmlCharacters(String text)
Take a String which may contain characters outside of the XML character range (http://www.w3.org/TR/REC-xml/#charsets) and return a String with those characters converted to Unicode "Replacement Character"s (0xFFFD).
static List safeSubList(List list, int max)
static Cookie setCookie(String key, String value)
Sets a cookie.
static void setSystemStartupTime(Long systemStartupTime)
static void setUserAccessor(UserAccessor userAcc)
static String shortenString(String str, int max)
Returns a substring of the specified string if it is longer than max.
static boolean shouldUrlDecode(String str)
static Collection specialLowerCaseCollection(Collection collection)
Takes a collection of Strings and lowercases the entries.
static String specialToLowerCase(String str)

the database lower() function in PostgreSQL only works for ASCII strings.
static String[] splitCommaDelimitedString(String escapedNames)
Method will turn a String of comma seperated entities into a String Array.
static boolean stringSet(String str)
long subtract(long a, long b)
long subtract(String firstOperandAsString, String secondOperandAsString)
static String summarise(String content)
This method is deprecated. since 2.0 use summarise(String) instead.
static Date toEndOfMonth(Calendar postDate)
Takes a Calendar object and returns the very end (last day, hour, minute, second and milisecond) of the month that the Calendar is in.
static String trimDownStringToWord(String s)
static String unescapeCDATA(String s)
static String unescapeEntities(String str)
static void unzipFile(File zipFile, File dirToExtractTo)
Unzips the zip file to a folder in temp and returns the File pointing to that expanded folder.
static void unzipUrl(URL zipUrl, File dirToExtractTo)
Unzips the zip url to a folder in temp and returns the File pointing to that expanded folder.
static String urlDecode(String url)
static String urlEncode(String url)
A utility method to encode HTTP form parameter/values.
static String urlEncode(String value, String encoding)
static String wordWrap(String str, int max)
For really long strings that have no spaces or line breaks, browsers such as firefox, Netscape, have difficulty wrapping them inside a table cell, and so these strings end up stretching the cell longer than its suppose to be = ugly

we want to simulate IE's word-wrap/break function here
[Expand]
Inherited Methods
From class java.lang.Object

Public Constructors

public GeneralUtil ()

Public Methods

public static String alwaysMaskEmail (String emailAddress)

Masks an email address by replacing '@' with 'at' and '.' with 'dot'.

Parameters
emailAddress an email address to mask, eg dwillis@atlassian.com
Returns
  • a masked version of the email, eg dwillis at atlassian dot com

public static String appendAmpsandOrQuestionMark (String str)

public int arraySize (int[] array)

convenience method to allow us to determine the size of an int array a velocity file

public static String base64Decode (String s)

public static String base64Encode (String s)

public static String checkPartnerDetails (License license, String buildPartnerName)

public static String completeUrlEncode (String url)

A utility method to encode the given url for protocols which the CompleteURLEncoder supports. To only encode HTTP form parameter/values or fragments, use urlEncode() instead.

Parameters
url - the entire URL to encode
Returns
  • encoded url

public static String constrainLength (String s, int length)

Truncate a string after n characters

Parameters
s The String to truncate
length The maximum length allowed.
Returns
  • The truncated String -- or the original String if no truncation was needed.

public static Map convertBeanToMap (Object bean)

Parameters
bean a bean to be converted to a Map.
Returns
  • a Map where the keys are the property names from the beans, and the values are the property values. An empty Map will be returned if the bean cannot be converted.

public static Date convertMailFormatDate (String date)

public static Boolean convertToBoolean (Object obj)

public static boolean convertToBoolean (Object bool, boolean defaultValue)

public static Character convertToCharacter (Object obj)

public static Integer convertToInteger (Object obj)

public static String convertToString (Object obj)

public static void copyDate (Calendar original, Calendar copy)

Takes two calendar objects and sets the Date of the second to the Date of the first. Used to keep dates consistent regardless of timezones.

public static File createTempDirectoryInConfluenceTemp (String prefix)

public static File createTempFile (String directory)

public static String customGetPageUrl (AbstractPage page)

Need a special case of generalutils getpageurl that appends ? or ampersand smartly this is used to prefix url parameters that are appended after this path like: showcomments=true#addcomment

public static String displayShortUrl (String url)

public static String displayShortUrl (String url, int length)

public static String doubleUrlEncode (String s)

public static String escapeCDATA (String s)

public static List escapeCommas (List toEscape)

Escape commas on each entry in the given list of strings.

Parameters
toEscape Strings to escape
Returns

public static String escapeCommas (String toEscape)

Escapes commas and backslashes with leading backslashes.

Parameters
toEscape string to escape. If null, then null will be returned.

public static String escapeForHtmlAttribute (String s)

Escapes " and \ with a leading \ so that strings can't break out of double-quoted HTML attributes.

public static String escapeForJavascript (String s)

Escapes ', " and \ with a leading \.

public static String escapeXMLCharacters (String input)

Take a String which may contain or & and return an XML string containing entities

public static String[] escapeXml (Object[] args)

Produces an array of XML escaped Strings from a list of Objects. valueOf(Object) is used to produce Strings from the Objects

public static String escapeXml (String stringToEscape)

public static List filterNulls (Collection in)

Return a List with no null entries

public static String findAndMaskEmail (String text, User currentUser)

public static String format (String str)

public static String format (Number number)

This method is deprecated.
since 3.1 unused anywhere in the application.

TODO: Replace with a NumberFormatter, similar to DateFormatter

Returns
  • the number formatted a String, or null if an exception occurred.

public static String format (Object obj)

public static String formatDateFull (Date date)

public static String formatLongTime (long time)

public static Date getBuildDate ()

public static String getBuildDateString ()

public static String getBuildExcludedLocale ()

public static String getBuildNumber ()

The build number of the currently running Confluence instance.

See Also

public static String getBuildPartner ()

public static String getCharacterEncoding ()

public static String getCompactDuration (long time)

Returns the duration in a compact HH:mm:ss format.

Parameters
time duration in milliseconds
Returns
  • the duration in a compact HH:mm:ss format.

public static File getConfluenceTempDirectory ()

public static String getConfluenceTempDirectoryPath ()

Checks if temp directory exists before returning the path. Create it if it doesn't already exist.

Returns
  • path to temp directory inside Confluence home

public static String getCookieValue (String key)

public static ResourceBundle getDefaultResourceBundle ()

public static String getFormatDateSimple (Date date)

public static Settings getGlobalSettings ()

public static I18NBean getI18n ()

Returns

public static String getIdBasedPageUrl (AbstractPage page)

Get page URL that is id based (i.e. in the format /pages/viewpage.action?pageId=<pageId>)

Parameters
page the page to generate a url for
Returns
  • page URL that is id based

public static ImageInfo getImageInfo (File pathToImage)

public static String getNiceDuration (int minutes, int seconds)

public static String getPageUrl (AbstractPage page)

public static String getPageUrl (VersionHistorySummary summary)

public long getPercentage (long numerator, long denom)

converts a fraction into a percentage

public long getPercentage (String numeratorAsString, String denomAsString)

public static List<T> getRandomSubSet (List<T> list, int sizeOfSubset, Random random)

Returns a randomised subset of the list provided. If the size of the subset is larger than the list, the entire list is returned in a random order.

Parameters
list - the list to subset
sizeOfSubset - the size of the subset to return
random - the source of randomness
Returns
  • a randomised subset of the list

public static String getRelativeTime (Date date)

This method is deprecated.
since 2.7 use FriendlyDateFormatter

Returns
  • A relative time period, 'X hours, Y minutes ago'

public static String getStackTrace (Throwable t)

public static Long getSystemStartupTime ()

public static String getUploadFileTooLargeMessage (String errorMessage)

if this error message is of the type: "java.io.IOException: Content Length Error" convert it to something nicer

public static UserAccessor getUserAccessor ()

public static String getVersionNumber ()

public static String hackSingleQuotes (String s)

hack to make strings that contain singles compatible with javascript (which also uses single quotes denote strings)

public static boolean hasTooManyUsers ()

Check if the current installation has more active users than is allowed by the license

Returns
  • true if the number exceeds the license, false otherwise.

public static String highlight (String content, String searchwords)

public static String htmlEncode (String text)

public static String htmlEncodeAndReplaceSpaces (String text)

public static String htmlEscapeQuotes (String input)

Take a string and escape the quotes in it with \" and HTML escape them afterwards. We need this function to escape strings containing quotes passed into JavaScript functions null input will be returned as an empty String.

public static boolean isAllAscii (String s)

public static boolean isAllLettersOrNumbers (String s)

public static boolean isDefaultUserProfilePicture (String username)

This method is deprecated.
This method must not be used anymore, it is horribly inefficient. Rather use the ProfilePictureInfo: since it is never null, you can ask that object is the user has a default profile picture or not

public static boolean isInLastDays (Date date, int maxDays)

Parameters
date the date to check
maxDays the number of days into the past the date can fall
Returns
  • Whether whether the date falls within maxDays before the present.

public static boolean isLicenseExpired ()

public static boolean isOutgoingMailConfigured ()

public static boolean isSafeTitleForFilesystem (String title)

This method is deprecated.
Since Confluence 4.0. This was introduced in Confluence 3.0 but is no longer required.

Ensure the title is safe to be written to the file system. See CONF-10741.

public static boolean isSafeTitleForUrl (String title)

Is "title" something we can safely put in a /foo/bar/title URL? Or should we reference this thing by ID just to be safe?

public static boolean isSetupComplete ()

public static boolean isSuperUser (User user)

This method is deprecated.
since 3.5 calls to the PermissionManager will ensure super-user checks are performed

Parameters
user the user to check for (the null user will always return false
Returns
  • true if the user is a super-user, false otherwise.

public static void loadDefaultProperties ()

This method is deprecated.
since 3.0 because it doesn't do anything

See Also

public static String lookupDomainName (HttpServletRequest request)

Get the default domain name.

Parameters
request the request
Returns
  • null if request is null, otherwise a base URL derived from the request.

public static String makeFlatSummary (String content, String query)

Create a summary of this content fragment given a query

See Also
  • Summarizer

public static String makeFlatSummary (String content)

Create a summary of this content fragment.

See Also
  • Summarizer

public static Summary makeSummary (String content)

Create a proper summary of this content fragment.

See Also
  • Summarizer

public static Summary makeSummary (String content, String query)

Create a proper summary of this content fragment given a query

See Also
  • Summarizer

public static String maskEmail (String emailAddress)

If configured, masks an email address to defeat the most simplistic spam bots. If Confluence is not configured to mask email addresses, just returns the original address.

Passing in null to this method will just get you null back
Parameters
emailAddress the email address to mask
Returns
  • the masked email address, or the original address if masking is not configured

public static ConfluenceActionSupport newWiredConfluenceActionSupport ()

public static String personalSpaceUrl (String contextPath, String username)

public static String plain2html (String text)

public static String populateSimpleMessage (String template, List<String> values)

Populate the template String supplied using the given values. The template may contain place holders which are denoted numerically in the form {n} where n is an index into the supplied values list.

e.g. "The template called {1} will expects a colour here {0}".

This template will use value 0 and value 1 from the supplied values array. If the referenced value cannot be found then the place holder will simply be removed.

Parameters
template the template to be populated
values the values used to populate the template
Returns
  • a populated template with all place holder markers removed.

public static Map prefixAllMapKeys (String prefix, Map map)

Convert the supplied Map so that all of the keys in the Map are prefixed by the supplied String followed by a full stop. e.g. monkey could become howler.monkey.

If any of the keys in the Map are not Strings then they will be ignored.

Parameters
prefix the prefix to be pre-pended to each Map key, if null then the original Map will be returned.
map the Map to be modified. If null, then an empty Map will be returned.
Returns
  • a new Map containing the modified keys and the supplied values.

public static void profilePop (String s)

public static void profilePush (String s)

public static String rdfEncode (String s)

A fairly evil hack to work around CONF-10364. It sucks, but is necessary.

Parameters
s to encode
Returns
  • the input String with double hyphens replaced by --

public static String replaceConfluenceHomeConstant (String in, String confHome)

public static String replaceInvalidXmlCharacters (String text)

Take a String which may contain characters outside of the XML character range (http://www.w3.org/TR/REC-xml/#charsets) and return a String with those characters converted to Unicode "Replacement Character"s (0xFFFD). Note that this method does not "escape" the string (e.g. "&" is not converted to "&"). Similar to checkCharacterData(String) but converts illegals instead of throwing Exceptions.

public static List safeSubList (List list, int max)

public static Cookie setCookie (String key, String value)

Sets a cookie. set to use a default cookie age of one year and the context path as the default path

public static void setSystemStartupTime (Long systemStartupTime)

public static void setUserAccessor (UserAccessor userAcc)

public static String shortenString (String str, int max)

Returns a substring of the specified string if it is longer than max. This method also appends "..." to the end of the string if it does truncate it.

Returns
  • a substring of the specified string if it is longer than max.

public static boolean shouldUrlDecode (String str)

public static Collection specialLowerCaseCollection (Collection collection)

Takes a collection of Strings and lowercases the entries.

Parameters
collection the collection
Returns
  • lowercased collection of strings

public static String specialToLowerCase (String str)

the database lower() function in PostgreSQL only works for ASCII strings. All other unicode and multibyte characters like capital umlaut are not properly converted. At the moment, when searching for pages we do the following comparison:

lower(page.title) = :pageTitle (Where :pageTitle is normally .toLowerCase() first before being passed in)

This special lower case function will skip the JAVA .toLowerCase() for postgres whose database lower() is ineffective.

public static String[] splitCommaDelimitedString (String escapedNames)

Method will turn a String of comma seperated entities into a String Array. Spaces before or after the comma will be cropped. Backslashes are treated as escaped characters. Eg when "backslash""comma" is encountered, the backslash is discarded and the comma is not treated as a delimiter.

Parameters
escapedNames Comma delimited string with original commas and backslashes escaped by backslashes
Returns
  • String[] of escapedNames

public static boolean stringSet (String str)

public long subtract (long a, long b)

public long subtract (String firstOperandAsString, String secondOperandAsString)

public static String summarise (String content)

This method is deprecated.
since 2.0 use summarise(String) instead.

public static Date toEndOfMonth (Calendar postDate)

Takes a Calendar object and returns the very end (last day, hour, minute, second and milisecond) of the month that the Calendar is in. The original Calendar object is left unaltered.

Returns
  • Date object signifying the very end of the Calendar's month

public static String trimDownStringToWord (String s)

public static String unescapeCDATA (String s)

public static String unescapeEntities (String str)

public static void unzipFile (File zipFile, File dirToExtractTo)

Unzips the zip file to a folder in temp and returns the File pointing to that expanded folder.

Throws
Exception

public static void unzipUrl (URL zipUrl, File dirToExtractTo)

Unzips the zip url to a folder in temp and returns the File pointing to that expanded folder.

Throws
Exception

public static String urlDecode (String url)

public static String urlEncode (String url)

A utility method to encode HTTP form parameter/values. To encode entire URLs, use completeUrlEncode() instead.

Parameters
url - part of the url to encode
Returns
  • encoded url

public static String urlEncode (String value, String encoding)

public static String wordWrap (String str, int max)

For really long strings that have no spaces or line breaks, browsers such as firefox, Netscape, have difficulty wrapping them inside a table cell, and so these strings end up stretching the cell longer than its suppose to be = ugly

we want to simulate IE's word-wrap/break function here
Parameters
str the string to wrap
max max length of string allowed per line