com.atlassian.confluence.util
Class GeneralUtil

java.lang.Object
  extended bycom.atlassian.confluence.util.GeneralUtil

public final class GeneralUtil
extends Object


Constructor Summary
GeneralUtil()
           
 
Method Summary
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(com.atlassian.license.License license, String buildPartnerName)
           
static Date convertMailFormatDate(String date)
           
static Boolean convertToBoolean(Object obj)
           
static Character convertToCharacter(Object obj)
           
static Integer convertToInteger(Object obj)
           
static String convertToString(Object obj)
           
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 escapeForJavascript(String s)
          Escapes ', " and \ with a leading \.
static String escapeXml(String stringToEscape)
           
static String escapeXMLCharacters(String input)
          Take a String which may contain <, > or & and return an XML string containing entities
static List filterNulls(Collection in)
          Return a List with no null entries
static String findAndMaskEmail(String text, User currentUser)
           
static String format(Date date)
          Deprecated. since 2.3. Provided for pre-2.3 themes and layouts only. New themes and layouts should use $dateFormatter.format(Date) in the Velocity context or ConfluenceUserPreferences.getDateFormatter(FormatSettingsManager).
static String format(Number number)
          TODO: Replace with a NumberFormatter, similar to DateFormatter
static String format(Object obj)
           
static String format(String str)
           
static String formatBlogDate(Date date)
          Deprecated. since 2.3. Provided for pre-2.3 themes and layouts only. New themes and layouts should use $dateFormatter.formatBlogDate(Date) in the Velocity context or ConfluenceUserPreferences.getDateFormatter(FormatSettingsManager).
static String formatDateFull(Date date)
           
static String formatDateTime(Date date)
          Deprecated. since 2.3. Provided for pre-2.3 themes and layouts only. New themes and layouts should use $dateFormatter.formatDateTime(Date) in the Velocity context or ConfluenceUserPreferences.getDateFormatter(FormatSettingsManager).
static String formatLongTime(long time)
           
static String formatTime(Date date)
          Deprecated. since 2.3. Provided for pre-2.3 themes and layouts only. New themes and layouts should use $dateFormatter.formatTime(Date) in the Velocity context or ConfluenceUserPreferences.getDateFormatter(FormatSettingsManager).
static Date getBuildDate()
           
static String getBuildDateString()
           
static String getBuildExcludedLocale()
           
static String getBuildNumber()
           
static String getBuildPartner()
           
static String getCharacterEncoding()
           
static File getConfluenceTempDirectory()
           
static String getConfluenceTempDirectoryPath()
          Checks if temp directory exists before returning the path.
static String getCookieValue(String key)
           
static String getDefaultFontFamily()
           
static ResourceBundle getDefaultResourceBundle()
           
static String getFormatDateSimple(Date date)
           
static Settings getGlobalSettings()
           
static I18NBean getI18n()
           
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 Properties getProperties(String resource, Class callingClass)
          Deprecated. since 2.3 use PropertyUtils.getProperties(String, Class) instead
static Properties getPropertiesFromFile(File file)
          Deprecated. since 2.3 use PropertyUtils.getProperties(String, Class) instead
static Properties getPropertiesFromStream(InputStream is)
          Deprecated. since 2.3 use PropertyUtils.getProperties(String, Class) instead
static String getRelativeTime(Date date)
           
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 s)
          our own htmlEncode() ripped from the TextUtils class.
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 isGlobalAdministrator(Object notUsedAnyMore, User user)
          Deprecated. since 2.0 use PermissionManager directly, or use the $permissionHelper from velocity
static boolean isInLastDays(Date date, int maxDays)
           
static boolean isLicenseExpired()
           
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)
           
static String lookupDomainName(javax.servlet.http.HttpServletRequest request)
          Get the default domain name.
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)
          The function converts plain text into html in two steps.
static void profilePop(String s)
           
static void profilePush(String s)
           
static String replaceConfluenceHomeConstant(String in, String confHome)
           
static List safeSubList(List list, int max)
           
static javax.servlet.http.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)
           
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)
          Deprecated. since 2.0 use RendererUtil.summarise(String) instead.
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)
           
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

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

GeneralUtil

public GeneralUtil()
Method Detail

getStackTrace

public static String getStackTrace(Throwable t)

format

public static String format(Number number)
TODO: Replace with a NumberFormatter, similar to DateFormatter

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

format

public static String format(Date date)
Deprecated. since 2.3. Provided for pre-2.3 themes and layouts only. New themes and layouts should use $dateFormatter.format(Date) in the Velocity context or ConfluenceUserPreferences.getDateFormatter(FormatSettingsManager).

See Also:
DateFormatter.format(Date)

format

