Top Description Fields Constructors Methods
org.freedesktop.dbus.utils

public final Class Util

extends Object
Class Inheritance
Imports
org.freedesktop.dbus.TypeRef, org.slf4j.Logger, .LoggerFactory, java.io.*, java.lang.reflect.Array, .Constructor, .ParameterizedType, .Type, java.net.URL, .URLConnection, java.nio.charset.Charset, java.nio.file.Files, .LinkOption, .Path, java.nio.file.attribute.*, java.util.*, java.util.regex.Matcher, .Pattern

Utility class providing helper methods for handling strings, files and so on.
Author
hypfvieh
Since
v3.2.5 - 2020-12-28

Field Summary

Modifier and TypeField and Description
private static final Logger
private static final Random
private static final char[]
SYMBOLS

Characters used for random strings

private static final String

Constructor Summary

AccessConstructor and Description
private
Util()

Method Summary

Modifier and TypeMethod and Description
public static String

Returns:

abbreviated string, original string if string length is lower or equal then desired length or null if input was null
abbreviate
(String
string to abbrivate
_str
,
int
max length
_length
)

Abbreviates a String using ellipses.

public static int

Returns:

given value if in range
checkIntInRange
(int
value to check
_check
,
int
minimum allowed value (including)
_min
,
int
maximum allowed value (including)
_max
)

Checks if given value is greater or equal to the given minimum and less or equal to the given maximum.

public static <
type
T
>
boolean

Returns:

true if any value found, false if any parameter null or no matching value found
collectionContainsAny
(Collection<T>
collection to check
_haystack
,
Collection<T>
values to find
_needles
)

Checks if any of the 'needle' values are found in 'haystack'.

public static String

Returns:

address String
createDynamicSessionAddress
(boolean
true if the address should be used for a listing socket
_listeningSocket
,
boolean
true to create an abstract socket
_abstract
)

Creates a unix socket address using.

public static String

Returns:

input string or default
defaultString
(String
input string
_input
,
String
default to use if input is null
_default
)

Return a default String if input is null.

public static String

Returns:

String
genGUID
()

Create a random GUID (used for connection addresses).

public static <
type of input class
C
>
Constructor<? extends C>

Returns:

constructor matching given pattern or null
getConstructor
(Class<? extends C>
class to query for constructor
_clz
,
Class<?>...
parameter classes used in constructor
_args
)

Tries to find a constructor of the given class with the given signature.

public static String

Returns:

logged on user
getCurrentUser
()

Determines the current logged on user.

public static String

Returns:

host name
getHostName
()

Gets the host name of the local machine.

public static int

Returns:

java major
getJavaVersion
()

Get the java version of the current running JRE.

public static List<String>

Returns:

list of string or null on error
getTextfileFromUrl
(String
url providing the file to read
_url
,
Charset
charset to use
_charset
,
boolean
true to not log exceptions, false otherwise
_silent
)

Reads a text file from the given URL using the provided charset.

public static boolean

Returns:

true if string is blank or null, false otherwise
isBlank
(String
string to test
_str
)

Checks if the given String is either null or blank.

public static boolean

Returns:

true if string is empty or null, false otherwise
isEmpty
(String
string to test
_str
)

Checks if the given String is either null or empty.

public static boolean
public static boolean

Returns:

true if integer, false otherwise
isInteger
(String
string to validate
_str
,
boolean
negative integer allowed
_allowNegative
)

Check if string is an either positive or negative integer.

public static boolean

Returns:

true if MacOS (or MacOS X), false otherwise
isMacOs
()

Checks if the running OS is a MacOS/MacOS X.

public static boolean

Returns:

true if int is a valid network port, false otherwise
isValidNetworkPort
(int
'port' to check
_port
,
boolean
allow ports below 1024 (aka reserved well known ports)
_allowWellKnown
)

Check if the given value is a valid network port (1 - 65535).

public static boolean

Returns:

true if valid port, false otherwise
isValidNetworkPort
(String
string to check
_str
,
boolean
allow well known port
_allowWellKnown
)

public static boolean

Returns:

true if Windows, false otherwise
isWindows
()

