hudson
Class Util

java.lang.Object
  extended by hudson.Util

public class Util
extends Object

Various utility methods that don't have more proper home.

Author:
Kohsuke Kawaguchi

Field Summary
static boolean NO_SYMLINK
          On Unix environment that cannot run "ln", set this to true.
static org.apache.commons.lang.time.FastDateFormat RFC822_DATETIME_FORMATTER
           
static boolean SYMLINK_ESCAPEHATCH
           
static org.apache.commons.lang.time.FastDateFormat XS_DATETIME_FORMATTER
           
 
Constructor Summary
Util()
           
 
Method Summary
static File changeExtension(File dst, String ext)
          Returns a file name by changing its extension.
static String combine(long n, String suffix)
          Deprecated. Use individual localization methods instead. See Messages.Util_year(Object) for an example. Deprecated since 2009-06-24, remove method after 2009-12-24.
static void copyFile(File src, File dst)
          Copies a single file by using Ant.
static void copyStream(InputStream in, OutputStream out)
           
static void copyStream(Reader in, Writer out)
           
static void copyStreamAndClose(InputStream in, OutputStream out)
           
static void copyStreamAndClose(Reader in, Writer out)
           
static org.apache.tools.ant.types.FileSet createFileSet(File baseDir, String includes)
           
static org.apache.tools.ant.types.FileSet createFileSet(File baseDir, String includes, String excludes)
          Creates Ant FileSet with the base dir and include pattern.
static
<T> List<T>
createSubList(Collection<?> source, Class<T> type)
          Create a sub-list by only picking up instances of the specified type.
static void createSymlink(File baseDir, String targetPath, String symlinkPath, TaskListener listener)
          Creates a symlink to targetPath at baseDir+symlinkPath.
static File createTempDir()
          Creates a new temporary directory.
static void deleteContentsRecursive(File file)
          Deletes the contents of the given directory (but not the directory itself) recursively.
static void deleteFile(File f)
          Deletes this file (and does not take no for an answer).
static void deleteRecursive(File dir)
           
static void displayIOException(IOException e, TaskListener listener)
          On Windows, error messages for IOException aren't very helpful.
static String encode(String s)
          Escapes non-ASCII characters in URL.
