Class Commons
java.lang.Object
de.iip_ecosphere.platform.support.commons.Commons
Commons utility interface.
- Author:
- Holger Eichelberger, SSE
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static Commonsstatic final StringThe System property key for the Java home directory.static final StringThe System property key for the Java Runtime Environment specification version.static final StringThe System property key for the architecture name of the operating system.static final StringThe System property key for the name of the operating system.static final StringThe System property key for the user home directory. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionabstract voidbase64ToFile(String string, File file) Turn base64 encodedstringinto afile.abstract voidcleanDirectory(File directory) Cleans a directory recursively.abstract booleancontentEquals(File file1, File file2) Tests whether the contents of two files are equal.abstract voidcopyDirectory(File srcDir, File destDir) Copies a whole directory to a new location, preserving the file dates.abstract voidcopyDirectory(File srcDir, File destDir, FileFilter filter) Copies a filtered directory to a new location preserving the file dates.abstract voidcopyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate) Copies a filtered directory to a new location.abstract voidcopyFields(Object source, Object target) Copies all fields from thesourceto thetargetobject.abstract voidCopies a file to a new location preserving the file date.abstract voidcopyInputStreamToFile(InputStream source, File destination) abstract FileAlterationMonitorcreateFileAlterationMonitor(long interval, FileAlterationObserver... observers) Creates a file alteration monitor with given file alteration observers.abstract FileAlterationObservercreateFileAlterationObserver(String directory, FileFilter fileFilter) Creates a file alteration observer.abstract TailercreateTailer(File file, TailerListener listener, Duration delayDuration, boolean fromEnd) Creates a tailer on a file, i.e., an instance that returns the tail of the file also when new lines are appended.abstract <T extends CharSequence>
TdefaultIfBlank(T str, T defaultStr) Returns either the passed in CharSequence, or if the CharSequence is whitespace, empty ("") or null, the value ofdefaultStr.abstract <T extends CharSequence>
TdefaultIfEmpty(T str, T defaultStr) Returns either the passed in CharSequence, or if the CharSequence is empty or null, the value ofdefaultStr.abstract voiddeleteDirectory(File directory) Deletes a directory recursively.abstract voiddeleteOnExit(File file) Deletes a file or directory on JVM exit, not throwing an exception.abstract booleandeleteQuietly(File file) Deletes a file or directory, not throwing an exception.abstract StringescapeJava(String input) Escapes the characters in aStringusing Java String rules.abstract StringescapeJson(String input) Escapes the characters in aStringusing Json String rules.abstract StringfileToBase64(File file) Turnfileinto a base64 encoded string.abstract FileTries to find the filenameinfolderand its subfolders.abstract voidforceDelete(File file) Deletes a file or directory.static CommonsReturns the Commons instance.Gets the Java home directory as aFile.Returns the Java Runtime Environment specification version.Returns the operating system architecture.Returns the operating system name.abstract FileReturns aFilerepresenting the system temporary directory.abstract StringReturns the path to the system temporary directory.abstract FileReturns aFilerepresenting the user's home directory.abstract StringReturns the path to the user's home directory.Returns theuser.homeSystem Property.abstract booleanReturns whether we are running on Java 9 or newer.abstract booleanisBlank(CharSequence cs) Checks if a CharSequence is empty (""), null or whitespace only.abstract booleanisEmpty(CharSequence cs) Checks if a CharSequence is empty ("") or null.abstract booleanisIpV4Addess(String address) Returns whether the given string is an IPv4 address.abstract booleanReturns whether we are running on Java 1.8.abstract booleanisLinux()Returns whether we are running on Linux.abstract booleanisMac()Returns whether we are running on Mac.abstract booleanChecks if a CharSequence is not empty (""), not null and not whitespace only.abstract booleanisUnix()Returns whether we are running on Unix.abstract booleanReturns whether we are running on windows.abstract byte[]readFileToByteArray(File file) Reads the contents of a file into a byte array.abstract StringreadFileToString(File file) Reads the contents of a file into a String with platform default charset.abstract StringreadFileToString(File file, Charset charset) Reads the contents of a file into a String.readLines(InputStream in, Charset charset) Gets the contents of anInputStreamas a list of Strings, one entry per line, using the specified character encoding.abstract voidRegisters plugin-supplied date-time converters that shall be registered with the platform.abstract StringRemoves a substring only if it is at the end of a source string, otherwise returns the source string.abstract StringremoveStart(String str, String remove) Removes a substring only if it is at the beginning of a source string, otherwise returns the source string.abstract StringreplaceOnce(String text, String searchString, String replacement) Replaces a String with another String inside a larger String, once.abstract voidReverses the order of the given array.static voidsetInstance(Commons commons) Manually sets the instance.abstract byte[]toByteArray(InputStream inputStream) Gets the contents of anInputStreamas abyte[].abstract StringtoString(InputStream in, Charset charset) Gets the contents of anInputStreamas a String using the specified character encoding.abstract StringTurns an object to an readable string, usually using reflection.abstract StringtoStringShortStyle(Object obj) Turns an object to an readable string, usually using reflection.abstract StringunescapeJava(String input) Unescapes any Java literals found in theString.abstract StringunescapeJson(String input) Unescapes any Json literals found in theString.abstract voidwrite(File file, CharSequence data, Charset charset) Writes a CharSequence to a file creating the file if it does not exist.abstract voidwriteByteArrayToFile(File file, byte[] data) Writes a byte array to a file creating the file if it does not exist.abstract voidwriteByteArrayToFile(File file, byte[] data, boolean append) Writes a byte array to a file creating the file if it does not exist.abstract voidwriteStringToFile(File file, String data) Writes a String with platform default charset to a file creating the file if it does not exist.abstract voidwriteStringToFile(File file, String data, Charset charset) Writes a String to a file creating the file if it does not exist.
-
Field Details
-
PROP_JAVA_HOME
The System property key for the Java home directory.- See Also:
-
PROP_USER_HOME
The System property key for the user home directory.- See Also:
-
PROP_OS_NAME
The System property key for the name of the operating system.- See Also:
-
PROP_OS_ARCH
The System property key for the architecture name of the operating system.- See Also:
-
PROP_JAVA_SPEC_VER
The System property key for the Java Runtime Environment specification version.- See Also:
-
instance
-
-
Constructor Details
-
Commons
public Commons()
-
-
Method Details
-
getInstance
Returns the Commons instance.- Returns:
- the instance
-
setInstance
Manually sets the instance. Shall not be needed, but may be required in some tests.- Parameters:
commons- the Commons instance
-
reverse
Reverses the order of the given array. There is no special handling for multi-dimensional arrays. This method does nothing for a null input array.- Parameters:
array- the array to reverse, may be null
-
copyFields
Copies all fields from thesourceto thetargetobject.- Parameters:
source- the source object (may be null, ignored then)target- the target object (may be null, ignored then)- Throws:
ExecutionException- if copying fails
-
escapeJava
Escapes the characters in aStringusing Java String rules. Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)- Parameters:
input- String to escape values in, may be null- Returns:
- String with escaped values, null if null string input
-
unescapeJava
Unescapes any Java literals found in theString.- Parameters:
input- theStringto unescape, may be null- Returns:
- a new unescaped
String, null if null string input
-
escapeJson
Escapes the characters in aStringusing Json String rules. Escapes any values it finds into their Json String form. Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)- Parameters:
input- String to escape values in, may be null- Returns:
- String with escaped values, null if null string input
-
unescapeJson
Unescapes any Json literals found in theString.- Parameters:
input- theStringto unescape, may be null- Returns:
- A new unescaped
String, null if null string input
-
defaultIfBlank
Returns either the passed in CharSequence, or if the CharSequence is whitespace, empty ("") or null, the value ofdefaultStr.- Type Parameters:
T- the specific kind of CharSequence- Parameters:
str- the CharSequence to check, may be nulldefaultStr- the default CharSequence to return if the input is whitespace, empty ("") or null- Returns:
- the passed in CharSequence, or the default
-
defaultIfEmpty
Returns either the passed in CharSequence, or if the CharSequence is empty or null, the value ofdefaultStr.- Type Parameters:
T- the specific kind of CharSequence- Parameters:
str- the CharSequence to check, may be nulldefaultStr- the default CharSequence to return if the input is empty ("") or null- Returns:
- the passed in CharSequence, or the default
-
isBlank
Checks if a CharSequence is empty (""), null or whitespace only.- Parameters:
cs- the CharSequence to check, may be null- Returns:
trueif the CharSequence is null, empty or whitespace only
-
isNotBlank
Checks if a CharSequence is not empty (""), not null and not whitespace only.- Parameters:
cs- the CharSequence to check, may be null- Returns:
trueif the CharSequence is not empty and not null and not whitespace only
-
replaceOnce
Replaces a String with another String inside a larger String, once.- Parameters:
text- text to search and replace in, may be nullsearchString- the String to search for, may be nullreplacement- the String to replace with, may be null- Returns:
- the text with any replacements processed, null if null String input
-
isEmpty
Checks if a CharSequence is empty ("") or null.- Parameters:
cs- the CharSequence to check, may be null- Returns:
trueif the CharSequence is empty or null
-
toString
Turns an object to an readable string, usually using reflection. Uses some default style.- Parameters:
obj- the object- Returns:
- the string representation
-
toStringShortStyle
Turns an object to an readable string, usually using reflection. Uses oktoflow short style.- Parameters:
obj- the object- Returns:
- the string representation
-
removeStart
Removes a substring only if it is at the beginning of a source string, otherwise returns the source string.- Parameters:
str- the source String to search, may be nullremove- the String to search for and remove, may be null- Returns:
- the substring with the string removed if found, null if null String input
-
removeEnd
Removes a substring only if it is at the end of a source string, otherwise returns the source string.- Parameters:
str- the source String to search, may be nullremove- the String to search for and remove, may be null- Returns:
- the substring with the string removed if found, null if null String input
-
getUserHome
Returns theuser.homeSystem Property. User's home directory. -
isWindows
public abstract boolean isWindows()Returns whether we are running on windows.- Returns:
truefor windows,falseelse
-
isLinux
public abstract boolean isLinux()Returns whether we are running on Linux.- Returns:
truefor Linux,falseelse
-
isUnix
public abstract boolean isUnix()Returns whether we are running on Unix.- Returns:
truefor Unix,falseelse
-
isMac
public abstract boolean isMac()Returns whether we are running on Mac.- Returns:
truefor Mac,falseelse
-
isJava1_8
public abstract boolean isJava1_8()Returns whether we are running on Java 1.8.- Returns:
truefor Java 1.8,falseelse
-
isAtLeastJava9
public abstract boolean isAtLeastJava9()Returns whether we are running on Java 9 or newer.- Returns:
truefor Java 9 nor newer,falseelse
-
getOsName
Returns the operating system name.- Returns:
- the operating system name
-
getOsArch
Returns the operating system architecture.- Returns:
- the operating system architecture.
-
getJavaHome
Gets the Java home directory as aFile.- Returns:
- a directory
- Throws:
SecurityException- if a security manager exists and itscheckPropertyAccessmethod doesn't allow access to the specified system property.
-
getJavaSpecificationVersion
Returns the Java Runtime Environment specification version.- Returns:
- the specification version
-
isIpV4Addess
Returns whether the given string is an IPv4 address.- Parameters:
address- the address to validate- Returns:
truefor a valid address,falseelse
-
toString
Gets the contents of anInputStreamas a String using the specified character encoding.- Parameters:
in- theInputStreamto readcharset- the charset to use, null means platform default- Returns:
- the requested String
- Throws:
IOException- if an I/O error occurs
-
readLines
Gets the contents of anInputStreamas a list of Strings, one entry per line, using the specified character encoding.- Parameters:
in- theInputStreamto readcharset- the charset to use, null means platform default- Returns:
- the list of Strings
- Throws:
IOException- if an I/O error occurs
-
toByteArray
Gets the contents of anInputStreamas abyte[].- Parameters:
inputStream- theInputStreamto read.- Returns:
- the requested byte array.
- Throws:
NullPointerException- if the InputStream isnull.IOException- if an I/O error occurs or reading more thanInteger.MAX_VALUEoccurs.
-
deleteQuietly
Deletes a file or directory, not throwing an exception. If file is a directory, delete it and all sub-directories. [convenience]- Parameters:
file- file or directory to delete, may benull- Returns:
trueiffilewas deleted, otherwisefalse
-
forceDelete
Deletes a file or directory. For a directory, delete it and all subdirectories.- Parameters:
file- file or directory to delete- Throws:
FileNotFoundException- if the file was not foundIOException- in case deletion is unsuccessful
-
deleteOnExit
Deletes a file or directory on JVM exit, not throwing an exception. If file is a directory, delete it and all sub-directories. [convenience]- Parameters:
file- file or directory to delete, may benull
-
getTempDirectoryPath
Returns the path to the system temporary directory. [convenience]- Returns:
- the path to the system temporary directory.
-
getTempDirectory
Returns aFilerepresenting the system temporary directory. [convenience]- Returns:
- the system temporary directory.
-
getUserDirectory
Returns aFilerepresenting the user's home directory.- Returns:
- the user's home directory.
-
getUserDirectoryPath
Returns the path to the user's home directory.- Returns:
- the path to the user's home directory.
-
fileToBase64
Turnfileinto a base64 encoded string.- Parameters:
file- the file- Returns:
- the base64 encoded string
- Throws:
IOException- iffilecannot be read
-
base64ToFile
Turn base64 encodedstringinto afile.- Parameters:
string- the base64 encoded stringfile- the file- Throws:
IOException- iffilecannot be written
-
findFile
Tries to find the filenameinfolderand its subfolders.- Parameters:
folder- the folder to searchname- the file name to find- Returns:
- the found file or null for none
-
write
Writes a CharSequence to a file creating the file if it does not exist.- Parameters:
file- the file to writedata- the content to write to the filecharset- the requested charset, null means platform default- Throws:
IOException- in case of an I/O error
-
readFileToString
Reads the contents of a file into a String with platform default charset. Thefileis always closed.- Parameters:
file- the file to read- Returns:
- the file contents
- Throws:
IOException- if an I/O error occurs, including when the file does not exist, is a directory rather than a regular file, or for some other reason why the file cannot be opened for reading.
-
readFileToString
Reads the contents of a file into a String. Thefileis always closed.- Parameters:
file- the file to readcharset- the requested charset, null means platform default- Returns:
- the file contents
- Throws:
IOException- if an I/O error occurs, including when the file does not exist, is a directory rather than a regular file, or for some other reason why the file cannot be opened for reading.
-
cleanDirectory
Cleans a directory recursively.- Parameters:
directory- directory to delete- Throws:
IOException- in case deletion is unsuccessfulIllegalArgumentException- ifdirectoryis not a directory
-
deleteDirectory
Deletes a directory recursively.- Parameters:
directory- directory to delete- Throws:
IOException- in case deletion is unsuccessfulIllegalArgumentException- ifdirectoryis not a directory
-
copyDirectory
Copies a filtered directory to a new location preserving the file dates. This method copies the contents of the specified source directory to within the specified destination directory. The destination directory is created if it does not exist. If the destination directory does exist, then this method merges the source with the destination, with the source taking precedence.- Parameters:
srcDir- an existing directory to copydestDir- the new directoryfilter- the filter to apply, null means copy all directories and files should be the same as the original- Throws:
IllegalArgumentException- ifsrcDirexists but is not a directory, or the source and the destination directory are the sameFileNotFoundException- if the source does not existIOException- if an error occurs, the destination is not writable, or setting the last-modified time didn't succeed
-
copyDirectory
public abstract void copyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate) throws IOException Copies a filtered directory to a new location. This method copies the contents of the specified source directory to within the specified destination directory. The destination directory is created if it does not exist. If the destination directory does exist, then this method merges the source with the destination, with the source taking precedence.- Parameters:
srcDir- an existing directory to copydestDir- the new directoryfilter- the filter to apply, null means copy all directories and filespreserveFileDate- true if the file date of the copy should be the same as the original- Throws:
IllegalArgumentException- ifsrcDirexists but is not a directory, the source and the destination directory are the same, or the destination is not writableFileNotFoundException- if the source does not existIOException- if an error occurs or setting the last-modified time didn't succeed
-
copyDirectory
Copies a whole directory to a new location, preserving the file dates. This method copies the specified directory and all its child directories and files to the specified destination. The destination is the new location and name of the directory. That is, copying /home/bar to /tmp/bang copies the contents of /home/bar into /tmp/bang. It does not create /tmp/bang/bar. The destination directory is created if it does not exist. If the destination directory does exist, then this method merges the source with the destination, with the source taking precedence.- Parameters:
srcDir- an existing directory to copydestDir- the new directory- Throws:
IllegalArgumentException- ifsrcDirexists but is not a directory, the source and the destination directory are the sameFileNotFoundException- if the source does not exist.IOException- if an error occurs, the destination is not writable, or setting the last-modified time didn't succeed
-
copyFile
Copies a file to a new location preserving the file date. This method copies the contents of the specified source file to the specified destination file. The directory holding the destination file is created if it does not exist. If the destination file exists, then this method overwrites it. A symbolic link is resolved before copying so the new file is not a link.- Parameters:
srcFile- an existing file to copydestFile- the new file- Throws:
IOException- if source or destination is invalid, if an error occurs or setting the last-modified time didn't succeed, if the output file length is not the same as the input file length after the copy completes
-
writeStringToFile
Writes a String with platform default charset to a file creating the file if it does not exist. The parent directories of the file will be created if they do not exist.- Parameters:
file- the file to writedata- the content to write to the file- Throws:
IOException- in case of an I/O errorUnsupportedEncodingException- if the encoding is not supported by the VM
-
writeStringToFile
Writes a String to a file creating the file if it does not exist. The parent directories of the file will be created if they do not exist.- Parameters:
file- the file to writedata- the content to write to the filecharset- the charset to use, null means platform default- Throws:
IOException- in case of an I/O errorUnsupportedEncodingException- if the encoding is not supported by the VM
-
readFileToByteArray
Reads the contents of a file into a byte array. Thefileis always closed.- Parameters:
file- the file to read- Returns:
- the file contents
- Throws:
IOException- if an I/O error occurs, including when the file does not exist, is a directory rather than a regular file, or for some other reason why the file cannot be opened for reading.
-
writeByteArrayToFile
Writes a byte array to a file creating the file if it does not exist. The parent directories of the file will be created if they do not exist.- Parameters:
file- the file to write todata- the content to write to the file- Throws:
IOException- in case of an I/O error
-
writeByteArrayToFile
public abstract void writeByteArrayToFile(File file, byte[] data, boolean append) throws IOException Writes a byte array to a file creating the file if it does not exist.- Parameters:
file- the file to write todata- the content to write to the fileappend- iftrue, then bytes will be added to the end of the file rather than overwriting- Throws:
IOException- in case of an I/O error
-
copyInputStreamToFile
Copies bytes from anInputStreamsourceto a filedestination. The directories up todestinationwill be created if they don't already exist.destinationwill be overwritten if it already exists.- Parameters:
source- theInputStreamto copy bytes from, must not be, will be closeddestination- the non-directoryFileto write bytes to (possibly overwriting)- Throws:
IOException- ifdestinationis a directory, ifdestinationcannot be written, ifdestinationneeds creating but can't be, if an IO error occurs during copying
-
contentEquals
Tests whether the contents of two files are equal. This method checks to see if the two files are different lengths or if they point to the same file, before resorting to byte-by-byte comparison of the contents.- Parameters:
file1- the first filefile2- the second file- Returns:
trueif the content of the files are equal or they both don't exist,falseotherwise- Throws:
IllegalArgumentException- when an input is not a file.IOException- If an I/O error occurs.
-
registerDateConverters
public abstract void registerDateConverters()Registers plugin-supplied date-time converters that shall be registered with the platform. -
createTailer
public abstract Tailer createTailer(File file, TailerListener listener, Duration delayDuration, boolean fromEnd) Creates a tailer on a file, i.e., an instance that returns the tail of the file also when new lines are appended.- Parameters:
file- the file to taillistener- the listener being informed on events and new linesdelayDuration- the duration between two checks, null leads to a check every secondfromEnd- defines where to start tailing,truefor the end of the file,falsebeginning- Returns:
- the tailer instance
-
createFileAlterationObserver
public abstract FileAlterationObserver createFileAlterationObserver(String directory, FileFilter fileFilter) Creates a file alteration observer.- Parameters:
directory- the name of the directory to observefileFilter- the file filter or null if none- Returns:
- the alteration observer
-
createFileAlterationMonitor
public abstract FileAlterationMonitor createFileAlterationMonitor(long interval, FileAlterationObserver... observers) Creates a file alteration monitor with given file alteration observers.- Parameters:
interval- the observation interval in msobservers- the observers to apply- Returns:
- the file alteration monitor
-