Checks if the running OS is a MS Windows OS.

public static String

Returns:

random string or empty string if _length <= 0
randomString
(int
length of random string
_length
)

Generate a simple (cryptographic insecure) random string.

public static List<String>

Returns:

list containing text
readFileToList
(String
file to read
_fileName
)

Reads a file to a List<String> (each line is one entry in list).

public static String

Returns:

String containing content, maybe null
readFileToString
(File
file to read
_file
)

Reads a file to a String.

public static Properties

Returns:

Properties Object or null
readProperties
(File
property file to read
_file
)

Trys to read a properties file.

public static Properties

Returns:

properties object/null
readProperties
(InputStream
input stream providing property file content
_stream
)

Tries to read a properties file from an inputstream.

public static List<String>

Returns:

List of string or null on error
readTextFileFromStream
(InputStream
stream to read
_input
,
Charset
charset to use
_charset
,
boolean
true to disable exception logging, false otherwise
_silent
)

Reads a text file from given InputStream using the given Charset.

public static void
setFilePermissions(Path
path to file which where permissions should be set
_path
,
String
new owner for the file
_fileOwner
,
String
new group for the file
_fileGroup
,
Set<PosixFilePermission>
unix permissions to set on file
_fileUnixPermissions
)

Setup the unix socket file permissions.

public static String

Returns:

camel case string or input if nothing todo. Returns null if input was null.
snakeToCamelCase
(String
string
_input
)

Converts a snake-case-string to camel case string.

public static boolean

Returns:

true if both are equal (also true if both are null)
strEquals
(String
first string
_str1
,
String
second string
_str2
)

Null-safe equals for two strings.

public static Object[]

Returns:

object array
toObjectArray
(Object
object of arbitrary type
_obj
)

Convert a object of arbitrary type to an object array.

public static Type

Returns:

Type used in TypeRef if class is extending TypeRef interface, null otherwise
unwrapTypeRef
(Class<?>
class to unwrap
_type
)

Gets the type wrapped by a TypeRef interface.

public static String

Returns:

uppercased string
upperCaseFirstChar
(String
string
_str
)

Upper case the first letter of the given string.

public static <
exception type which might be thrown
T extends Throwable
>
void
waitFor(String
name for the lock (used in exception text and logging)
_lockName
,
IThrowingSupplier<Boolean, T>
supplier to wait for
_wait
,
long
timeout in milliseconds when wait will fail
_timeoutMs
,
long
sleep time between each retries
_sleepTime
)

Waits for the provided supplier to return true or throws an exception.

public static boolean

Returns:

true on successful write, false otherwise
writeTextFile
(String
the file to write
_fileName
,
String
the content to write
_fileContent
,
Charset
the charset to use
_charset
,
boolean
append content to file, if false file will be overwritten if existing
_append
)

Write String to file with the given charset.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

LOGGERback to summary
private static final Logger LOGGER
RANDOMback to summary
private static final Random RANDOM
SYMBOLSback to summary
private static final char[] SYMBOLS

Characters used for random strings

SYSPROP_OS_NAMEback to summary
private static final String SYSPROP_OS_NAME

Constructor Detail

Utilback to summary
private Util()

Method Detail

abbreviateback to summary
public static String abbreviate(String _str, int _length)

Abbreviates a String using ellipses.

Parameters
_str:String

string to abbrivate

_length:int

max length

Returns:String

abbreviated string, original string if string length is lower or equal then desired length or null if input was null

checkIntInRangeback to summary
public static int checkIntInRange(int _check, int _min, int _max)

Checks if given value is greater or equal to the given minimum and less or equal to the given maximum.

Parameters
_check:int

value to check

_min:int

minimum allowed value (including)

_max:int

maximum allowed value (including)

Returns:int

given value if in range

Exceptions
IllegalArgumentException:
when given value is out of range
Since
4.2.0 - 2022-07-13
collectionContainsAnyback to summary
public static <T> boolean collectionContainsAny(Collection<T> _haystack, Collection<T> _needles)

Checks if any of the 'needle' values are found in 'haystack'.

Parameters
<T>
type
_haystack:Collection<T>