static String encodeRFC2396(String url)
          Deprecated. since 2008-05-13. This method is broken (see ISSUE#1666). It should probably be removed but I'm not sure if it is considered part of the public API that needs to be maintained for backwards compatibility. Use encode(String) instead.
static String ensureEndsWith(String subject, String suffix)
          Ensure string ends with suffix
static String escape(String text)
          Escapes HTML unsafe characters like <, & to the respective character entities.
static
<T> List<T>
filter(Iterable<?> base, Class<T> type)
          Creates a filtered sublist.
static
<T> List<T>
filter(List<?> base, Class<T> type)
          Creates a filtered sublist.
static String fixEmpty(String s)
          Convert empty string to null.
static String fixEmptyAndTrim(String s)
          Convert empty string to null, and trim whitespace.
static
<T> Collection<T>
fixNull(Collection<T> l)
           
static
<T> Iterable<T>
fixNull(Iterable<T> l)
           
static
<T> List<T>
fixNull(List<T> l)
           
static
<T> Set<T>
fixNull(Set<T> l)
           
static String fixNull(String s)
          Convert null to "".
static byte[] fromHexString(String data)
           
static String getDigestOf(InputStream source)
          Computes MD5 digest of the given input stream.
static String getDigestOf(String text)
           
static String getFileName(String filePath)
          Cuts all the leading path portion and get just the file name.
static String getHostName()
          Guesses the current host name.
static String getPastTimeString(long duration)
          Get a human readable string representing strings like "xxx days ago", which should be used to point to the occurrence of an event in the past.
static String getTimeSpanString(long duration)
          Returns a human readable text of the time duration, for example "3 minutes 40 seconds".
static String getWin32ErrorMessage(int n)
          Gets a human readable message for the given Win32 error code.
static String getWin32ErrorMessage(IOException e)
           
static String getWin32ErrorMessage(Throwable e)
          Extracts the Win32 error message from Throwable if possible.
static String intern(String s)
          Null-safe String intern method.
static boolean isAbsoluteUri(String uri)
          Return true if the systemId denotes an absolute URI .
static boolean isOverridden(Class base, Class derived, String methodName, Class... types)
          Checks if the public method defined on the base type with the given arguments are overridden in the given derived type.
static boolean isSymlink(File file)
          Checks if the given file represents a symlink.
static String join(Collection<?> strings, String separator)
          Concatenate multiple strings by inserting a separator.
static
<T> List<T>
join(Collection<? extends T>... items)
          Combines all the given collections into a single list.
static String loadFile(File logfile)
          Loads the contents of a file into a string.
static String loadFile(File logfile, Charset charset)
           
static Properties loadProperties(String properties)
          Loads a key/value pair string as Properties
static String[] mapToEnv(Map<String,String> m)
          Converts the map format of the environment variables to the K=V format in the array.
static int min(int x, int... values)
           
static String nullify(String v)
           
static String rawEncode(String s)
          Encode a single path component for use in an HTTP URL.
static String removeTrailingSlash(String s)
           
static String replaceMacro(String s, Map<String,String> properties)
          Replaces the occurrence of '$key' by properties.get('key').
static String replaceMacro(String s, VariableResolver<String> resolver)
          Replaces the occurrence of '$key' by resolver.get('key').
static String resolveSymlink(File link)
          Resolves symlink, if the given file is a symlink.
static String resolveSymlink(File link, TaskListener listener)
          Deprecated. as of 1.456 Use resolveSymlink(File)
static File resolveSymlinkToFile(File link)
          Resolves a symlink to the File that points to.
static String singleQuote(String s)
          Surrounds by a single-quote.
static SecretKey toAes128Key(String s)
          Converts a string into 128-bit AES key.
static String toHexString(byte[] bytes)
           
static String toHexString(byte[] data, int start, int len)
           
static String[] tokenize(String s)
           
static String[] tokenize(String s, String delimiter)
          Tokenizes the text separated by delimiters.
static void touch(File file)
          Creates an empty file.
static Number tryParseNumber(String numberStr, Number defaultNumber)
          Returns the parsed string if parsed successful; otherwise returns the default number.
static String wrapToErrorSpan(String s)
          Wraps with the error icon and the CSS class to render error message.
static String xmlEscape(String text)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

XS_DATETIME_FORMATTER

public static final org.apache.commons.lang.time.FastDateFormat XS_DATETIME_FORMATTER

RFC822_DATETIME_FORMATTER

public static final org.apache.commons.lang.time.FastDateFormat RFC822_DATETIME_FORMATTER

NO_SYMLINK

public static boolean NO_SYMLINK
On Unix environment that cannot run "ln", set this to true.


SYMLINK_ESCAPEHATCH

public static boolean SYMLINK_ESCAPEHATCH
Constructor Detail

Util

public Util()
Method Detail

filter

public static <T> List<T> filter(Iterable<?> base,
                                 Class<T> type)
Creates a filtered sublist.

Since:
1.176

filter

public static <T> List<T> filter(List<?> base,
                                 Class<T> type)
Creates a filtered sublist.


replaceMacro

public static String replaceMacro(String s,
                                  Map<String,String> properties)
Replaces the occurrence of '$key' by properties.get('key').

Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.)


replaceMacro

public static String replaceMacro(String s,
                                  VariableResolver<String> resolver)
Replaces the occurrence of '$key' by resolver.get('key').

Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.)


loadFile

public static String loadFile(File logfile)
                       throws IOException
Loads the contents of a file into a string.

Throws:
IOException

loadFile

public static String loadFile(File logfile,
                              Charset charset)
                       throws IOException
Throws:
IOException

deleteContentsRecursive

public static void deleteContentsRecursive(File file)
                                    throws IOException
Deletes the contents of the given directory (but not the directory itself) recursively.

Throws:
IOException - if the operation fails.

deleteFile

public static void deleteFile(File f)
                       throws IOException
Deletes this file (and does not take no for an answer).

Parameters:
f - a file to delete
Throws:
IOException - if it exists but could not be successfully deleted

deleteRecursive

public static void deleteRecursive(File dir)
                            throws IOException
Throws:
IOException

isSymlink

public static boolean isSymlink(File file)
                         throws IOException
Checks if the given file represents a symlink.

Throws:
IOException

createTempDir

public static File createTempDir()
                          throws IOException
Creates a new temporary directory.

Throws:
IOException

displayIOException

public static void displayIOException(IOException e,
                                      TaskListener listener)
On Windows, error messages for IOException aren't very helpful. This method generates additional user-friendly error message to the listener


getWin32ErrorMessage

public static String getWin32ErrorMessage(IOException e)

getWin32ErrorMessage

public static String getWin32ErrorMessage(Throwable e)
Extracts the Win32 error message from Throwable if possible.

Returns:
null if there seems to be no error code or if the platform is not Win32.

getWin32ErrorMessage

public static String getWin32ErrorMessage(int n)
Gets a human readable message for the given Win32 error code.

Returns:
null if no such message is available.

