Modifier and Type | Class and Description |
---|---|
private static class |
Utils.DirectionString
Utility class to save a string along with its rendering direction
(left-to-right or right-to-left).
|
static interface |
Utils.Function<A,B>
Represents a function that can be applied to objects of
A and
returns objects of B . |
Modifier and Type | Field and Description |
---|---|
private static char[] |
DEFAULT_STRIP |
private static double |
EPSILON |
private static char[] |
HEX_ARRAY |
private static Pattern |
HTTP_PREFFIX_PATTERN |
private static int |
MILLIS_OF_DAY |
private static int |
MILLIS_OF_HOUR |
private static int |
MILLIS_OF_MINUTE |
private static int |
MILLIS_OF_SECOND |
static String |
URL_CHARS |
static Pattern |
WHITE_SPACES_PATTERN
Pattern matching white spaces
|
Modifier | Constructor and Description |
---|---|
private |
Utils() |
Modifier and Type | Method and Description |
---|---|
static <T> T[] |
addInArrayCopy(T[] array,
T item)
Adds the given item at the end of a new copy of given array.
|
static <T> T |
cast(Object o,
Class<T> klass)
Cast an object savely.
|
static void |
close(Closeable c)
Utility method for closing a
Closeable object. |
static void |
close(ZipFile zip)
Utility method for closing a
ZipFile . |
static Integer |
color_float2int(Float val)
convert float range 0 <= x <= 1 to integer range 0..255
when dealing with colors and color alpha value
|
static Float |
color_int2float(Integer val)
convert integer range 0..255 to float range 0 <= x <= 1
when dealing with colors and color alpha value
|
static Color |
complement(Color clr)
Returns the complementary color of
clr . |
static char[] |
copyArray(char[] array)
Copies the given array.
|
static int[] |
copyArray(int[] array)
Copies the given array.
|
static <T> T[] |
copyArray(T[] array)
Copies the given array.
|
static void |
copyDirectory(File in,
File out)
Recursive directory copy function
|
static Path |
copyFile(File in,
File out)
Simple file copy function that will overwrite the target file.
|
static boolean |
copyToClipboard(String s)
Copies the string
s to system clipboard. |
static String |
decodeUrl(String s)
Decodes a
application/x-www-form-urlencoded string. |
static boolean |
deleteDirectory(File path)
Deletes a directory recursively.
|
static boolean |
deleteFile(File file)
Deletes a file and log a default warning if the deletion fails.
|
static boolean |
deleteFile(File file,
String warnMsg)
Deletes a file and log a configurable warning if the deletion fails.
|
static String |
encodeUrl(String s)
Translates a string into
application/x-www-form-urlencoded
format. |
static void |
ensure(boolean condition,
String message,
Object... data)
Ensures a logical condition is met.
|
static boolean |
equalCollection(Collection<?> a,
Collection<?> b)
Determines if two collections are equal.
|
static boolean |
equalsEpsilon(double a,
double b)
Determines if the two given double values are equal (their delta being smaller than a fixed epsilon)
|
static String |
escapeReservedCharactersHTML(String s)
Replaces some HTML reserved characters (<, > and &) by their equivalent entity (<, > and &);
|
static String |
execOutput(List<String> command)
Runs an external command and returns the standard output.
|
static <T> boolean |
exists(Iterable<? extends T> collection,
Predicate<? super T> predicate)
Tests whether
predicate applies to at least one element from collection . |
static <T> boolean |
exists(Iterable<T> collection,
Class<? extends T> klass) |
static URL |
fileToURL(File f)
Converts the given file to its URL.
|
static <T> Collection<T> |
filter(Collection<? extends T> collection,
Predicate<? super T> predicate) |
static <S,T extends S> |
filteredCollection(Collection<S> collection,
Class<T> klass)
Filter a collection by (sub)class.
|
static <T> T |
find(Iterable<? extends T> collection,
Predicate<? super T> predicate) |
static <T> T |
find(Iterable<? super T> collection,
Class<? extends T> klass) |
static <T> T |
firstNonNull(T... items)
Returns the first element from
items which is non-null, or null if all elements are null. |
static String |
fixURLQuery(String url)
Fixes URL with illegal characters in the query (and fragment) part by
percent encoding those characters.
|
static <T> boolean |
forAll(Iterable<? extends T> collection,
Predicate<? super T> predicate)
Tests whether
predicate applies to all elements from collection . |
static org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream |
getBZip2InputStream(InputStream in)
Returns a Bzip2 input stream wrapping given input stream.
|
static String |
getClipboardContent()
Extracts clipboard content as string.
|
static String |
getDurationString(long elapsedTime)
Returns a simple human readable (hours, minutes, seconds) string for a given duration in milliseconds.
|
static List<GlyphVector> |
getGlyphVectorsBidi(String string,
Font font,
FontRenderContext frc)
Convert a string to a list of
GlyphVector s. |
static GZIPInputStream |
getGZipInputStream(InputStream in)
Returns a Gzip input stream wrapping given input stream.
|
static File |
getJosmTempDir()
Returns the JOSM temp directory.
|
static List<String> |
getMatches(Matcher m)
Returns a list of capture groups if
Matcher.matches() , or null . |
static String |
getPositionListString(List<Integer> positionList)
Returns a human readable representation of a list of positions.
|
static Throwable |
getRootCause(Throwable t)
Returns the root cause of a throwable object.
|
static String |
getSizeString(long bytes,
Locale locale)
Returns a human readable representation (B, kB, MB, ...) for the given number of byes.
|
static Transferable |
getTransferableContent(Clipboard clipboard)
Extracts clipboard content as
Transferable object. |
static ZipInputStream |
getZipInputStream(InputStream in)
Returns a Zip input stream wrapping given input stream.
|
static boolean |
hasExtension(File file,
String... extensions)
Determines if the file's name has one of the given extensions, in a robust manner.
|
static boolean |
hasExtension(String filename,
String... extensions)
Determines if the filename has one of the given extensions, in a robust manner.
|
static int |
hashMapInitialCapacity(int nEntries)
Returns the initial capacity to pass to the HashMap / HashSet constructor
when it is initialized with a known number of entries.
|
static int |
hashMapInitialCapacity(int nEntries,
float loadFactor)
Returns the initial capacity to pass to the HashMap / HashSet constructor
when it is initialized with a known number of entries.
|
static <T> int |
indexOf(Iterable<? extends T> collection,
Predicate<? super T> predicate) |
static boolean |
isLocalUrl(String url)
Determines if the given URL denotes a file on a local filesystem.
|
static String |
join(String sep,
Collection<?> values)
Joins a list of strings (or objects that can be converted to string via
Object.toString()) into a single string with fields separated by sep.
|
static String |
joinAsHtmlUnorderedList(Iterable<?> values)
Converts the given iterable collection as an unordered HTML list.
|
static int |
max(int a,
int b,
int c,
int d)
Returns the greater of four
int values. |
static String |
md5Hex(String data)
Calculate MD5 hash of a string and output in hexadecimal format.
|
static int |
min(int a,
int b,
int c)
Returns the minimum of three values.
|
static int |
mod(int a,
int n)
Return the modulus in the range [0, n)
|
static SAXParser |
newSafeSAXParser()
Returns a new secure SAX parser, supporting XML namespaces.
|
static ThreadFactory |
newThreadFactory(String nameFormat,
int threadPriority)
Creates a new
ThreadFactory which creates threads with names according to nameFormat . |
static Pair<Integer,ExecutorService> |
newThreadPool(String pref,
String nameFormat,
int threadPriority)
Returns a pair containing the number of threads (n), and a thread pool (if n > 1) to perform
multi-thread computation in the context of the given preference key.
|
static HttpURLConnection |
openHttpConnection(URL httpURL)
Deprecated.
Use
HttpClient instead |
static HttpURLConnection |
openHttpConnection(URL httpURL,
boolean keepAlive)
Deprecated.
Use
HttpClient instead |
static HttpURLConnection |
openHttpConnection(URL httpURL,
boolean keepAlive,
boolean followRedirects)
Deprecated.
Use
HttpClient instead |
static InputStream |
openURL(URL url)
Deprecated.
Use
HttpClient instead |
static InputStream |
openURLAndDecompress(URL url,
boolean decompress)
Deprecated.
Use
HttpClient instead |
static BufferedReader |
openURLReader(URL url)
Deprecated.
Use
HttpClient instead |
static BufferedReader |
openURLReaderAndDecompress(URL url,
boolean decompress)
Deprecated.
Use
HttpClient instead |
static void |
parseSafeSAX(InputSource is,
DefaultHandler dh)
Parse the content given
InputSource as XML using the specified DefaultHandler . |
static byte[] |
readBytesFromStream(InputStream stream)
Reads the input stream and closes the stream at the end of processing (regardless if an exception was thrown)
|
static String |
restrictStringLines(String s,
int maxLines)
If the string
s is longer than maxLines lines, the string is cut and a "..." line is appended. |
static URLConnection |
setupURLConnection(URLConnection connection)
Deprecated.
Use
HttpClient instead |
static String |
shortenString(String s,
int maxLength)
If the string
s is longer than maxLength , the string is cut and "..." is appended. |
static String |
strip(String str)
An alternative to
String.trim() to effectively remove all leading and trailing white characters, including Unicode ones. |
private static String |
strip(String str,
char[] skipChars) |
static String |
strip(String str,
String skipChars)
An alternative to
String.trim() to effectively remove all leading and trailing white characters, including Unicode ones. |
private static boolean |
stripChar(char[] strip,
char c) |
private static char[] |
stripChars(String skipChars) |
static String |
toHexString(byte[] bytes)
Converts a byte array to a string of hexadecimal characters.
|
static <T> List<T> |
topologicalSort(MultiMap<T,T> dependencies)
Topological sort.
|
static String |
toString(Color c)
convert Color to String
(Color.toString() omits alpha value)
|
static <A,B> Collection<B> |
transform(Collection<? extends A> c,
Utils.Function<A,B> f)
Transforms the collection
c into an unmodifiable collection and
applies the Utils.Function f on each element upon access. |
static <A,B> List<B> |
transform(List<? extends A> l,
Utils.Function<A,B> f)
Transforms the list
l into an unmodifiable list and
applies the Utils.Function f on each element upon access. |
static String |
updateSystemProperty(String key,
String value)
Updates a given system property.
|
public static final Pattern WHITE_SPACES_PATTERN
private static final int MILLIS_OF_SECOND
private static final int MILLIS_OF_MINUTE
private static final int MILLIS_OF_HOUR
private static final int MILLIS_OF_DAY
public static final String URL_CHARS
private static char[] DEFAULT_STRIP
private static final double EPSILON
private static final char[] HEX_ARRAY
private static final Pattern HTTP_PREFFIX_PATTERN
private Utils()
public static <T> boolean exists(Iterable<? extends T> collection, Predicate<? super T> predicate)
predicate
applies to at least one element from collection
.T
- type of itemscollection
- the collectionpredicate
- the predicatetrue
if predicate
applies to at least one element from collection
public static <T> boolean forAll(Iterable<? extends T> collection, Predicate<? super T> predicate)
predicate
applies to all elements from collection
.T
- type of itemscollection
- the collectionpredicate
- the predicatetrue
if predicate
applies to all elements from collection
public static <T> Collection<T> filter(Collection<? extends T> collection, Predicate<? super T> predicate)
@SafeVarargs public static <T> T firstNonNull(T... items)
items
which is non-null, or null if all elements are null.T
- type of itemsitems
- the items to look forpublic static <S,T extends S> SubclassFilteredCollection<S,T> filteredCollection(Collection<S> collection, Class<T> klass)
S
- Super type of itemsT
- type of itemscollection
- the collectionklass
- the (sub)classpublic static <T> int indexOf(Iterable<? extends T> collection, Predicate<? super T> predicate)
public static int min(int a, int b, int c)
a
- an argument.b
- another argument.c
- another argument.a
, b
and c
.public static int max(int a, int b, int c, int d)
int
values. That is, the
result is the argument closer to the value of
Integer.MAX_VALUE
. If the arguments have the same value,
the result is that same value.a
- an argument.b
- another argument.c
- another argument.d
- another argument.a
, b
, c
and d
.public static void ensure(boolean condition, String message, Object... data)
condition
- the condition to be metmessage
- Formatted error message to raise if condition is not metdata
- Message parameters, optionalAssertionError
- if the condition is not metpublic static int mod(int a, int n)
a
- dividendn
- divisorpublic static String join(String sep, Collection<?> values)
sep
- the separatorvalues
- collection of objects, null is converted to the
empty stringpublic static String joinAsHtmlUnorderedList(Iterable<?> values)
values
- The iterable collectionpublic static String toString(Color c)
c
- the colorpublic static Integer color_float2int(Float val)
val
- float value between 0 and 1public static Float color_int2float(Integer val)
val
- integer valuepublic static Color complement(Color clr)
clr
.clr
- the color to complementclr
public static <T> T[] copyArray(T[] array)
Arrays.copyOf(T[], int)
, this method is null-safe.T
- type of itemsarray
- The array to copynull
if array
is nullpublic static char[] copyArray(char[] array)
Arrays.copyOf(T[], int)
, this method is null-safe.array
- The array to copynull
if array
is nullpublic static int[] copyArray(int[] array)
Arrays.copyOf(T[], int)
, this method is null-safe.array
- The array to copynull
if array
is nullpublic static Path copyFile(File in, File out) throws IOException
in
- The source fileout
- The destination fileIOException
- if any I/O error occursIllegalArgumentException
- if in
or out
is null
public static void copyDirectory(File in, File out) throws IOException
in
- The source directoryout
- The destination directoryIOException
- if any I/O error ooccursIllegalArgumentException
- if in
or out
is null
public static boolean deleteDirectory(File path)
path
- The directory to deletetrue
if and only if the file or directory is
successfully deleted; false
otherwisepublic static boolean deleteFile(File file)
file
- file to delete
and must contain a single parameter {0}
for the file pathtrue
if and only if the file is successfully deleted; false
otherwisepublic static boolean deleteFile(File file, String warnMsg)
file
- file to deletewarnMsg
- warning message. It will be translated with tr()
and must contain a single parameter {0}
for the file pathtrue
if and only if the file is successfully deleted; false
otherwisepublic static void close(Closeable c)
Utility method for closing a Closeable
object.
c
- the closeable object. May be null.public static void close(ZipFile zip)
Utility method for closing a ZipFile
.
zip
- the zip file. May be null.public static URL fileToURL(File f)
f
- The file to get URL fromnull
if not possible.public static boolean equalsEpsilon(double a, double b)
a
- The first double value to compareb
- The second double value to comparetrue
if abs(a - b) <= 1e-11
, false
otherwisepublic static boolean equalCollection(Collection<?> a, Collection<?> b)
a
- first collectionb
- second collectiontrue
if collections are equal, false
otherwisepublic static boolean copyToClipboard(String s)
s
to system clipboard.s
- string to be copied to clipboard.public static Transferable getTransferableContent(Clipboard clipboard)
Transferable
object.clipboard
- clipboard from which contents are retrievednull
otherwise.public static String getClipboardContent()
null
otherwise.public static String md5Hex(String data)
data
- arbitrary Stringpublic static String toHexString(byte[] bytes)
bytes
- the byte arraypublic static <T> List<T> topologicalSort(MultiMap<T,T> dependencies)
T
- type of itemsdependencies
- contains mappings (key -> value). In the final list of sorted objects, the key will come
after the value. (In other words, the key depends on the value(s).)
There must not be cyclic dependencies.public static String escapeReservedCharactersHTML(String s)
s
- The unescaped stringpublic static <A,B> Collection<B> transform(Collection<? extends A> c, Utils.Function<A,B> f)
c
into an unmodifiable collection and
applies the Utils.Function
f
on each element upon access.A
- class of input collectionB
- class of transformed collectionc
- a collectionf
- a function that transforms objects of A
to objects of B
public static <A,B> List<B> transform(List<? extends A> l, Utils.Function<A,B> f)
l
into an unmodifiable list and
applies the Utils.Function
f
on each element upon access.A
- class of input collectionB
- class of transformed collectionl
- a collectionf
- a function that transforms objects of A
to objects of B
@Deprecated public static HttpURLConnection openHttpConnection(URL httpURL) throws IOException
HttpClient
insteadhttpURL
- The HTTP url to open (must use http:// or https://)IOException
- if an I/O exception occurs.@Deprecated public static InputStream openURL(URL url) throws IOException
HttpClient
insteadurl
- The url to openIOException
- if an I/O exception occurs.@Deprecated public static InputStream openURLAndDecompress(URL url, boolean decompress) throws IOException
HttpClient
insteadurl
- The url to opendecompress
- whether to wrap steam in a GZIPInputStream
or BZip2CompressorInputStream
if the Content-Type
header is set accordingly.IOException
- if an I/O exception occurs.public static org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream getBZip2InputStream(InputStream in) throws IOException
in
- The raw input streamnull
if in
is null
IOException
- if the given input stream does not contain valid BZ2 headerpublic static GZIPInputStream getGZipInputStream(InputStream in) throws IOException
in
- The raw input streamnull
if in
is null
IOException
- if an I/O error has occurredpublic static ZipInputStream getZipInputStream(InputStream in) throws IOException
in
- The raw input streamnull
if in
is null
IOException
- if an I/O error has occurred@Deprecated public static URLConnection setupURLConnection(URLConnection connection)
HttpClient
insteadconnection
- The connection to setupconnection
, with updated properties@Deprecated public static BufferedReader openURLReader(URL url) throws IOException
HttpClient
insteadurl
- The url to openIOException
- if an I/O exception occurs.@Deprecated public static BufferedReader openURLReaderAndDecompress(URL url, boolean decompress) throws IOException
HttpClient
insteadurl
- The url to opendecompress
- whether to wrap steam in a GZIPInputStream
or BZip2CompressorInputStream
if the Content-Type
header is set accordingly.IOException
- if an I/O exception occurs.@Deprecated public static HttpURLConnection openHttpConnection(URL httpURL, boolean keepAlive) throws IOException
HttpClient
insteadhttpURL
- The HTTP url to open (must use http:// or https://)keepAlive
- whether not to set header Connection=close
IOException
- if an I/O exception occurs.@Deprecated public static HttpURLConnection openHttpConnection(URL httpURL, boolean keepAlive, boolean followRedirects) throws IOException
HttpClient
insteadhttpURL
- The HTTP url to open (must use http:// or https://)keepAlive
- whether not to set header Connection=close
followRedirects
- wheter or not to follow HTTP(S) redirectsIOException
- if an I/O exception occurspublic static String strip(String str)
String.trim()
to effectively remove all leading and trailing white characters, including Unicode ones.str
- The string to stripstr
, without leading and trailing characters, according to
Character.isWhitespace(char)
and Character.isSpaceChar(char)
.public static String strip(String str, String skipChars)
String.trim()
to effectively remove all leading and trailing white characters, including Unicode ones.str
- The string to stripskipChars
- additional characters to skipstr
, without leading and trailing characters, according to
Character.isWhitespace(char)
, Character.isSpaceChar(char)
and skipChars.private static char[] stripChars(String skipChars)
private static boolean stripChar(char[] strip, char c)
public static String execOutput(List<String> command) throws IOException
command
- the command with argumentsIOException
- when there was an error, e.g. command does not existpublic static File getJosmTempDir()
<java.io.tmpdir>/JOSM
), or null
if java.io.tmpdir
is not definedpublic static String getDurationString(long elapsedTime)
elapsedTime
- The duration in millisecondsIllegalArgumentException
- if elapsedTime is < 0public static String getSizeString(long bytes, Locale locale)
bytes
- the number of byteslocale
- the locale used for formattingpublic static String getPositionListString(List<Integer> positionList)
For instance, [1,5,2,6,7
yields "1-2,5-7
positionList
- a list of positionspublic static List<String> getMatches(Matcher m)
Matcher.matches()
, or null
.
The first element (index 0) is the complete match.
Further elements correspond to the parts in parentheses of the regular expression.m
- the matcherMatcher.matches()
, or null
.public static <T> T cast(Object o, Class<T> klass)
T
- the target typeo
- the object to castklass
- the target class (same as T)o
is null or the type o
is not
a subclass of klass
. The casted value otherwise.public static Throwable getRootCause(Throwable t)
t
- The object to get root cause fort
public static <T> T[] addInArrayCopy(T[] array, T item)
T
- type of itemsarray
- The source arrayitem
- The item to addarray
containing item
as additional last elementpublic static String shortenString(String s, int maxLength)
s
is longer than maxLength
, the string is cut and "..." is appended.s
- String to shortenmaxLength
- maximum number of characters to keep (not including the "...")public static String restrictStringLines(String s, int maxLines)
s
is longer than maxLines
lines, the string is cut and a "..." line is appended.s
- String to shortenmaxLines
- maximum number of lines to keep (including including the "..." line)public static String fixURLQuery(String url)
url
- the URL that should be fixedpublic static String encodeUrl(String s)
application/x-www-form-urlencoded
format. This method uses UTF-8 encoding scheme to obtain the bytes for unsafe
characters.s
- String
to be translated.String
.decodeUrl(String)
public static String decodeUrl(String s)
application/x-www-form-urlencoded
string.
UTF-8 encoding is used to determine
what characters are represented by any consecutive sequences of the
form "%xy
".s
- the String
to decodeString
encodeUrl(String)
public static boolean isLocalUrl(String url)
url
- The URL to testtrue
if the url points to a local filepublic static ThreadFactory newThreadFactory(String nameFormat, int threadPriority)
ThreadFactory
which creates threads with names according to nameFormat
.nameFormat
- a String.format(String, Object...)
compatible name format; its first argument is a unique thread indexthreadPriority
- the priority of the created threads, see Thread.setPriority(int)
ThreadFactory
public static Pair<Integer,ExecutorService> newThreadPool(String pref, String nameFormat, int threadPriority)
pref
- The preference keynameFormat
- see newThreadFactory(String, int)
threadPriority
- see newThreadFactory(String, int)
public static String updateSystemProperty(String key, String value)
key
- The property keyvalue
- The property valuenull
if it did not have one.public static SAXParser newSafeSAXParser() throws ParserConfigurationException, SAXException
ParserConfigurationException
- if a parser cannot be created which satisfies the requested configuration.SAXException
- for SAX errors.public static void parseSafeSAX(InputSource is, DefaultHandler dh) throws ParserConfigurationException, SAXException, IOException
InputSource
as XML using the specified DefaultHandler
.
This method uses a secure SAX parser, supporting XML namespaces.is
- The InputSource containing the content to be parsed.dh
- The SAX DefaultHandler to use.ParserConfigurationException
- if a parser cannot be created which satisfies the requested configuration.SAXException
- for SAX errors.IOException
- if any IO errors occur.public static boolean hasExtension(String filename, String... extensions)
filename
- The file nameextensions
- The list of extensions to look for (without dot)true
if the filename has one of the given extensionspublic static boolean hasExtension(File file, String... extensions)
file
- The fileextensions
- The list of extensions to look for (without dot)true
if the file's name has one of the given extensionspublic static byte[] readBytesFromStream(InputStream stream) throws IOException
stream
- input streamIOException
- if any I/O error occurspublic static int hashMapInitialCapacity(int nEntries, float loadFactor)
nEntries
- the number of entries expectedloadFactor
- the load factorpublic static int hashMapInitialCapacity(int nEntries)
nEntries
- the number of entries expectedpublic static List<GlyphVector> getGlyphVectorsBidi(String string, Font font, FontRenderContext frc)
GlyphVector
s. The string may contain
bi-directional text. The result will be in correct visual order.
Each element of the resulting list corresponds to one section of the
string with consistent writing direction (left-to-right or right-to-left).string
- the string to renderfont
- the fontfrc
- a FontRenderContext object