public static String format(String str)

format

public static String format(Object obj)

formatDateTime

public static String formatDateTime(Date date)
Deprecated. since 2.3. Provided for pre-2.3 themes and layouts only. New themes and layouts should use $dateFormatter.formatDateTime(Date) in the Velocity context or ConfluenceUserPreferences.getDateFormatter(FormatSettingsManager).

See Also:
DateFormatter.formatDateTime(Date)

formatTime

public static String formatTime(Date date)
Deprecated. since 2.3. Provided for pre-2.3 themes and layouts only. New themes and layouts should use $dateFormatter.formatTime(Date) in the Velocity context or ConfluenceUserPreferences.getDateFormatter(FormatSettingsManager).

See Also:
DateFormatter.formatTime(Date)

formatBlogDate

public static String formatBlogDate(Date date)
Deprecated. since 2.3. Provided for pre-2.3 themes and layouts only. New themes and layouts should use $dateFormatter.formatBlogDate(Date) in the Velocity context or ConfluenceUserPreferences.getDateFormatter(FormatSettingsManager).

See Also:
DateFormatter.formatBlogDate(Date)

convertMailFormatDate

public static Date convertMailFormatDate(String date)
                                  throws ParseException
Throws:
ParseException

convertToCharacter

public static Character convertToCharacter(Object obj)

convertToInteger

public static Integer convertToInteger(Object obj)

convertToBoolean

public static Boolean convertToBoolean(Object obj)

convertToString

public static String convertToString(Object obj)

urlEncode

public static String urlEncode(String url)

urlDecode

public static String urlDecode(String url)

shouldUrlDecode

public static boolean shouldUrlDecode(String str)

getPageUrl

public static String getPageUrl(VersionHistorySummary summary)

getPageUrl

public static String getPageUrl(AbstractPage page)

isSafeTitleForUrl

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?


customGetPageUrl

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


appendAmpsandOrQuestionMark

public static String appendAmpsandOrQuestionMark(String str)

wordWrap

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 -
max - - max length of string allowed per line

highlight

public static String highlight(String content,
                               String searchwords)

doubleUrlEncode

public static String doubleUrlEncode(String s)

isAllAscii

public static boolean isAllAscii(String s)

isAllLettersOrNumbers

public static boolean isAllLettersOrNumbers(String s)

getVersionNumber

public static String getVersionNumber()

getBuildDate

public static Date getBuildDate()

getBuildDateString

public static String getBuildDateString()

getBuildNumber

public static String getBuildNumber()

getBuildPartner

public static String getBuildPartner()

getBuildExcludedLocale

public static String getBuildExcludedLocale()

getSystemStartupTime

public static Long getSystemStartupTime()

setSystemStartupTime

public static void setSystemStartupTime(Long systemStartupTime)

isLicenseExpired

public static boolean isLicenseExpired()

checkPartnerDetails

public static String checkPartnerDetails(com.atlassian.license.License license,
                                         String buildPartnerName)

hasTooManyUsers

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.

stringSet

public static boolean stringSet(String str)

formatLongTime

public static String formatLongTime(long time)

displayShortUrl

public static String displayShortUrl(String url)

displayShortUrl

public static String displayShortUrl(String url,
                                     int length)

formatDateFull

public static String formatDateFull(Date date)

isSuperUser

public static boolean isSuperUser(User user)

getCharacterEncoding

public static String getCharacterEncoding()

escapeXml

public static String escapeXml(String stringToEscape)

escapeForJavascript

public static String escapeForJavascript(String s)
Escapes ', " and \ with a leading \.


isSetupComplete

public static boolean isSetupComplete()

maskEmail

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

findAndMaskEmail

public static String findAndMaskEmail(String text,
                                      User currentUser)

escapeCDATA

public static String escapeCDATA(String s)

unescapeCDATA

public static String unescapeCDATA(String s)

createTempDirectoryInConfluenceTemp

public static File createTempDirectoryInConfluenceTemp(String prefix)

createTempFile

public static File createTempFile(String directory)

unescapeEntities

public static String unescapeEntities(String str)

base64Decode

public static String base64Decode(String s)

base64Encode

public static String base64Encode(String s)

hackSingleQuotes

public static String hackSingleQuotes(String s)
hack to make strings that contain singles compatible with javascript (which also uses single quotes denote strings)

Parameters:
s -

isInLastDays

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.

getRelativeTime

public static String getRelativeTime(Date date)
Returns:
A relative time period, 'X hours, Y minutes ago'

getFormatDateSimple

public static String getFormatDateSimple(Date date)

setCookie

public static javax.servlet.http.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

Parameters:
key -
value -

getCookieValue

public static String getCookieValue(String key)

htmlEncode