getHostName

public static String getHostName()
Guesses the current host name.


copyStream

public static void copyStream(InputStream in,
                              OutputStream out)
                       throws IOException
Throws:
IOException

copyStream

public static void copyStream(Reader in,
                              Writer out)
                       throws IOException
Throws:
IOException

copyStreamAndClose

public static void copyStreamAndClose(InputStream in,
                                      OutputStream out)
                               throws IOException
Throws:
IOException

copyStreamAndClose

public static void copyStreamAndClose(Reader in,
                                      Writer out)
                               throws IOException
Throws:
IOException

tokenize

public static String[] tokenize(String s,
                                String delimiter)
Tokenizes the text separated by delimiters.

In 1.210, this method was changed to handle quotes like Unix shell does. Before that, this method just used StringTokenizer.

Since:
1.145
See Also:
QuotedStringTokenizer

tokenize

public static String[] tokenize(String s)

mapToEnv

public static String[] mapToEnv(Map<String,String> m)
Converts the map format of the environment variables to the K=V format in the array.


min

public static int min(int x,
                      int... values)

nullify

public static String nullify(String v)

removeTrailingSlash

public static String removeTrailingSlash(String s)

ensureEndsWith

public static String ensureEndsWith(String subject,
                                    String suffix)
Ensure string ends with suffix

Parameters:
subject - Examined string
suffix - Desired suffix
Returns:
Original subject in case it already ends with suffix, null in case subject was null and subject + suffix otherwise.
Since:
1.505

getDigestOf

public static String getDigestOf(InputStream source)
                          throws IOException
Computes MD5 digest of the given input stream.

Parameters:
source - The stream will be closed by this method at the end of this method.
Returns:
32-char wide string
Throws:
IOException

getDigestOf

public static String getDigestOf(String text)

toAes128Key

public static SecretKey toAes128Key(String s)
Converts a string into 128-bit AES key.

Since:
1.308

toHexString

public static String toHexString(byte[] data,
                                 int start,
                                 int len)

toHexString

public static String toHexString(byte[] bytes)

fromHexString

public static byte[] fromHexString(String data)

getTimeSpanString

public static String getTimeSpanString(long duration)
Returns a human readable text of the time duration, for example "3 minutes 40 seconds". This version should be used for representing a duration of some activity (like build)

Parameters:
duration - number of milliseconds.

getPastTimeString

public static String getPastTimeString(long duration)
Get a human readable string representing strings like "xxx days ago", which should be used to point to the occurrence of an event in the past.


combine

public static String combine(long n,
                             String suffix)
Deprecated. Use individual localization methods instead. See Messages.Util_year(Object) for an example. Deprecated since 2009-06-24, remove method after 2009-12-24.

Combines number and unit, with a plural suffix if needed.


createSubList

public static <T> List<T> createSubList(Collection<?> source,
                                        Class<T> type)
Create a sub-list by only picking up instances of the specified type.


encode

public static String encode(String s)
Escapes non-ASCII characters in URL.

Note that this methods only escapes non-ASCII but leaves other URL-unsafe characters, such as '#'. rawEncode(String) should generally be used instead, though be careful to pass only a single path component to that method (it will encode /, but this method does not).


rawEncode