collection to check

_needles:Collection<T>

values to find

Returns:boolean

true if any value found, false if any parameter null or no matching value found

createDynamicSessionAddressback to summary
public static String createDynamicSessionAddress(boolean _listeningSocket, boolean _abstract)

Creates a unix socket address using.

Parameters
_listeningSocket:boolean

true if the address should be used for a listing socket

_abstract:boolean

true to create an abstract socket

Returns:String

address String

defaultStringback to summary
public static String defaultString(String _input, String _default)

Return a default String if input is null.

Parameters
_input:String

input string

_default:String

default to use if input is null

Returns:String

input string or default

genGUIDback to summary
public static String genGUID()

Create a random GUID (used for connection addresses).

Returns:String

String

getConstructorback to summary
public static <C> Constructor<? extends C> getConstructor(Class<? extends C> _clz, Class<?>... _args)

Tries to find a constructor of the given class with the given signature. Will catch all exceptions and return null in doubt.

Parameters
<C>
type of input class
_clz:Class<? extends C>

class to query for constructor

_args:Class<?>[]

parameter classes used in constructor

Returns:Constructor<? extends C>

constructor matching given pattern or null

getCurrentUserback to summary
public static String getCurrentUser()

Determines the current logged on user.

Returns:String

logged on user

getHostNameback to summary
public static String getHostName()

Gets the host name of the local machine.

Returns:String

host name

getJavaVersionback to summary
public static int getJavaVersion()

Get the java version of the current running JRE.

Returns:int

java major

getTextfileFromUrlback to summary
public static List<String> getTextfileFromUrl(String _url, Charset _charset, boolean _silent)

Reads a text file from the given URL using the provided charset. Using the _silent argument optionally disables all error logging.

Parameters
_url:String

url providing the file to read

_charset:Charset

charset to use

_silent:boolean

true to not log exceptions, false otherwise

Returns:List<String>

list of string or null on error

isBlankback to summary
public static boolean isBlank(String _str)

Checks if the given String is either null or blank. Blank means:

" " - true
"" - true
null - true
" xx" - false
Parameters
_str:String

string to test

Returns:boolean

true if string is blank or null, false otherwise

isEmptyback to summary
public static boolean isEmpty(String _str)

Checks if the given String is either null or empty. Blank means:

" " - false
"" - true
null - true
" xx" - false
Parameters
_str:String

string to test

Returns:boolean

true if string is empty or null, false otherwise

isFreeBsdback to summary
public static boolean isFreeBsd()
isIntegerback to summary
public static boolean isInteger(String _str, boolean _allowNegative)

Check if string is an either positive or negative integer.

Parameters
_str:String

string to validate

_allowNegative:boolean

negative integer allowed

Returns:boolean

true if integer, false otherwise

isMacOsback to summary
public static boolean isMacOs()

Checks if the running OS is a MacOS/MacOS X.

Returns:boolean

true if MacOS (or MacOS X), false otherwise

isValidNetworkPortback to summary
public static boolean isValidNetworkPort(int _port, boolean _allowWellKnown)

Check if the given value is a valid network port (1 - 65535).

Parameters
_port:int

'port' to check

_allowWellKnown:boolean

allow ports below 1024 (aka reserved well known ports)

Returns:boolean

true if int is a valid network port, false otherwise

isValidNetworkPortback to summary
public static boolean isValidNetworkPort(String _str, boolean _allowWellKnown)
Parameters
_str:String

string to check

_allowWellKnown:boolean

allow well known port

Returns:boolean

true if valid port, false otherwise

See Also
isValidNetworkPort(int, boolean)
isWindowsback to summary
public static boolean isWindows()

Checks if the running OS is a MS Windows OS.

Returns:boolean

true if Windows, false otherwise

randomStringback to summary
public static String randomString(int _length)

Generate a simple (cryptographic insecure) random string.

Parameters
_length:int

length of random string

Returns:String

random string or empty string if _length <= 0

readFileToListback to summary
public static List<String> readFileToList(String _fileName)

Reads a file to a List<String> (each line is one entry in list). Line endings (line feed/carriage return) are NOT removed!

