Class K
java.lang.Object
ch.k43.util.K
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final String
User directory.static final String
Default encoding.static final String
Platform dependent file separator.static final String
Home directory.static final int
JVM major version numberstatic final String
JVM platform.static final String
JVM version name.static final String
Platform dependent line separator.static final String
Platform dependent path separator.static final Calendar
Application start time.static final String
Temporary file directory.static final String
User language.static final String
User name.static final String
Package version number. -
Method Summary
Modifier and TypeMethodDescriptionstatic byte[]
compressZLIB
(byte[] argBuffer) Compress the passed data using the ZLIB algorithm.static byte[]
decodeBase64
(String argBuffer) Return decoded Base64 string.static String
Return decoded CSV string with the delimiter ','static String
Return decoded CSV stringstatic String
decodeJSON
(String argBuffer) Return decoded JSON stringstatic String
Return decoded UTF-8 string.static String
Return decoded XML Stringstatic String
decodeYAML
(String argBuffer) Return decoded YAML stringstatic byte[]
decompressZLIB
(byte[] argBuffer) Decompress the passed data using the ZLIB algorithm.static byte[]
decryptAES256
(byte[] argBuffer, byte[] argSecretKey, byte[] argInitVector) Return decrypted AES-256 buffer (AES/CBC/PKCS5Padding).static Object
deserialize
(String argString) Return base64 decoded and deserialized object.static String
encodeBase64
(byte[] argBuffer) Return encoded buffer to Base64 stringstatic String
Return encoded string for CSV with the delimiter ','static String
Return encoded string for CSVstatic String
encodeJSON
(String argBuffer) Return encoded string for JSON.static String
encodeJSON
(String argBuffer, boolean argEnforceQuotes) Return encoded string for JSON.static String
Return encoded string in UTF-8static String
Encode string for XMLstatic String
encodeYAML
(String argBuffer) Return encoded string for YAML.static String
encodeYAML
(String argBuffer, boolean argEnforceQuotes) Return encoded string for YAML.static byte[]
encryptAES256
(byte[] argBuffer, byte[] argSecretKey, byte[] argInitVector) Return encrypted AES-256 buffer (AES/CBC/PKCS5Padding).static String
formatBytes
(double argSizeInBytes) Convert number of bytes to formatted string (Example: 212 B, 21.23 KiB, 3.00 MiB).static byte[]
generateHash
(String argHashType, byte[] argBuffer) Return compute Hash (MD5, SHA-256, SHA-384, SHA-512, SHA3-256, SHA3-384 or SHA3-512)static Certificate
getCertificate
(String argFileName, char[] argFilePassword, String argKey) Get certificate from JKS keystore file.static String
Deprecated.Use K.CURRENT_DIRECTORY insteadstatic String
getIPAddress
(String argHostname) Return IP address of hostnamestatic int
Return number of processors for the JVM.static long[]
Return JVM memory statistics.static String
Deprecated.Use K.JVM_VERSION_NAME insteadstatic String
Deprecated.Use K.JVM_PLATFORM insteadstatic int
Deprecated.Use K.JVM_MAJOR_VERSION insteadstatic String
Return the last error message.static String[]
Return the last error messages.static String
Deprecated.Use K.LINE_SEPARATOR insteadstatic String
Return local TCP/IP address.static String
Return local TCP/IP host namestatic byte[]
getPasswordHash
(byte[] argPassword, byte[] argSalt, int argIteration) Generate hash from password with salt.static byte[]
getPasswordHash
(String argPassword, String argSalt) Generate hash from password with salt.static PrivateKey
getPrivateKey
(String argFileName, char[] argFilePassword, String argKey, char[] argKeyPassword) Get private key from JKS key store file.static PublicKey
getPublicKey
(String argFileName, char[] argFilePassword, String argKey) Get public key from JKS key store file.static byte[]
getRandomBytes
(int argLength) Return random bytes generated by the SecureRandom class.static int
getRandomInt
(int argMinInt, int argMaxInt) Return random integer between the given range.static Calendar
Deprecated.Use K.START_TIME insteadstatic String
Return current date and time in ISO 8601 format (Example: "2024-02-24T14:12:44.234").static String
getTimeISO8601
(Calendar argDateTime) Return date and time in ISO 8601 format (Example: "2024-02-24T14:12:44.234").static String
Return unique id (Example: 27F1E0F5-186F-48FF-BA46-10E6E4A0FAA0).static String
Return offset from local time zone to UTC as string (Example +02:00).static int
Return difference in number of minutes between UTC and the local time zone.static boolean
Check if object is empty.static boolean
Check whether the passed string contains an integer.static boolean
Check whether the passed string contains an integer and is within the allowed range.static boolean
Check if a new version of the package ch.k43.util is available.static boolean
Check whether the passed string contains a number.static boolean
Check whether the passed string contains a number and is within the allowed range.static Class
<?> Dynamic load a Java classstatic String[]
Return DNS records for the specified record type.static String
replaceParams
(String argData, Object... argObjects) Replace parameter holders "{}" with the passed arguments.static double
round
(double argValue, int argPrecision) Return rounded value.static double
roundSwiss
(double argValue) Return rounded value according to the "Swiss Rounding Rule 5+".static long
runGC()
Manually run garbage collector of Java virtual machine.static void
Save error message.static String
serialize
(Serializable argObject) Return base64 encoded and serialized object.static boolean
stopThread
(Thread argThread) Signal interrupt to thread.static boolean
stopThread
(Thread argThread, int argTimeOutSec) Signal interrupt to thread and wait for its termination.static String
toHex
(byte[] argBytes) Format byte array as hexadecimal string.static String
Format string as hexadecimal string representation.toString()
String representation of object.static void
waitHours
(int argHours) Waits the specified time.static void
waitMilliseconds
(int argMilliseconds) Waits the specified time.static void
waitMinutes
(int argMinutes) Waits the specified time.static void
waitSeconds
(int argSeconds) Waits the specified time.
-
Field Details
-
VERSION
-
START_TIME
Application start time. -
LINE_SEPARATOR
Platform dependent line separator. Examples: "\r", "\n", "\r\n". -
FILE_SEPARATOR
Platform dependent file separator. Examples: "/", "\". -
PATH_SEPARATOR
Platform dependent path separator. Examples: ":", ";". -
USER_NAME
User name. Example: "joesmith". -
CURRENT_DIRECTORY
User directory. The returned string is terminated with the platform dependent file separator. -
HOME_DIRECTORY
Home directory. The returned string is terminated with the platform dependent file separator. -
TEMP_DIRECTORY
Temporary file directory. The returned string is terminated with the platform dependent file separator. -
USER_LANGUAGE
User language. Examples: "en", "fr", "de". -
DEFAULT_ENCODING
Default encoding. Example: "UTF-8". -
JVM_MAJOR_VERSION
public static final int JVM_MAJOR_VERSIONJVM major version number -
JVM_VERSION_NAME
JVM version name. Example: "Java HotSpot(TM) 64-Bit Server VM - Oracle Corporation" -
JVM_PLATFORM
JVM platform. Example: "Mac OS X Version 15.3.1/aarch64"
-
-
Method Details
-
compressZLIB
public static byte[] compressZLIB(byte[] argBuffer) Compress the passed data using the ZLIB algorithm.- Parameters:
argBuffer
- Data to be compressed- Returns:
- Compressed data
- Since:
- 2024.08.11
-
decodeBase64
Return decoded Base64 string.- Parameters:
argBuffer
- Base64 string to decode- Returns:
- byte[] Decoded string
-
decodeCSV
-
decodeCSV
-
decodeJSON
-
decodeURL
-
decodeXML
-
decodeYAML
-
decompressZLIB
public static byte[] decompressZLIB(byte[] argBuffer) Decompress the passed data using the ZLIB algorithm.- Parameters:
argBuffer
- Data to be decompressed- Returns:
- Decompressed data or empty array for for errors
- Since:
- 2024.08.11
-
decryptAES256
public static byte[] decryptAES256(byte[] argBuffer, byte[] argSecretKey, byte[] argInitVector) Return decrypted AES-256 buffer (AES/CBC/PKCS5Padding).Note: Before being used as the decryption key, the passed secret key is hashed with SHA-256 to always create a 256 bit key.
Example: byte[] clearText = "Some datq to be encrypted".getBytes(); byte[] secureKey = "SomeSecureKey".getBytes(); byte[] iv = K.getRandomBytes(16); byte[] encrBuffer = K.encryptAES256(clearText, secureKey, iv); byte[] decrBuffer = K.decryptAES256(encrBuffer, secureKey, iv);
- Parameters:
argBuffer
- Encrypted bufferargSecretKey
- Secret key for decryptionargInitVector
- Initialization vector (16 bytes)- Returns:
- byte[] Decrypted buffer
-
deserialize
-
encodeBase64
Return encoded buffer to Base64 string- Parameters:
argBuffer
- Buffer to convert- Returns:
- String Base64 encoded string
-
encodeCSV
-
encodeCSV
-
encodeJSON
-
encodeJSON
Return encoded string for JSON.- Parameters:
argBuffer
- String to be encodedargEnforceQuotes
- Flag to enforce surrounding quotes (required for JSON keys, optional for JSON boolean/numeric values)- Returns:
- String Encoded string
- Since:
- 2024.06.28
-
encodeURL
-
encodeXML
-
encodeYAML
-
encodeYAML
Return encoded string for YAML. Note: Strings are always enclosed with double quotes.- Parameters:
argBuffer
- String to be encodedargEnforceQuotes
- Flag to enforce surrounding quotes (optional for YAML values)- Returns:
- String Encoded string
- Since:
- 2024.09.14
-
encryptAES256
public static byte[] encryptAES256(byte[] argBuffer, byte[] argSecretKey, byte[] argInitVector) Return encrypted AES-256 buffer (AES/CBC/PKCS5Padding).Note: Before being used as the encryption key, the passed secret key is hashed with SHA-256 to always create a 256 bit key.
Example: byte[] clearText = "Some data to be encrypted".getBytes(); byte[] secureKey = "SomeSecureKey".getBytes(); byte[] iv = K.getRandomBytes(16); byte[] encrBuffer = K.encryptAES256(clearText, secureKey, iv); byte[] decrBuffer = K.decryptAES256(encrBuffer, secureKey, iv);
- Parameters:
argBuffer
- Clear text bufferargSecretKey
- Secret key for encryptionargInitVector
- Initialization vector (16 bytes)- Returns:
- byte[] Encrypted buffer or empty array
-
formatBytes
Convert number of bytes to formatted string (Example: 212 B, 21.23 KiB, 3.00 MiB).- Parameters:
argSizeInBytes
- Number of bytes to be formatted- Returns:
- String with formatted size (Example 12.03 GiB)
- Since:
- 2024.06.23
-
generateHash
Return compute Hash (MD5, SHA-256, SHA-384, SHA-512, SHA3-256, SHA3-384 or SHA3-512)- Parameters:
argHashType
- Hash algorithmargBuffer
- argBuffer to hash- Returns:
- byte[] Hashed data
-
getCertificate
Get certificate from JKS keystore file.- Parameters:
argFileName
- JKS file nameargFilePassword
- JKS file passwordargKey
- Key (alias) name- Returns:
- Certificate or null for errors
- Since:
- 2024.12.06
-
getCurrentDir
Deprecated.Use K.CURRENT_DIRECTORY insteadReturn current directory.- Returns:
- Current directory, e.g. "/Users/johnsmith"
- Since:
- 2024.05.24
-
getIPAddress
-
getJVMCPUCount
public static int getJVMCPUCount()Return number of processors for the JVM. The number of processors may change during the applications lifetime.- Returns:
- Number of processors
-
getJVMMemStats
public static long[] getJVMMemStats()Return JVM memory statistics.Note: The returned array has the following values:
[0] = Maximum heap size in bytes
[1] = Current heap size in bytes
[2] = Used heap size in bytes
[3] = Free heap size in bytes- Returns:
- JVM memory statistics
-
getJVMName
Deprecated.Use K.JVM_VERSION_NAME insteadReturn JVM name (Example "OpenJDK 64-Bit Server VM - Eclipse Adoptium").- Returns:
- String JVM version number and vendor
-
getJVMPlatform
Deprecated.Use K.JVM_PLATFORM insteadReturn JVM platform (Example: "Mac OS X (Version 14.5/aarch64)").- Returns:
- String JVM platform
-
getJVMVersion
Deprecated.Use K.JVM_MAJOR_VERSION insteadReturn JVM major version (Example: 1.9.x as 9, 12.4 as 12).- Returns:
- int Major version number of JVM runtime or 0 for errors
-
getLastError
Return the last error message.- Returns:
- Last error message or null
- Since:
- 2024.12.08
-
getLastErrors
Return the last error messages.- Returns:
- Array of error messages
- Since:
- 2024.12.08
-
getLineSeparator
Deprecated.Use K.LINE_SEPARATOR insteadGet line separator- Returns:
- String Platform dependent line separator (\r, \n or \r\n)
-
getLocalHostAddress
-
getLocalHostName
-
getPasswordHash
public static byte[] getPasswordHash(byte[] argPassword, byte[] argSalt, int argIteration) Generate hash from password with salt. The hashing is repeated for the number of iterations with SHA3-512(password + salt).- Parameters:
argPassword
- Password to be hashedargSalt
- Salt to be added to password (should be at least 16 bytes and unique for each password)argIteration
- Number of hash cycles (recommended between 100'000 and 1'000'000)- Returns:
- Hashed password (64 bytes)
- Since:
- 2025.02.15
-
getPasswordHash
Generate hash from password with salt. The hashing is repeated 500'000 times with SHA3-512(password + salt).- Parameters:
argPassword
- Password to be hashedargSalt
- Salt to be added to password (should be at least 16 bytes and unique for each password)- Returns:
- Hashed password (64 bytes)
- Since:
- 2025.02.15
-
getPrivateKey
public static PrivateKey getPrivateKey(String argFileName, char[] argFilePassword, String argKey, char[] argKeyPassword) Get private key from JKS key store file.- Parameters:
argFileName
- JKS file nameargFilePassword
- JKS file passwordargKey
- Key (alias) nameargKeyPassword
- Key password- Returns:
- Private key or null for errors
- Since:
- 2024.12.06
-
getPublicKey
-
getRandomBytes
public static byte[] getRandomBytes(int argLength) Return random bytes generated by the SecureRandom class.- Parameters:
argLength
- Number of bytes to be generated- Returns:
- byte[] Generated bytes
-
getRandomInt
public static int getRandomInt(int argMinInt, int argMaxInt) Return random integer between the given range.- Parameters:
argMinInt
- Lowest possible integer (inclusive)argMaxInt
- Highest possible integer (exclusive)- Returns:
- Random integer
- Since:
- 2024.05.29
-
getStartTime
Deprecated.Use K.START_TIME insteadGet application start time and date.- Returns:
- Start date and time
- Since:
- 2024.05.24
-
getTimeISO8601
Return current date and time in ISO 8601 format (Example: "2024-02-24T14:12:44.234").- Returns:
- String ISO 8601 date/time
-
getTimeISO8601
-
getUniqueID
Return unique id (Example: 27F1E0F5-186F-48FF-BA46-10E6E4A0FAA0).- Returns:
- Unique id
- Since:
- 2024.05.24
-
getUTCOffsetAsString
Return offset from local time zone to UTC as string (Example +02:00).- Returns:
- String with zone offset
-
getUTCOffsetMin
public static int getUTCOffsetMin()Return difference in number of minutes between UTC and the local time zone.- Returns:
- Difference in minutes
-
isEmpty
Check if object is empty.- Parameters:
argObject
- Object to test for emptiness- Returns:
- True if object is empty (null or no elements), false otherwise
- Since:
- 2024.05.20
-
isInteger
Check whether the passed string contains an integer.- Parameters:
argString
- String to be tested- Returns:
- True if number, false otherwise
- Since:
- 2024.08.26
-
isInteger
Check whether the passed string contains an integer and is within the allowed range.- Parameters:
argString
- String to be testedargMinimum
- Minimum allowed valueargMaximum
- Maximum allowed value- Returns:
- True if number, false otherwise
- Since:
- 2024.08.26
-
isNewVersionAvailable
public static boolean isNewVersionAvailable()Check if a new version of the package ch.k43.util is available. The check is done by fetching https://k43.ch/java-util/version.txt and checking the result against the active package version.- Returns:
- true (new version available) or false (current version up-to-date or website is not reachable).
- Since:
- 2024.12.23
-
isNumber
Check whether the passed string contains a number.- Parameters:
argString
- String to be tested- Returns:
- True if number, false otherwise
- Since:
- 2024.06.28
-
isNumber
Check whether the passed string contains a number and is within the allowed range.- Parameters:
argString
- String to be testedargMinimum
- Minimum allowed valueargMaximum
- Maximum allowed value- Returns:
- True if number, false otherwise
- Since:
- 2024.09.12
-
loadClass
-
queryDNS
-
replaceParams
-
round
public static double round(double argValue, int argPrecision) Return rounded value.- Parameters:
argValue
- Value to be roundedargPrecision
- Number of decimal digits- Returns:
- double Rounded value
- Since:
- 2025.08.10
-
roundSwiss
public static double roundSwiss(double argValue) Return rounded value according to the "Swiss Rounding Rule 5+". Note: The calculation is equivalent to Math.round(value * 20.0) / 20.0 and is mainly used by Swiss financial applications.
Examples:
- Values between 0.0000 and 0.0249 are rounded down to 0.00
- Values between 0.0250 and 0.0749 are rounded to 0.05
- Values between 0.0750 and 0.0999 are rounded up to 0.10- Parameters:
argValue
- Value to be rounded- Returns:
- double Rounded value
-
runGC
public static long runGC()Manually run garbage collector of Java virtual machine. Note: The manual execution of the garbage collector is not needed under normal operation.- Returns:
- Number of bytes reclaimed
-
saveError
Save error message.- Parameters:
argMessage
- Error Message- Since:
- 2025.02.02
- See Also:
-
serialize
Return base64 encoded and serialized object.- Parameters:
argObject
- Object to serialize and encode- Returns:
- Base64 string
- Since:
- 2024.08.22
-
stopThread
Signal interrupt to thread.- Parameters:
argThread
- Thread to interrupt for termination- Returns:
- True for success, false otherwise
- Since:
- 2024.08.29
-
stopThread
Signal interrupt to thread and wait for its termination.- Parameters:
argThread
- Thread to terminateargTimeOutSec
- Number of seconds to wait for thread termination (0 to 60)- Returns:
- True for success, false otherwise
- Since:
- 2024.08.29
-
toHex
Format byte array as hexadecimal string.- Parameters:
argBytes
- Byte array- Returns:
- Hexadecimal string
- Since:
- 2024.05.24
-
toHex
-
waitHours
public static void waitHours(int argHours) Waits the specified time.- Parameters:
argHours
- Number of hours to wait
-
waitMilliseconds
public static void waitMilliseconds(int argMilliseconds) Waits the specified time.- Parameters:
argMilliseconds
- Number of milliseconds to wait
-
waitMinutes
public static void waitMinutes(int argMinutes) Waits the specified time.- Parameters:
argMinutes
- Number of minutes to wait
-
waitSeconds
public static void waitSeconds(int argSeconds) Waits the specified time.- Parameters:
argSeconds
- Number of seconds to wait
-
toString
-