public static String rawEncode(String s)
Encode a single path component for use in an HTTP URL. Escapes all non-ASCII, general unsafe (space and "#%<>[\]^`{|}~) and HTTP special characters (/;:?) as specified in RFC1738. (so alphanumeric and !@$&*()-_=+',. are not encoded) Note that slash (/) is encoded, so the given string should be a single path component used in constructing a URL. Method name inspired by PHP's rawurlencode.


singleQuote

public static String singleQuote(String s)
Surrounds by a single-quote.


escape

public static String escape(String text)
Escapes HTML unsafe characters like <, & to the respective character entities.


xmlEscape

public static String xmlEscape(String text)

touch

public static void touch(File file)
                  throws IOException
Creates an empty file.

Throws:
IOException

copyFile

public static void copyFile(File src,
                            File dst)
                     throws org.apache.tools.ant.BuildException
Copies a single file by using Ant.

Throws:
org.apache.tools.ant.BuildException

fixNull

public static String fixNull(String s)
Convert null to "".


fixEmpty

public static String fixEmpty(String s)
Convert empty string to null.


fixEmptyAndTrim

public static String fixEmptyAndTrim(String s)
Convert empty string to null, and trim whitespace.

Since:
1.154

fixNull

public static <T> List<T> fixNull(List<T> l)

fixNull

public static <T> Set<T> fixNull(Set<T> l)

fixNull

public static <T> Collection<T> fixNull(Collection<T> l)

fixNull

public static <T> Iterable<T> fixNull(Iterable<T> l)

getFileName

public static String getFileName(String filePath)
Cuts all the leading path portion and get just the file name.


join

public static String join(Collection<?> strings,
                          String separator)
Concatenate multiple strings by inserting a separator.


join

public static <T> List<T> join(Collection<? extends T>... items)
Combines all the given collections into a single list.


createFileSet

public static org.apache.tools.ant.types.FileSet createFileSet(File baseDir,
                                                               String includes,
                                                               String excludes)
Creates Ant FileSet with the base dir and include pattern.

The difference with this and using AbstractFileSet.setIncludes(String) is that this method doesn't treat whitespace as a pattern separator, which makes it impossible to use space in the file path.

Parameters:
includes - String like "foo/bar/*.xml" Multiple patterns can be separated by ',', and whitespace can surround ',' (so that you can write "abc, def" and "abc,def" to mean the same thing.
excludes - Exclusion pattern. Follows the same format as the 'includes' parameter. Can be null.
Since:
1.172

createFileSet

public static org.apache.tools.ant.types.FileSet createFileSet(File baseDir,
                                                               String includes)

createSymlink

public static void createSymlink(File baseDir,
                                 String targetPath,
                                 String symlinkPath,
                                 TaskListener listener)
                          throws InterruptedException
Creates a symlink to targetPath at baseDir+symlinkPath.

If there's a prior symlink at baseDir+symlinkPath, it will be overwritten.

Parameters:
baseDir - Base directory to resolve the 'symlinkPath' parameter.
targetPath - The file that the symlink should point to. Usually relative to the directory of the symlink but may instead be an absolute path.
symlinkPath - Where to create a symlink in (relative to baseDir)
Throws:
InterruptedException

resolveSymlink

public static String resolveSymlink(File link,
                                    TaskListener listener)
                             throws InterruptedException,
                                    IOException
Deprecated. as of 1.456 Use resolveSymlink(File)

Throws:
InterruptedException
IOException

resolveSymlinkToFile

public static File resolveSymlinkToFile(File link)
                                 throws InterruptedException,
                                        IOException
Resolves a symlink to the File that points to.

Returns:
null if the specified file is not a symlink.
Throws:
InterruptedException
IOException

resolveSymlink

public static String resolveSymlink(File link)
                             throws InterruptedException,
                                    IOException
Resolves symlink, if the given file is a symlink. Otherwise return null.

If the resolution fails, report an error.

Returns:
null if the given file is not a symlink. If the symlink is absolute, the returned string is an absolute path. If the symlink is relative, the returned string is that relative representation. The relative path is meant to be resolved from the location of the symlink.
Throws:
InterruptedException
IOException

encodeRFC2396

@Deprecated
public static String encodeRFC2396(String url)
Deprecated. since 2008-05-13. This method is broken (see ISSUE#1666). It should probably be removed but I'm not sure if it is considered part of the public API that needs to be maintained for backwards compatibility. Use encode(String) instead.

Encodes the URL by RFC 2396. I thought there's another spec that refers to UTF-8 as the encoding, but don't remember it right now.

Since:
1.204

wrapToErrorSpan

public static String wrapToErrorSpan(String s)
Wraps with the error icon and the CSS class to render error message.

Since:
1.173

tryParseNumber

public static Number tryParseNumber(String numberStr,
                                    Number defaultNumber)
Returns the parsed string if parsed successful; otherwise returns the default number. If the string is null, empty or a ParseException is thrown then the defaultNumber is returned.

Parameters:
numberStr - string to parse
defaultNumber - number to return if the string can not be parsed
Returns:
returns the parsed string; otherwise the default number

isOverridden

public static boolean isOverridden(Class base,
                                   Class derived,
                                   String methodName,
                                   Class... types)
Checks if the public method defined on the base type with the given arguments are overridden in the given derived type.


changeExtension

public static File changeExtension(File dst,
                                   String ext)
Returns a file name by changing its extension.

Parameters:
ext - For example, ".zip"

intern

public static String intern(String s)
Null-safe String intern method.


isAbsoluteUri

public static boolean isAbsoluteUri(String uri)
Return true if the systemId denotes an absolute URI . The same algorithm can be seen in URI, but implementing this by ourselves allow it to be more lenient about escaping of URI.


loadProperties

@IgnoreJRERequirement
public static Properties loadProperties(String properties)
                                 throws IOException
Loads a key/value pair string as Properties

Throws:
IOException
Since:
1.392


Copyright © 2004-2013. All Rights Reserved.