Class SafeGeneralUtil

  • Direct Known Subclasses:
    GeneralUtil

    public class SafeGeneralUtil
    extends Object
    Utility class for use in Velocity templates. Do NOT add any methods which mutate their input, application state, or returns an object which can. Such methods should be added to GeneralUtil instead.
    Since:
    8.5.5
    • Field Detail

      • systemStartupTime

        protected static Long systemStartupTime
    • Constructor Detail

      • SafeGeneralUtil

        protected SafeGeneralUtil()
    • Method Detail

      • convertToCharacter

        @Deprecated
        public static Character convertToCharacter​(Object obj)
        Deprecated.
        since 7.3.0, no replacement
      • convertToInteger

        public static Integer convertToInteger​(Object obj)
      • convertToBoolean

        @Deprecated
        public static @Nullable Boolean convertToBoolean​(Object obj)
        Deprecated.
        since 7.3.0, no replacement
      • convertToBoolean

        @Deprecated
        public static boolean convertToBoolean​(Object bool,
                                               boolean defaultValue)
        Deprecated.
        since 7.3.0, no replacement
      • convertToString

        @Deprecated
        public static String convertToString​(Object obj)
        Deprecated.
        since 7.3.0, no replacement
      • getOriginalUrl

        public static String getOriginalUrl​(javax.servlet.http.HttpServletRequest request)
      • completeUrlEncode

        @Deprecated
        public static String completeUrlEncode​(String url)
        Deprecated.
        since 6.10.0 Use HtmlUtil.completeUrlEncode(String) instead.
        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
      • urlEncode

        @Deprecated
        public static String urlEncode​(String url)
        Deprecated.
        since 6.10.0 Use HtmlUtil.urlEncode(String) instead.
        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
      • getIdBasedPageUrl

        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
      • getEditPageUrl

        public static String getEditPageUrl​(AbstractPage page)
        Get a resume draft URL that includes the shareDraftid
        Parameters:
        page - the page to generate an edit url for
        Returns:
        The edit URL for that page
        Since:
        6.1
      • getAttachmentUrl

        public static String getAttachmentUrl​(Attachment attachment)
        Get the permalink URL to preview the given attachment in the previewer.
        Parameters:
        attachment - the attachment to generate an URL for.
        Returns:
        permalink URL for the attachment.
      • getCommentUrl

        public static String getCommentUrl​(Attachment attachment,
                                           Comment comment)
        Get the permalink URL to preview the given comment (annotation) in the previewer.
        Parameters:
        attachment - the attachment that the annotation is on.
        comment - the annotation to generate the url for.
        Returns:
        permalink URL for the annotation.
      • getParentPageOrBlog

        public static @Nullable AbstractPage getParentPageOrBlog​(Contained content)
        returns the page or blog that the content is attached to, or null if it is not attached to a page or blog.
        Parameters:
        content - content to check for containing page or blog.
        Returns:
        container page or blog.
      • getParentComment

        public static Comment getParentComment​(Comment comment)
        Returns the top-level comment that the comment is attached to
        Parameters:
        comment - comment to check for parent comment
        Returns:
        top-level parent comment
      • isSafeTitleForUrl

        @Deprecated(forRemoval=true)
        public static boolean isSafeTitleForUrl​(String title)
        Deprecated, for removal: This API element is subject to removal in a future version.
        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?
        Parameters:
        title - The title to check
        Returns:
        True of the title can be put in a URL, false otherwise
      • isSafeTitleForFilesystem

        @Deprecated(forRemoval=true)
        public static boolean isSafeTitleForFilesystem​(String title)
        Deprecated, for removal: This API element is subject to removal in a future version.
        Ensure the title is safe to be written to the file system. See CONF-10741.
        Parameters:
        title - The title to check
        Returns:
        True if the title is safe for the filesystem, false otherwise
      • 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
        Parameters:
        page - The page to get the URL of
        Returns:
        The URL of the page with a trailing ? or &
      • appendAmpersandOrQuestionMark

        @Deprecated(forRemoval=true)
        public static String appendAmpersandOrQuestionMark​(String str)
        Deprecated, for removal: This API element is subject to removal in a future version.
        Appends an ampersand if the given string already contains a question mark, or a question mark otherwise.
        Parameters:
        str - the string to prepare for adding a query param to.
        Returns:
        the given string with a question mark
        Since:
        5.7
      • 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 - the string to wrap
        max - max length of string allowed per line
        Returns:
        The wrapped string
      • doubleUrlEncode

        @Deprecated
        public static String doubleUrlEncode​(String url)
        Deprecated.
        since 6.10.0, No replacement
      • 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()
      • getSystemStartupTime

        public static Long getSystemStartupTime()
      • hasTooManyUsers

        @Deprecated
        public static boolean hasTooManyUsers()
        Deprecated.
        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

        @Deprecated
        public static boolean stringSet​(String str)
        Deprecated.
        since 5.10 Use StringUtils.isNotEmpty(CharSequence)
      • formatLongTime

        public static String formatLongTime​(long time)
      • displayShortUrl

        public static String displayShortUrl​(String url)
      • displayShortUrl

        public static String displayShortUrl​(String url,
                                             int length)
      • toEndOfMonth

        @Deprecated(forRemoval=true)
        public static Date toEndOfMonth​(Calendar postDate,
                                        boolean isSqlServer)
        Deprecated, for removal: This API element is subject to removal in a future version.
        since 8.6
        Takes a Calendar object and returns the very end (last day, hour, minute, second and millisecond) of the month that the Calendar is in. The original Calendar object is left unaltered.
        Parameters:
        postDate - A calendar object
        Returns:
        Date object signifying the very end of the Calendar's month
      • copyDate

        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.
        Parameters:
        original - The source calendar object
        copy - The destination calendar object
      • getCharacterEncoding

        public static String getCharacterEncoding()
      • getDefaultCharset

        public static Charset getDefaultCharset()
      • escapeXml

        public static String escapeXml​(String stringToEscape)
      • cleanQuietly

        @Deprecated(forRemoval=true)
        public static String cleanQuietly​(String stringToClean)
        Deprecated, for removal: This API element is subject to removal in a future version.
        Sanitizes the input by removing unsafe elements or attributes. It will keep the safe tags.

        For example, the input below,

        <div><script>alert(1);</script></div>

        will generate the following output,

        <div></div>
        Parameters:
        stringToClean - - the string might contain unsafe contents.
        Returns:
        the string where the unsafe contents have been removed.
      • escapeForJavascript

        public static String escapeForJavascript​(String s)
        Escapes ', " and \ with a leading \.
        Parameters:
        s - the string to escape
        Returns:
        the escaped string
      • escapeForHtmlAttribute

        @Deprecated
        public static String escapeForHtmlAttribute​(String s)
        Deprecated.
        since 7.3.0, use HtmlUtil.htmlEncode(String) to escape an HTML attribute or StringEscapeUtils.escapeEcmaScript(String) to have similar behaviour
        Escapes " and \ with a leading \ so that strings can't break out of double-quoted HTML attributes.
        Parameters:
        s - the string to escape
        Returns:
        the escaped string
      • 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
      • maskEmail

        public static String maskEmail​(String emailAddress,
                                       Settings globalSettings)
        Since:
        7.3.0
      • alwaysMaskEmail

        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
      • findAndMaskEmail

        public static String findAndMaskEmail​(String text,
                                              com.atlassian.user.User currentUser)
      • escapeCDATA

        public static String escapeCDATA​(String s)
      • unescapeCDATA

        public static String unescapeCDATA​(String s)
      • unescapeEntities

        public static String unescapeEntities​(String str)
      • base64Decode

        public static String base64Decode​(String s)
      • base64Encode

        public static String base64Encode​(String s)
      • hackSingleQuotes

        @Deprecated
        public static String hackSingleQuotes​(String s)
        Deprecated.
        since 7.3.0, use StringEscapeUtils.escapeEcmaScript(String) instead
        hack to make strings that contain singles compatible with javascript (which also uses single quotes denote strings)
        Parameters:
        s - the input string
        Returns:
        the string with ' replaced with ' + '\\'' + '
      • 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)
        Deprecated.
        since 2.7 use FriendlyDateFormatter
        Parameters:
        date - the date to convert to a relative time string
        Returns:
        A relative time period, 'X hours, Y minutes ago'
      • getFormatDateSimple

        public static String getFormatDateSimple​(Date date)
      • getDefaultResourceBundle

        public static ResourceBundle getDefaultResourceBundle()
      • getI18n

        public static I18NBean getI18n()
        Returns:
        The I18NBean for the current user
      • arraySize

        @Deprecated
        public static int arraySize​(int[] array)
        Deprecated.
        since 7.3.0, no replacement
        convenience method to allow us to determine the size of an int array a velocity file
        Parameters:
        array - the array to find the length of
        Returns:
        the length of the array
      • escapeXMLCharacters

        @Deprecated
        public static @Nullable String escapeXMLCharacters​(@Nullable String input)
        Deprecated.
        since 7.3.0, use escapeXml(String)
        Take a String which may contain <, > or & and return an XML string containing entities.
        Parameters:
        input - a string to escape for XML
        Returns:
        the string with XML entities escaped
      • replaceInvalidXmlCharacters

        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 Verifier.checkCharacterData(String) but converts illegals instead of throwing Exceptions.

        Parameters:
        text - the input string
        Returns:
        the input string with those characters converted to Unicode "Replacement Character"s
      • htmlEscapeQuotes

        @Deprecated
        public static String htmlEscapeQuotes​(String input)
        Deprecated.
        since 7.3.0, use StringEscapeUtils.escapeEcmaScript(String) combined with HtmlUtil.htmlEncode(String) or template-level automatic escaping
        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.

        Parameters:
        input - string to escape
        Returns:
        the escaped string
      • filterNulls

        @Deprecated
        public static <T> List<T> filterNulls​(Collection<T> in)
        Deprecated.
        since 7.3.0, no replacement, use Java's stream api
        Return a List with no null entries
        Parameters:
        in - a collection to filter nulls
        Returns:
        a list that is a copy of the collection with nulls removed
      • shortenString

        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 ELLIPSIS to the end of the string if it does truncate it.
        Parameters:
        str - the string to shorten
        max - the maximum desired length of the result (excluding ELLIPSIS)
        Returns:
        a substring of the specified string if it is longer than max.
        See Also:
        StringUtils.abbreviate(String, int)
      • 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 - the string to convert to lower case
        Returns:
        the lower cased string
      • specialLowerCaseCollection

        @Deprecated
        public static Collection<String> specialLowerCaseCollection​(Collection<String> collection)
        Deprecated.
        since 7.3.0, no replacement, use java stream api in combination with specialToLowerCase(String)
        Takes a collection of Strings and lowercases the entries.
        Parameters:
        collection - the collection
        Returns:
        lowercased collection of strings
      • safeSubList

        public static <T> List<T> safeSubList​(List<T> list,
                                              int max)
      • summarise

        public static String summarise​(String content)
        Parameters:
        content - the content to summarise
        Returns:
        the summarised content
      • makeSummary

        public static Summary makeSummary​(String content)
        Create a proper summary of this content fragment.
        Parameters:
        content - the string to summarise
        Returns:
        the summary object for the string
        See Also:
        Summarizer
      • makeSummary

        public static Summary makeSummary​(String content,
                                          @Nullable String query)
        Create a proper summary of this content fragment given a query
        Parameters:
        content - the string to summarise
        query - the lucene query
        Returns:
        the summary object for the content and query
        See Also:
        Summarizer
      • makeFlatSummary

        public static String makeFlatSummary​(String content)
        Create a summary of this content fragment.
        Parameters:
        content - the content to summarise
        Returns:
        the summary as a string
        See Also:
        Summarizer
      • makeFlatSummary

        public static String makeFlatSummary​(String content,
                                             @Nullable String query)
        Create a summary of this content fragment given a query
        Parameters:
        content - the content string
        query - the lucene query string
        Returns:
        the summarised content and query
        See Also:
        Summarizer
      • getImageInfo

        public static com.atlassian.core.util.ImageInfo getImageInfo​(File pathToImage)
      • getNiceDuration

        public static String getNiceDuration​(int minutes,
                                             int seconds)
      • getCompactDuration

        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.
      • lookupDomainName

        public static String lookupDomainName​(javax.servlet.http.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.
      • getGlobalSettings

        public static Settings getGlobalSettings()
      • getPercentage

        public static long getPercentage​(long numerator,
                                         long denom)
        converts a fraction into a percentage
        Parameters:
        numerator - the number to include in the percentage
        denom - the total number
        Returns:
        the percentage as a long integer, rounded
      • getPercentage

        public static long getPercentage​(String numeratorAsString,
                                         String denomAsString)
      • splitCommaDelimitedString

        public static String[] splitCommaDelimitedString​(String escapedNames)
        Method will turn a String of comma separated 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

        @Deprecated
        public static List<String> escapeCommas​(List<String> toEscape)
        Deprecated.
        since 7.3.0, no replacement, use java stream api in combination with escapeCommas(String)
        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.
        Returns:
        the escaped string
      • constrainLength

        @Deprecated
        public static String constrainLength​(String s,
                                             int length)
        Deprecated.
        since 7.3.0, use StringUtils.truncate(String, int) instead
        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.
      • convertBeanToMap

        @Deprecated(forRemoval=true)
        public static Map<String,​String> convertBeanToMap​(Object bean)
        Deprecated, for removal: This API element is subject to removal in a future version.
        since 8.6 use BeanUtils.describe(Object)
        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.
      • prefixAllMapKeys

        public static <K,​V> Map<K,​V> prefixAllMapKeys​(String prefix,
                                                                  Map<K,​V> 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.
      • rdfEncode

        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 --
      • populateSimpleMessage

        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.
      • getRandomSubSet

        public static <T> 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
      • trimDownStringToWord

        public static String trimDownStringToWord​(String s)
      • isDateWithin24Hours

        public static boolean isDateWithin24Hours​(Date date)
        Determines if given date is within 24 hours
        Parameters:
        date -
        Returns:
      • refineOsDestination

        public static String refineOsDestination​(String osDestination)
        Escape XML and replace all space with %20
        Parameters:
        osDestination -
        Returns:
      • removeEmailsFromString

        public static String removeEmailsFromString​(String text)
        Remove all emails from text
        Parameters:
        text -
        Returns:
      • getServerRenderTime

        public static Duration getServerRenderTime​(javax.servlet.ServletRequest servletRequest)
        Calculates the duration of the request
        Since:
        5.9.0
      • getRequestCorrelationId

        public static String getRequestCorrelationId()
        Returns request correlation id
        Since:
        5.9.0
      • flushResponse

        public static void flushResponse()
        Flushes response writer. Logs error if exception occurs.
        Since:
        5.9.1
      • elapse

        public static void elapse​(String tag)
        Add elapsed time to HttpRequestStats
        Since:
        5.9.1
        See Also:
        HttpRequestStats
      • applyIfNonNull

        public static <T> T applyIfNonNull​(T delegate,
                                           Function<T,​T> wrapper)
      • sortList

        public static List<String> sortList​(List<String> list)
        Sorts a list of strings alphabetically in ascending order without the mutating original list.
        Parameters:
        list - a list of strings
        Returns:
        the list sorted alphabetically
      • profilePush

        @Deprecated
        public static void profilePush​(String s)
        Deprecated.
        since 7.0. Use Timers.start(String).
        Parameters:
        s - the profiling frame name to push
      • profilePop

        @Deprecated
        public static void profilePop​(String s)
        Deprecated.
        since 7.0. Use Timers.start(String) and a try-finally block.
        Parameters:
        s - the profiling frame name to pop