public class Util extends Object
Modifier and Type | Field and Description |
---|---|
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 and Description |
---|
Util() |
Modifier and Type | Method and Description |
---|---|
static File |
changeExtension(File dst,
String ext)
Returns a file name by changing its extension.
|
static void |
closeAndLogFailures(Closeable toClose,
Logger logger,
String closeableName,
String closeableOwner)
Closes the item and logs error to the log in the case of error.
|
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)
Deprecated.
since 2.335; use
Files.copy(Path, Path, CopyOption...) directly |
static void |
copyStream(InputStream in,
OutputStream out)
Deprecated.
Use
IOUtils.copy(InputStream, OutputStream) |
static void |
copyStream(Reader in,
Writer out)
Deprecated.
Use
IOUtils.copy(Reader, Writer) |
static void |
copyStreamAndClose(InputStream in,
OutputStream out)
Deprecated.
Use
IOUtils.copy(InputStream, OutputStream) in a try -with-resources block |
static void |
copyStreamAndClose(Reader in,
Writer out)
Deprecated.
Use
IOUtils.copy(Reader, Writer) in a try -with-resources block |
static Path |
createDirectories(Path dir,
FileAttribute<?>... attrs)
Create a directory by creating all nonexistent parent directories first.
|
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 long |
daysBetween(Date a,
Date b)
Compute the number of calendar days elapsed since the given date.
|
static long |
daysElapsedSince(Date date) |
static void |
deleteContentsRecursive(File file)
Deletes the contents of the given directory (but not the directory itself)
recursively.
|
static void |
deleteContentsRecursive(Path path,
PathRemover.PathChecker pathChecker)
Deletes the given directory contents (but not the directory itself) recursively using a PathChecker.
|
static void |
deleteFile(File f)
Deletes this file (and does not take no for an answer).
|
static void |
deleteRecursive(File dir)
Deletes the given directory (including its contents) recursively.
|
static void |
deleteRecursive(Path dir,
PathRemover.PathChecker pathChecker)
Deletes the given directory and contents recursively using a filter.
|
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 JENKINS-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 Path |
fileToPath(File file)
|
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 <T> T |
fixNull(T s,
T defaultValue)
Convert
null to a default value. |
static byte[] |
fromHexString(String data) |
static String |
fullEncode(String s)
Encode a single path component for use in an HTTP URL.
|
static String |
getDigestOf(File file)
Computes the MD5 digest of a file.
|
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 <T> T |
getNearestAncestorOfTypeOrThrow(org.kohsuke.stapler.StaplerRequest request,
Class<T> clazz)
Find the specific ancestor, or throw an exception.
|
static String |
getPastTimeString(long duration)
Deprecated.
Actually identical to
getTimeSpanString(long) , does not add ago . |
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 <T> T |
ifOverridden(Supplier<T> supplier,
Class<?> base,
Class<?> derived,
String methodName,
Class<?>... types)
Calls the given supplier if the method defined on the base type with the given arguments is overridden in the
given derived type.
|
static String |
intern(String s)
Null-safe String intern method.
|
static boolean |
isAbsoluteUri(String uri)
Deprecated.
Use
isSafeToRedirectTo(java.lang.String) instead if your goal is to prevent open redirects |
static boolean |
isDescendant(File forParent,
File potentialChild)
A check if a file path is a descendant of a parent path
|
static boolean |
isOverridden(Class<?> base,
Class<?> derived,
String methodName,
Class<?>... types)
Checks whether the method defined on the base type with the given arguments is overridden in the given derived
type.
|
static boolean |
isRelativePath(String path)
A mostly accurate check of whether a path is a relative path or not.
|
static boolean |
isSafeToRedirectTo(String uri)
Return true iff the parameter does not denote an absolute URI and not a scheme-relative URI.
|
static boolean |
isSymlink(File file)
Checks if the given file represents a symlink.
|
static boolean |
isSymlink(Path path) |
static String |
join(Collection<?> strings,
String separator)
Deprecated.
since 2.292; use
String.join(CharSequence, Iterable) |
static <T> List<T> |
join(Collection<? extends T>... items)
Combines all the given collections into a single list.
|
static String |
loadFile(File logfile)
Deprecated.
call
loadFile(java.io.File, java.nio.charset.Charset)
instead to specify the charset to use for decoding (preferably
StandardCharsets.UTF_8 ). |
static String |
loadFile(File logfile,
Charset charset)
Reads the entire contents of the text file at
logfile into a
string using charset for decoding. |
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 Set<PosixFilePermission> |
modeToPermissions(int mode) |
static String |
nullify(String v) |
static int |
permissionsToMode(Set<PosixFilePermission> permissions) |
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 if nonexistent or truncates the existing 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) |
public static final org.apache.commons.lang.time.FastDateFormat XS_DATETIME_FORMATTER
public static final org.apache.commons.lang.time.FastDateFormat RFC822_DATETIME_FORMATTER
public static boolean NO_SYMLINK
public static boolean SYMLINK_ESCAPEHATCH
@NonNull public static <T> List<T> filter(@NonNull Iterable<?> base, @NonNull Class<T> type)
@NonNull public static <T> List<T> filter(@NonNull List<?> base, @NonNull Class<T> type)
@Nullable public static String replaceMacro(@CheckForNull String s, @NonNull Map<String,String> properties)
properties.get('key')
.
Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.)
@Nullable public static String replaceMacro(@CheckForNull String s, @NonNull VariableResolver<String> resolver)
resolver.get('key')
.
Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.)
@NonNull @Deprecated public static String loadFile(@NonNull File logfile) throws IOException
loadFile(java.io.File, java.nio.charset.Charset)
instead to specify the charset to use for decoding (preferably
StandardCharsets.UTF_8
).logfile
into a
string using the default charset
for
decoding. If no such file exists, an empty string is returned.logfile
- The text file to read in its entirety.logfile
.IOException
- If an error occurs while reading the file.@NonNull public static String loadFile(@NonNull File logfile, @NonNull Charset charset) throws IOException
logfile
into a
string using charset
for decoding. If no such file exists,
an empty string is returned.logfile
- The text file to read in its entirety.charset
- The charset to use for decoding the bytes in logfile
.logfile
.IOException
- If an error occurs while reading the file.public static void deleteContentsRecursive(@NonNull File file) throws IOException
IOException
- if the operation fails.@Restricted(value=org.kohsuke.accmod.restrictions.NoExternalUse.class) public static void deleteContentsRecursive(@NonNull Path path, @NonNull PathRemover.PathChecker pathChecker) throws IOException
path
- a directory to deletepathChecker
- a security check to validate a path before deletingIOException
- if the operation failspublic static void deleteFile(@NonNull File f) throws IOException
f
- a file to deleteIOException
- if it exists but could not be successfully deletedpublic static void deleteRecursive(@NonNull File dir) throws IOException
IOException
- if the operation fails.@Restricted(value=org.kohsuke.accmod.restrictions.NoExternalUse.class) public static void deleteRecursive(@NonNull Path dir, @NonNull PathRemover.PathChecker pathChecker) throws IOException
dir
- a directory to deletepathChecker
- a security check to validate a path before deletingIOException
- if the operation failspublic static boolean isSymlink(@NonNull File file) throws IOException
Files.isSymbolicLink(Path)
, this method also
considers NTFS junction points as symbolic
links.IOException
@Restricted(value=org.kohsuke.accmod.restrictions.NoExternalUse.class) public static boolean isSymlink(@NonNull Path path)
public static boolean isRelativePath(String path)
path
- the path.true
if the path looks relative.public static boolean isDescendant(File forParent, File potentialChild) throws IOException
forParent
- the parent the child should be a descendant ofpotentialChild
- the path to checkIOException
- for invalid pathsInvalidPathException
public static File createTempDir() throws IOException
IOException
public static void displayIOException(@NonNull IOException e, @NonNull TaskListener listener)
@CheckForNull public static String getWin32ErrorMessage(@NonNull IOException e)
@CheckForNull public static String getWin32ErrorMessage(Throwable e)
Throwable
if possible.@CheckForNull public static String getWin32ErrorMessage(int n)
@NonNull public static String getHostName()
@Deprecated public static void copyStream(@NonNull InputStream in, @NonNull OutputStream out) throws IOException
IOUtils.copy(InputStream, OutputStream)
IOException
@Deprecated public static void copyStream(@NonNull Reader in, @NonNull Writer out) throws IOException
IOUtils.copy(Reader, Writer)
IOException
@Deprecated public static void copyStreamAndClose(@NonNull InputStream in, @NonNull OutputStream out) throws IOException
IOUtils.copy(InputStream, OutputStream)
in a try
-with-resources blockIOException
@Deprecated public static void copyStreamAndClose(@NonNull Reader in, @NonNull Writer out) throws IOException
IOUtils.copy(Reader, Writer)
in a try
-with-resources blockIOException
@NonNull public static String[] tokenize(@NonNull String s, @CheckForNull String delimiter)
In 1.210, this method was changed to handle quotes like Unix shell does.
Before that, this method just used StringTokenizer
.
QuotedStringTokenizer
@NonNull public static String[] mapToEnv(@NonNull Map<String,String> m)
public static int min(int x, @NonNull int... values)
@Nullable public static String ensureEndsWith(@CheckForNull String subject, @CheckForNull String suffix)
subject
- Examined stringsuffix
- Desired suffix@NonNull public static String getDigestOf(@NonNull InputStream source) throws IOException
source
- The stream will be closed by this method at the end of this method.IOException
DigestUtils.md5Hex(InputStream)
@NonNull public static String getDigestOf(@NonNull File file) throws IOException
file
- a fileIOException
- in case reading fails@NonNull public static SecretKey toAes128Key(@NonNull String s)
@NonNull public static String toHexString(@NonNull byte[] data, int start, int len)
@NonNull public static String toHexString(@NonNull byte[] bytes)
@NonNull public static byte[] fromHexString(@NonNull String data)
@NonNull public static String getTimeSpanString(long duration)
duration
- number of milliseconds.@Deprecated @NonNull public static String getPastTimeString(long duration)
getTimeSpanString(long)
, does not add ago
.@NonNull @Deprecated public static String combine(long n, @NonNull String suffix)
Messages.Util_year(Object)
for an example.
Deprecated since 2009-06-24, remove method after 2009-12-24.@NonNull public static <T> List<T> createSubList(@NonNull Collection<?> source, @NonNull Class<T> type)
@NonNull public static String encode(@NonNull String s)
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).
@NonNull public static String rawEncode(@NonNull String s)
"#%<>[\]^`{|}~
)
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.@NonNull public static String fullEncode(@NonNull String s)
/
) is encoded, so the given string should be a
single path component used in constructing a URL.@Nullable public static String escape(@CheckForNull String text)
public static void touch(@NonNull File file) throws IOException
touch
utility which merely
updates the file's access and/or modification time.IOException
@Deprecated @Restricted(value=org.kohsuke.accmod.restrictions.NoExternalUse.class) @RestrictedSince(value="2.335") public static void copyFile(@NonNull File src, @NonNull File dst) throws org.apache.tools.ant.BuildException
Files.copy(Path, Path, CopyOption...)
directlyorg.apache.tools.ant.BuildException
@NonNull public static <T> T fixNull(@CheckForNull T s, @NonNull T defaultValue)
null
to a default value.defaultValue
- Default value. It may be immutable or not, depending on the implementation.@CheckForNull public static String fixEmpty(@CheckForNull String s)
@CheckForNull public static String fixEmptyAndTrim(@CheckForNull String s)
@NonNull public static <T> List<T> fixNull(@CheckForNull List<T> l)
T
- Type of the list.l
- list to check.l
if l is not null
.
An empty immutable list if l is null
.@NonNull public static <T> Set<T> fixNull(@CheckForNull Set<T> l)
T
- Type of the set.l
- set to check.l
if l is not null
.
An empty immutable set if l is null
.@NonNull public static <T> Collection<T> fixNull(@CheckForNull Collection<T> l)
T
- Type of the collection.l
- collection to check.l
if l is not null
.
An empty immutable set if l is null
.@NonNull public static <T> Iterable<T> fixNull(@CheckForNull Iterable<T> l)
T
- Type of the iterable.l
- iterable to check.l
if l is not null
.
An empty immutable set if l is null
.@NonNull public static String getFileName(@NonNull String filePath)
@Deprecated @NonNull public static String join(@NonNull Collection<?> strings, @NonNull String separator)
String.join(CharSequence, Iterable)
@NonNull public static <T> List<T> join(@NonNull Collection<? extends T>... items)
@NonNull public static org.apache.tools.ant.types.FileSet createFileSet(@NonNull File baseDir, @NonNull String includes, @CheckForNull String excludes)
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.
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.@NonNull public static org.apache.tools.ant.types.FileSet createFileSet(@NonNull File baseDir, @NonNull String includes)
public static void createSymlink(@NonNull File baseDir, @NonNull String targetPath, @NonNull String symlinkPath, @NonNull TaskListener listener) throws InterruptedException
If there's a prior symlink at baseDir+symlinkPath, it will be overwritten.
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
)InterruptedException
@Deprecated public static String resolveSymlink(File link, TaskListener listener) throws InterruptedException, IOException
resolveSymlink(File)
InterruptedException
IOException
@CheckForNull public static File resolveSymlinkToFile(@NonNull File link) throws InterruptedException, IOException
File
that points to.InterruptedException
IOException
@CheckForNull public static String resolveSymlink(@NonNull File link) throws IOException
If the resolution fails, report an error.
IOException
@Deprecated public static String encodeRFC2396(String url)
encode(String)
instead.@NonNull public static String wrapToErrorSpan(@NonNull String s)
@CheckForNull public static Number tryParseNumber(@CheckForNull String numberStr, @CheckForNull Number defaultNumber)
numberStr
- string to parsedefaultNumber
- number to return if the string can not be parsedpublic static boolean isOverridden(@NonNull Class<?> base, @NonNull Class<?> derived, @NonNull String methodName, @NonNull Class<?>... types)
base
- The base type.derived
- The derived type.methodName
- The name of the method.types
- The types of the arguments for the method.true
when derived
provides the specified method other than as inherited from base
.IllegalArgumentException
- When derived
does not derive from base
, or when base
does not contain the specified method.public static <T> T ifOverridden(Supplier<T> supplier, @NonNull Class<?> base, @NonNull Class<?> derived, @NonNull String methodName, @NonNull Class<?>... types)
supplier
- The supplier to call if the method is indeed overridden.base
- The base type.derived
- The derived type.methodName
- The name of the method.types
- The types of the arguments for the method.true
when derived
provides the specified method other than as inherited from base
.IllegalArgumentException
- When derived
does not derive from base
, or when base
does not contain the specified method.AbstractMethodError
- If the derived class doesn't override the given method.@NonNull public static File changeExtension(@NonNull File dst, @NonNull String ext)
ext
- For example, ".zip"@Nullable public static String intern(@CheckForNull String s)
@Deprecated @RestrictedSince(value="1.651.2 / 2.3") @Restricted(value=org.kohsuke.accmod.restrictions.NoExternalUse.class) public static boolean isAbsoluteUri(@NonNull String uri)
isSafeToRedirectTo(java.lang.String)
instead if your goal is to prevent open redirectsURI
, but
implementing this by ourselves allow it to be more lenient about
escaping of URI.public static boolean isSafeToRedirectTo(@NonNull String uri)
@NonNull public static Properties loadProperties(@NonNull String properties) throws IOException
Properties
IOException
@Restricted(value=org.kohsuke.accmod.restrictions.NoExternalUse.class) public static void closeAndLogFailures(@CheckForNull Closeable toClose, @NonNull Logger logger, @NonNull String closeableName, @NonNull String closeableOwner)
WARNING
level.toClose
- Item to close. Nothing will happen if it is null
logger
- Logger, which receives the errorcloseableName
- Name of the closeable itemcloseableOwner
- String representation of the closeable holder@Restricted(value=org.kohsuke.accmod.restrictions.NoExternalUse.class) public static int permissionsToMode(Set<PosixFilePermission> permissions)
@Restricted(value=org.kohsuke.accmod.restrictions.NoExternalUse.class) public static Set<PosixFilePermission> modeToPermissions(int mode) throws IOException
IOException
@Restricted(value=org.kohsuke.accmod.restrictions.NoExternalUse.class) @NonNull public static Path fileToPath(@NonNull File file) throws IOException
IOException
- if f.toPath()
throws InvalidPathException
.@Restricted(value=org.kohsuke.accmod.restrictions.NoExternalUse.class) public static Path createDirectories(@NonNull Path dir, FileAttribute<?>... attrs) throws IOException
Unlike Files.createDirectory(java.nio.file.Path, java.nio.file.attribute.FileAttribute<?>...)
, an exception is not thrown
if the directory could not be created because it already exists.
Unlike Files.createDirectories(java.nio.file.Path, java.nio.file.attribute.FileAttribute<?>...)
, an exception is not thrown
if the directory (or one of its parents) is a symbolic link.
The attrs
parameter contains optional file attributes
to set atomically when creating the nonexistent directories.
Each file attribute is identified by its FileAttribute.name()
.
If more than one attribute of the same name is included in the array,
then all but the last occurrence is ignored.
If this method fails, then it may do so after creating some, but not all, of the parent directories.
dir
- The directory to create.attrs
- An optional list of file attributes to set atomically
when creating the directory.UnsupportedOperationException
- If the array contains an attribute
that cannot be set atomically when creating the directory.FileAlreadyExistsException
- If dir
exists but is not a directory.IOException
- If an I/O error occurs.Files.createDirectories(Path, FileAttribute[])
@Restricted(value=org.kohsuke.accmod.restrictions.NoExternalUse.class) public static long daysBetween(@NonNull Date a, @NonNull Date b)
@Restricted(value=org.kohsuke.accmod.restrictions.NoExternalUse.class) public static long daysElapsedSince(@NonNull Date date)
daysBetween(Date, Date)
@Restricted(value=org.kohsuke.accmod.restrictions.NoExternalUse.class) @NonNull public static <T> T getNearestAncestorOfTypeOrThrow(@NonNull org.kohsuke.stapler.StaplerRequest request, @NonNull Class<T> clazz)
Copyright © 2004–2022. All rights reserved.