Parameters
_fileName:String

file to read

Returns:List<String>

list containing text

readFileToStringback to summary
public static String readFileToString(File _file)

Reads a file to a String. Line endings (line feed/carriage return) are NOT removed!

Parameters
_file:File

file to read

Returns:String

String containing content, maybe null

readPropertiesback to summary
public static Properties readProperties(File _file)

Trys to read a properties file. Returns null if properties file could not be loaded

Parameters
_file:File

property file to read

Returns:Properties

Properties Object or null

readPropertiesback to summary
public static Properties readProperties(InputStream _stream)

Tries to read a properties file from an inputstream.

Parameters
_stream:InputStream

input stream providing property file content

Returns:Properties

properties object/null

readTextFileFromStreamback to summary
public static List<String> readTextFileFromStream(InputStream _input, Charset _charset, boolean _silent)

Reads a text file from given InputStream using the given Charset.

Parameters
_input:InputStream

stream to read

_charset:Charset

charset to use

_silent:boolean

true to disable exception logging, false otherwise

Returns:List<String>

List of string or null on error

setFilePermissionsback to summary
public static void setFilePermissions(Path _path, String _fileOwner, String _fileGroup, Set<PosixFilePermission> _fileUnixPermissions)

Setup the unix socket file permissions. User and group can always be set, file permissions are only set on non-windows OSes.

Parameters
_path:Path

path to file which where permissions should be set

_fileOwner:String

new owner for the file

_fileGroup:String

new group for the file

_fileUnixPermissions:Set<PosixFilePermission>

unix permissions to set on file

snakeToCamelCaseback to summary
public static String snakeToCamelCase(String _input)

Converts a snake-case-string to camel case string.
Eg. this_is_snake_case → thisIsSnakeCase

Parameters
_input:String

string

Returns:String

camel case string or input if nothing todo. Returns null if input was null.

strEqualsback to summary
public static boolean strEquals(String _str1, String _str2)

Null-safe equals for two strings.

Parameters
_str1:String

first string

_str2:String

second string

Returns:boolean

true if both are equal (also true if both are null)

toObjectArrayback to summary
public static Object[] toObjectArray(Object _obj)

Convert a object of arbitrary type to an object array.
If input is null or not an array, an empty array will be returned.

Parameters
_obj:Object

object of arbitrary type

Returns:Object[]

object array

unwrapTypeRefback to summary
public static Type unwrapTypeRef(Class<?> _type)

Gets the type wrapped by a TypeRef interface.

Parameters
_type:Class<?>

class to unwrap

Returns:Type

Type used in TypeRef if class is extending TypeRef interface, null otherwise

upperCaseFirstCharback to summary
public static String upperCaseFirstChar(String _str)

Upper case the first letter of the given string.

Parameters
_str:String

string

Returns:String

uppercased string

waitForback to summary
public static <T extends Throwable> void waitFor(String _lockName, IThrowingSupplier<Boolean, T> _wait, long _timeoutMs, long _sleepTime) throws IThrowingConsumer:T

Waits for the provided supplier to return true or throws an exception.

This method will call the provided supplier every _sleepTime milliseconds to check if the supplier returns true.
If supplier returns true, method will return. If no value is present after the defined _timeoutMs a IllegalStateException is thrown.

Parameters
<T>
exception type which might be thrown
_lockName:String

name for the lock (used in exception text and logging)

_wait:IThrowingSupplier<Boolean, T>

supplier to wait for

_timeoutMs:long

timeout in milliseconds when wait will fail

_sleepTime:long

sleep time between each retries

Annotations
@SuppressWarnings:unchecked
Exceptions
IThrowingConsumer:T:
when timeout is reached
writeTextFileback to summary
public static boolean writeTextFile(String _fileName, String _fileContent, Charset _charset, boolean _append)

Write String to file with the given charset. Optionally appends the data to the file.

Parameters
_fileName:String

the file to write

_fileContent:String

the content to write

_charset:Charset

the charset to use

_append:boolean

append content to file, if false file will be overwritten if existing

Returns:boolean

true on successful write, false otherwise