Package hudson

Class Functions

  • public class Functions
    extends Object
    Utility functions used in views.

    An instance of this class is created for each request and made accessible from view pages via the variable 'h' (h stands for Hudson.)

    Kohsuke Kawaguchi
    • Field Detail

      • DEBUG_YUI

        public static boolean DEBUG_YUI
        Set to true if you need to use the debug version of YUI.
    • Constructor Detail

      • Functions

        public Functions()
    • Method Detail

      • generateId

        public String generateId()
        Generates an unique ID.
      • isModel

        public static boolean isModel​(Object o)
      • isModelWithContextMenu

        public static boolean isModelWithContextMenu​(Object o)
      • isModelWithChildren

        public static boolean isModelWithChildren​(Object o)
      • isMatrixProject

        public static boolean isMatrixProject​(Object o)
      • iso8601DateTime

        public static String iso8601DateTime​(Date date)
      • localDate

        public static String localDate​(Date date)
        Returns a localized string for the specified date, not including time.
      • getTimeSpanString

        public static String getTimeSpanString​(Date date)
        Returns a human-readable string describing the time difference between now and the specified date.
      • isExtensionsAvailable

        public static boolean isExtensionsAvailable()
        During Jenkins start-up, before InitMilestone.PLUGINS_STARTED the extensions lists will be empty and they are not guaranteed to be fully populated until after InitMilestone.EXTENSIONS_AUGMENTED, similarly, during termination after Jenkins.isTerminating() is set, it is no longer safe to access the extensions lists. If you attempt to access the extensions list from a UI thread while the extensions are being loaded you will hit a big honking great monitor lock that will block until the effective extension list has been determined (as if a plugin fails to start, all of the failed plugin's extensions and any dependent plugins' extensions will have to be evicted from the list of extensions. In practical terms this only affects the "Jenkins is loading" screen, but as that screen uses the generic layouts we provide this utility method so that the generic layouts can avoid iterating extension lists while Jenkins is starting up. If you attempt to access the extensions list from a UI thread while Jenkins is being shut down, the extensions themselves may no longer be in a valid state and could attempt to revive themselves and block termination. In actual terms the termination only affects those views required to render HudsonIsRestarting's index.jelly which is the same set as the HudsonIsLoading pages so it makes sense to use both checks here.
        true if the extensions lists have been populated.
      • initPageVariables

        public static void initPageVariables​(org.apache.commons.jelly.JellyContext context)
      • getTypeParameter

        public static <B> Class getTypeParameter​(Class<? extends B> c,
                                                 Class<B> base,
                                                 int n)
        Given c=MyList (extends ArrayList<Foo>), base=List, compute the parameterization of 'base' that's assignable from 'c' (in this case List<Foo>), and return its n-th type parameter (n=0 would return Foo).

        This method is useful for doing type arithmetic.

        AssertionError - if c' is not parameterized.
      • getDiffString

        public static String getDiffString​(int i)
        Prints the integer as a string that represents difference, like "-5", "+/-0", "+3".
      • getDiffString2

        public static String getDiffString2​(int i)
        getDiffString(int) that doesn't show anything for +/-0
      • getDiffString2

        public static String getDiffString2​(String prefix,
                                            int i,
                                            String suffix)
        getDiffString2(int) that puts the result into prefix and suffix if there's something to print
      • addSuffix

        public static String addSuffix​(int n,
                                       String singular,
                                       String plural)
        Adds the proper suffix.
      • decompose

        public static Functions.RunUrl decompose​(org.kohsuke.stapler.StaplerRequest req)
      • getScreenResolution

        public static Area getScreenResolution()
        If we know the user's screen resolution, return it. Otherwise null.
      • useHidingPasswordFields

        public static boolean useHidingPasswordFields()
      • getNodeModes

        public static Node.Mode[] getNodeModes()
      • ifThenElse

        public static Object ifThenElse​(boolean cond,
                                        Object thenValue,
                                        Object elseValue)
        as of 1.294 JEXL now supports the real ternary operator "x?y:z", so this work around is no longer necessary.
      • getSystemProperties

        public static Map getSystemProperties()
      • getSystemProperty

        public static String getSystemProperty​(String key)
        Gets the system property indicated by the specified key. Delegates to SystemProperties.getString(String).
      • getEnvVars

        public static Map getEnvVars()
      • isWindows

        public static boolean isWindows()
      • isGlibcSupported

        public static boolean isGlibcSupported()
      • printLogRecordHtml

        public static String[] printLogRecordHtml​(LogRecord r,
                                                  LogRecord prior)
      • reverse

        public static <T> Iterable<T> reverse​(Collection<T> collection)
        Reverses a collection so that it can be easily walked in reverse order.
      • getCookie

        public static javax.servlet.http.Cookie getCookie​(javax.servlet.http.HttpServletRequest req,
                                                          String name)
      • getCookie

        public static String getCookie​(javax.servlet.http.HttpServletRequest req,
                                       String name,
                                       String defaultValue)
      • getYuiSuffix

        public static String getYuiSuffix()
        Gets the suffix to use for YUI JavaScript.
      • filterExcludingFrom

        public static <V> SortedMap<Integer,​V> filterExcludingFrom​(SortedMap<Integer,​V> map,
                                                                         String from,
                                                                         String to)
        Creates a sub map by using the given range (upper end inclusive).
      • configureAutoRefresh

        public static void configureAutoRefresh​(javax.servlet.http.HttpServletRequest request,
                                                javax.servlet.http.HttpServletResponse response,
                                                boolean noAutoRefresh)
        auto refresh has been removed
        No longer used.
      • isAutoRefresh

        public static boolean isAutoRefresh​(javax.servlet.http.HttpServletRequest request)
      • isCollapsed

        public static boolean isCollapsed​(String paneId)
      • isUserTimeZoneOverride

        public static boolean isUserTimeZoneOverride()
      • getUserTimeZone

        public static String getUserTimeZone()
      • getUserTimeZonePostfix

        public static String getUserTimeZonePostfix​(Date date)
      • getHourLocalTimezone

        public static long getHourLocalTimezone()
      • getNearestAncestorUrl

        public static String getNearestAncestorUrl​(org.kohsuke.stapler.StaplerRequest req,
                                                   Object it)
        Finds the given object in the ancestor list and returns its URL. This is used to determine the "current" URL assigned to the given object, so that one can compute relative URLs from it.
      • appendSpaceIfNotNull

        public static String appendSpaceIfNotNull​(String n)
      • nbspIndent

        public static String nbspIndent​(String size)
        One nbsp per 10 pixels in given size, which may be a plain number or "NxN" (like an iconSize). Useful in a sortable table heading.
      • getWin32ErrorMessage

        public static String getWin32ErrorMessage​(IOException e)
      • isMultiline

        public static boolean isMultiline​(String s)
      • encode

        public static String encode​(String s)
        Percent-encodes space and non-ASCII UTF-8 characters for use in URLs.
         Input example  1: !"£$%^&*()_+}{:@~?><|¬`,./;'#[]- =
         Output example 1: !"%C2%A3$%^&*()_+}{:@~?><|%C2%AC`,./;'#[]-%20=
        • a blank space will render as %20
        • this methods only escapes non-ASCII but leaves other URL-unsafe characters, such as '#'
        • Util.rawEncode(String) in the Util library should generally be used instead (do check the documentation for that method)
      • urlEncode

        public static String urlEncode​(String s)
        Shortcut function for calling URLEncoder.encode(String,String) (with UTF-8 encoding).
        Useful for encoding URL query parameters in jelly code (as in "...?param=${h.urlEncode(something)}").
        For convenience in jelly code, it also accepts null parameter, and then returns an empty string.
         Input example  1: & " ' < >
         Output example 1: %26+%22+%27+%3C+%3E
         Input example  2: !"£$%^&*()_+}{:@~?><|¬`,./;'#[]-=
         Output example 2: %21%22%C2%A3%24%25%5E%26*%28%29_%2B%7D%7B%3A%40%7E%3F%3E%3C%7C%C2%AC%60%2C.%2F%3B%27%23%5B%5D-%3D
        Note: A blank space will render as + (You can see this in above examples)
      • escape

        public static String escape​(String s)
        Transforms the input string so it renders as written in HTML output: newlines are converted to HTML line breaks, consecutive spaces are retained as &amp;nbsp;, and HTML metacharacters are escaped.
         Input example  1: & " ' < >
         Output example 1: &amp; &quot; &#039; &lt; &gt;
         Input example  2: !"£$%^&*()_+}{:@~?><|¬`,./;'#[]-=
         Output example 2: !&quot;£$%^&amp;*()_+}{:@~?&gt;&lt;|¬`,./;&#039;#[]-=
        See Also:
        xmlEscape(java.lang.String), Util.escape(java.lang.String)
      • xmlEscape

        public static String xmlEscape​(String s)
        Escapes XML unsafe characters
         Input example  1: < > &
         Output example 1: &lt; &gt; &amp;
         Input example  2: !"£$%^&*()_+}{:@~?><|¬`,./;'#[]-=
         Output example 2: !"£$%^&amp;*()_+}{:@~?&gt;&lt;|¬`,./;'#[]-=
        See Also:
      • xmlUnescape

        public static String xmlUnescape​(String s)
      • htmlAttributeEscape

        public static String htmlAttributeEscape​(String text)
        Escapes a string so it can be used in an HTML attribute value.
         Input example  1: & " ' < >
         Output example 1: &amp; &quot; &#39; &lt; &gt;
         Input example  2: !"£$%^&*()_+}{:@~?><|¬`,./;'#[]-=
         Output example 2: !&quot;£$%^&amp;*()_+}{:@~?&gt;&lt;|¬`,./;&#39;#[]-=
        Note: 2 consecutive blank spaces will not render any special chars.
      • checkPermission

        public static void checkPermission​(Permission permission)
                                    throws IOException,
      • checkPermission

        public static void checkPermission​(Object object,
                                           Permission permission)
                                    throws IOException,
        This version is so that the 'checkPermission' on layout.jelly degrades gracefully if "it" is not an AccessControlled object. Otherwise it will perform no check and that problem is hard to notice.
      • hasPermission

        public static boolean hasPermission​(Permission permission)
                                     throws IOException,
        Returns true if the current user has the given permission.
        permission - If null, returns true. This defaulting is convenient in making the use of this method terse.
      • hasPermission

        public static boolean hasPermission​(Object object,
                                            Permission permission)
                                     throws IOException,
        This version is so that the 'hasPermission' can degrade gracefully if "it" is not an AccessControlled object.
      • adminCheck

        public static void adminCheck​(org.kohsuke.stapler.StaplerRequest req,
                                      org.kohsuke.stapler.StaplerResponse rsp,
                                      Object required,
                                      Permission permission)
                               throws IOException,
      • inferHudsonURL

        public static String inferHudsonURL​(org.kohsuke.stapler.StaplerRequest req)
        Infers the hudson installation URL from the given request.
      • getFooterURL

        public static String getFooterURL()
        Returns the link to be displayed in the footer of the UI.
      • getGlobalNodePropertyDescriptors

        public static List<NodePropertyDescriptor> getGlobalNodePropertyDescriptors()
        Returns those node properties which can be configured as global node properties.
      • getSortedDescriptorsForGlobalConfigByDescriptor

        public static Collection<Descriptor> getSortedDescriptorsForGlobalConfigByDescriptor​(Predicate<Descriptor> predicate)
        Gets all the descriptors sorted by their inheritance tree of Describable so that descriptors of similar types come nearby.

        We sort them by Extension.ordinal() but only for GlobalConfigurations, as the value is normally used to compare similar kinds of extensions, and we needed GlobalConfigurations to be able to position themselves in a layer above. This however creates some asymmetry between regular Descriptors and GlobalConfigurations. Perhaps it is better to introduce another annotation element? But then, extensions shouldn't normally concern themselves about ordering too much, and the only reason we needed this for GlobalConfigurations are for backward compatibility.

        predicate - Filter the descriptors based on this predicate
      • getSortedDescriptorsForGlobalConfigNoSecurity

        public static Collection<Descriptor> getSortedDescriptorsForGlobalConfigNoSecurity()
        This is rather meaningless.
      • getSortedDescriptorsForGlobalConfigUnclassified

        public static Collection<Descriptor> getSortedDescriptorsForGlobalConfigUnclassified()
        Descriptors in the global configuration form that users with Jenkins.MANAGE permission can configure.
      • getSortedDescriptorsForGlobalConfigUnclassifiedReadable

        public static Collection<Descriptor> getSortedDescriptorsForGlobalConfigUnclassifiedReadable()
        Descriptors shown in the global configuration form to users with Jenkins.SYSTEM_READ permission.
      • hasAnyPermission

        public static boolean hasAnyPermission​(AccessControlled ac,
                                               Permission[] permissions)
        Checks if the current security principal has one of the supplied permissions.
      • hasAnyPermission

        public static boolean hasAnyPermission​(Object object,
                                               Permission[] permissions)
                                        throws IOException,
        This version is so that the 'hasAnyPermission' degrades gracefully if "it" is not an AccessControlled object. Otherwise it will perform no check and that problem is hard to notice.
      • checkAnyPermission

        public static void checkAnyPermission​(AccessControlled ac,
                                              Permission[] permissions)
        Checks if the current security principal has one of the supplied permissions.
        Throws: - if the user doesn't have the permission.
      • checkAnyPermission

        public static void checkAnyPermission​(Object object,
                                              Permission[] permissions)
                                       throws IOException,
        This version is so that the 'checkAnyPermission' on layout.jelly degrades gracefully if "it" is not an AccessControlled object. Otherwise it will perform no check and that problem is hard to notice.
      • getIconFilePath

        public static String getIconFilePath​(Action a)
        Computes the path to the icon of the given action from the context path.
      • size2

        public static int size2​(Object o)
                         throws Exception
        Works like JSTL build-in size(x) function, but handle null gracefully.
      • getRelativeLinkTo

        public static String getRelativeLinkTo​(Item p)
        Computes the relative path from the current page to the given item.
      • getRelativeNameFrom

        public static String getRelativeNameFrom​(@CheckForNull
                                                 Item p,
                                                 ItemGroup g,
                                                 boolean useDisplayName)
        Gets the relative name or display name to the given item from the specified group.
        p - the Item we want the relative display name. If null, a null will be returned by the method
        g - the ItemGroup used as point of reference for the item. If the group is not specified, item's path will be used.
        useDisplayName - if true, returns a display name, otherwise returns a name
        String like "foo » bar". null if item is null or if one of its parents is not an Item.
      • getRelativeNameFrom

        public static String getRelativeNameFrom​(@CheckForNull
                                                 Item p,
                                                 ItemGroup g)
        Gets the name to the given item relative to given group.
        p - the Item we want the relative display name If null, the method will immediately return null.
        g - the ItemGroup used as point of reference for the item
        String like "foo/bar". null if the item is null or if one of its parents is not an Item.
      • getRelativeDisplayNameFrom

        public static String getRelativeDisplayNameFrom​(@CheckForNull
                                                        Item p,
                                                        ItemGroup g)
        Gets the relative display name to the given item from the specified group.
        p - the Item we want the relative display name. If null, the method will immediately return null.
        g - the ItemGroup used as point of reference for the item
        String like "Foo » Bar". null if the item is null or if one of its parents is not an Item.
      • getThreadInfos

        public static ThreadInfo[] getThreadInfos()
      • isMustangOrAbove

        public static boolean isMustangOrAbove()
        Now always true.
      • emptyList

        public static <T> Collection<T> emptyList()
      • jsStringEscape

        public static String jsStringEscape​(String s)
        Escape a string so variable values can be used in inline JavaScript in views. Note that inline JavaScript and especially passing variables is discouraged, see the documentation for alternatives.
         Input example : \ \\ ' "
         Output example: \\ \\\\ \' \"
        See Also:
        Passing values to JavaScript
      • capitalize

        public static String capitalize​(String s)
        Converts "abc" to "Abc".
      • getVersion

        public static String getVersion()
      • getResourcePath

        public static String getResourcePath()
        Resource path prefix.
      • defaultToTrue

        public static boolean defaultToTrue​(Boolean b)
        Can be used to check a checkbox by default. Used from views like h.defaultToTrue(scm.useUpdate). The expression will evaluate to true if scm is null.
      • defaulted

        public static <T> T defaulted​(T value,
                                      T defaultValue)
        If the value exists, return that value. Otherwise return the default value.

        Starting 1.294, JEXL supports the elvis operator "x?:y" that supersedes this.

      • printThrowable

        public static String printThrowable​(@CheckForNull
                                            Throwable t)
        Prints a stack trace from an exception into a readable form. Unlike Throwable.printStackTrace(PrintWriter), this implementation follows the suggestion of JDK-6507809 to produce a linear trace even when Throwable.getCause() is used.
        t - Input Throwable
        If t is not null, generally a multiline string ending in a (platform-specific) newline; otherwise, the method returns a default "No exception details" string.
      • determineRows

        public static int determineRows​(String s)
        Counts the number of rows needed for textarea to fit the content. Minimum 5 rows.
      • toCCStatus

        public static String toCCStatus​(Item i)
        This functionality has been moved to ccxml plugin.
        Converts the Hudson build status to CruiseControl build status, which is either Success, Failure, Exception, or Unknown.
      • isAnonymous

        public static boolean isAnonymous()
        Checks if the current user is anonymous.
      • getCurrentJellyContext

        public static org.apache.commons.jelly.JellyContext getCurrentJellyContext()
        When called from within JEXL expression evaluation, this method returns the current JellyContext used to evaluate the script.
      • runScript

        public static String runScript​(org.apache.commons.jelly.Script script)
                                throws org.apache.commons.jelly.JellyTagException
        Evaluate a Jelly script and return output as a String.
      • subList

        public static <T> List<T> subList​(List<T> base,
                                          int maxSize)
        Returns a sub-list if the given list is bigger than the specified maxSize. Warning: do not call this with a RunList, or you will break lazy loading!
      • joinPath

        public static String joinPath​(String... components)
        Combine path components via '/' while handling leading/trailing '/' to avoid duplicates.
      • getActionUrl

        public static String getActionUrl​(String itUrl,
                                          Action action)
        Computes the hyperlink to actions, to handle the situation when the Action.getUrlName() returns absolute URL.
        null in case the action should not be presented to the user.
      • getConsoleUrl

        public static String getConsoleUrl​(Queue.Executable executable)
        Computes the link to the console for the run for the specified executable, taking ConsoleUrlProvider into account.
        executable - the executable (normally a Run)
        the absolute URL for accessing the build console for the executable, or null if there is no build associated with the executable
      • toEmailSafeString

        public static String toEmailSafeString​(String projectName)
        Escapes the character unsafe for e-mail address. See the Wikipedia page for the details, but here the vocabulary is even more restricted.
      • getServerName

        public String getServerName()
        Obtains the host name of the Hudson server that clients can use to talk back to.

        This was primarily used in jenkins-agent.jnlp.jelly to specify the destination that the agents talk to.

      • calcCheckUrl

        public void calcCheckUrl​(Map attributes,
                                 String userDefined,
                                 Object descriptor,
                                 String field)
        Determines the parameters that client-side needs for a form validation check. See prepareDatabinding.jelly
      • hyperlinkMatchesCurrentPage

        public boolean hyperlinkMatchesCurrentPage​(String href)
        If the given href link is matching the current page, return true. Used in task.jelly to decide if the page should be highlighted.
      • singletonList

        public <T> List<T> singletonList​(T t)
        From JEXL expressions (${…}) in *.jelly files you can use [obj] syntax to construct an Object[] (which may be usable where a List is expected) rather than h.singletonList(obj).
      • prepend

        public String prepend​(String prefix,
                              String body)
        Prepend a prefix only when there's the specified body.
      • getCrumb

        public static String getCrumb​(org.kohsuke.stapler.StaplerRequest req)
      • getCrumbRequestField

        public static String getCrumbRequestField()
      • getCurrentTime

        public static Date getCurrentTime()
      • getCurrentLocale

        public static Locale getCurrentLocale()
      • getLoggerNames

        public List<String> getLoggerNames()
        Work around for bug 6935026.
      • getPasswordValue

        public String getPasswordValue​(Object o)
        Used by <f:password/> so that we send an encrypted value to the client.
      • filterDescriptors

        public List filterDescriptors​(Object context,
                                      Iterable descriptors)
      • getIsUnitTest

        public static boolean getIsUnitTest()
        Returns true if we are running unit tests.
      • isArtifactsPermissionEnabled

        public static boolean isArtifactsPermissionEnabled()
        Returns true if the Run.ARTIFACTS permission is enabled, false otherwise.

        When the Run.ARTIFACTS permission is not turned on using the system property, this permission must not be considered to be set to false for every user. It must rather be like if the permission doesn't exist at all (which means that every user has to have an access to the artifacts but the permission can't be configured in the security screen). Got it?

      • isWipeOutPermissionEnabled

        public static boolean isWipeOutPermissionEnabled()
        Returns true if the Item.WIPEOUT permission is enabled, false otherwise.

        The "Wipe Out Workspace" action available on jobs is controlled by the Item.BUILD permission. For some specific projects, however, it is not acceptable to let users have this possibility, even it they can trigger builds. As such, when enabling the system property, a new "WipeOut" permission will allow to have greater control on the "Wipe Out Workspace" action.

      • createRenderOnDemandProxy

        public static String createRenderOnDemandProxy​(org.apache.commons.jelly.JellyContext context,
                                                       String attributesToCapture)
      • getCurrentDescriptorByNameUrl

        public static String getCurrentDescriptorByNameUrl()
      • setCurrentDescriptorByNameUrl

        public static String setCurrentDescriptorByNameUrl​(String value)
      • restoreCurrentDescriptorByNameUrl

        public static void restoreCurrentDescriptorByNameUrl​(String old)
      • getRequestHeaders

        public static List<String> getRequestHeaders​(String name)
      • rawHtml

        public static Object rawHtml​(Object o)
        Used for arguments to internationalized expressions to avoid escape
      • getAvatar

        public static String getAvatar​(User user,
                                       String avatarSize)
        Returns an avatar image URL for the specified user and preferred image size
        user - the user
        avatarSize - the preferred size of the avatar image
        a URL string
      • humanReadableByteSize

        public static String humanReadableByteSize​(long size)
        Returns human readable information about file size
        size - file size in bytes
        file size in appropriate unit
      • breakableString

        public static String breakableString​(String plain)
        Get a string that can be safely broken to several lines when necessary. This implementation inserts <wbr> tags into string. It allows browsers to wrap line before any sequence of punctuation characters or anywhere in the middle of prolonged sequences of word characters.
      • advertiseHeaders

        public static void advertiseHeaders​(javax.servlet.http.HttpServletResponse rsp)
        Advertises the minimum set of HTTP headers that assist programmatic discovery of Jenkins.
      • isContextMenuVisible

        public static boolean isContextMenuVisible​(Action a)
      • tryGetIcon

        public static Icon tryGetIcon​(String iconGuess)
      • extractPluginNameFromIconSrc

        public static String extractPluginNameFromIconSrc​(String iconSrc)
      • tryGetIconPath

        public static String tryGetIconPath​(String iconGuess,
                                            org.apache.commons.jelly.JellyContext context)
      • generateItemId

        public static String generateItemId()