public static String htmlEncode(String s)
our own htmlEncode() ripped from the TextUtils class. this version does NOT escape ugly characters (read their comments)

Parameters:
s -

isGlobalAdministrator

public static boolean isGlobalAdministrator(Object notUsedAnyMore,
                                            User user)
Deprecated. since 2.0 use PermissionManager directly, or use the $permissionHelper from velocity


plain2html

public static String plain2html(String text)
The function converts plain text into html in two steps. 1. utilize the oscore plain2html function to turn the plain text into html including converting linebreaks and special characters. 2. finds occurences of multiple spaces and replaces them with   html entities.

Parameters:
text -
Returns:
String converted to html

getProperties

public static Properties getProperties(String resource,
                                       Class callingClass)
Deprecated. since 2.3 use PropertyUtils.getProperties(String, Class) instead


getPropertiesFromFile

public static Properties getPropertiesFromFile(File file)
Deprecated. since 2.3 use PropertyUtils.getProperties(String, Class) instead


getPropertiesFromStream

public static Properties getPropertiesFromStream(InputStream is)
Deprecated. since 2.3 use PropertyUtils.getProperties(String, Class) instead


unzipFile

public static void unzipFile(File zipFile,
                             File dirToExtractTo)
                      throws Exception
Unzips the zip file to a folder in temp and returns the File pointing to that expanded folder.

Throws:
Exception

unzipUrl

public static void unzipUrl(URL zipUrl,
                            File dirToExtractTo)
                     throws Exception
Unzips the zip url to a folder in temp and returns the File pointing to that expanded folder.

Throws:
Exception

getUploadFileTooLargeMessage

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

Parameters:
errorMessage -

getDefaultResourceBundle

public static ResourceBundle getDefaultResourceBundle()

getI18n

public static I18NBean getI18n()

arraySize

public int arraySize(int[] array)
convenience method to allow us to determine the size of an int array a velocity file

Parameters:
array -

escapeXMLCharacters

public static String escapeXMLCharacters(String input)
Take a String which may contain <, > or & and return an XML string containing entities


htmlEscapeQuotes

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


filterNulls

public static List filterNulls(Collection in)
Return a List with no null entries


shortenString

public static String shortenString(String str,
                                   int max)

specialToLowerCase

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.

Parameters:
str -

replaceConfluenceHomeConstant

public static String replaceConfluenceHomeConstant(String in,
                                                   String confHome)

specialLowerCaseCollection

public static Collection specialLowerCaseCollection(Collection collection)
Takes a collection of Strings and lowercases the entries.

Parameters:
collection -
Returns:
lowercased collection of strings

safeSubList

public static List safeSubList(List list,
                               int max)

summarise

public static String summarise(String content)
Deprecated. since 2.0 use RendererUtil.summarise(String) instead.


makeSummary

public static Summary makeSummary(String content)
Create a proper summary of this content fragment.

See Also:
Summarizer

makeSummary

public static Summary makeSummary(String content,
                                  String query)
Create a proper summary of this content fragment given a query

See Also:
Summarizer

getUserAccessor

public static UserAccessor getUserAccessor()

setUserAccessor

public static void setUserAccessor(UserAccessor userAcc)

getImageInfo

public static ImageInfo getImageInfo(File pathToImage)

getNiceDuration

public static String getNiceDuration(int minutes,
                                     int seconds)

newWiredConfluenceActionSupport

public static ConfluenceActionSupport newWiredConfluenceActionSupport()

profilePush

public static void profilePush(String s)

profilePop

public static void profilePop(String s)

lookupDomainName

public static String lookupDomainName(javax.servlet.http.HttpServletRequest request)
Get the default domain name.

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

getGlobalSettings

public static Settings getGlobalSettings()

personalSpaceUrl

public static String personalSpaceUrl(String contextPath,
                                      String username)

getDefaultFontFamily

public static String getDefaultFontFamily()
Returns:
returns the name of either the installed font or default font

getPercentage

public long getPercentage(long numerator,
                          long denom)
converts a fraction into a percentage

Parameters:
numerator -
denom -

subtract

public long subtract(long a,
                     long b)

getPercentage

public long getPercentage(String numeratorAsString,
                          String denomAsString)

subtract

public long subtract(String firstOperandAsString,
                     String secondOperandAsString)

getConfluenceTempDirectoryPath

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

getConfluenceTempDirectory

public static File getConfluenceTempDirectory()

splitCommaDelimitedString

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

escapeCommas

public static List escapeCommas(List toEscape)
Escape commas on each entry in the given list of strings.

Parameters:
toEscape - Strings to escape
Returns:
escaped Strings

escapeCommas

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.


Confluence is developed by Atlassian.