Class K

java.lang.Object
ch.k43.util.K

public class K extends Object
Static class with many utility methods.
  • Field Details

    • VERSION

      public static final String VERSION
      Package version number. Example: "2025.01.24".
      See Also:
    • START_TIME

      public static final Calendar START_TIME
      Application start time.
    • LINE_SEPARATOR

      public static final String LINE_SEPARATOR
      Platform dependent line separator. Examples: "\r", "\n", "\r\n".
    • FILE_SEPARATOR

      public static final String FILE_SEPARATOR
      Platform dependent file separator. Examples: "/", "\".
    • PATH_SEPARATOR

      public static final String PATH_SEPARATOR
      Platform dependent path separator. Examples: ":", ";".
    • USER_NAME

      public static final String USER_NAME
      User name. Example: "joesmith".
    • CURRENT_DIRECTORY

      public static final String CURRENT_DIRECTORY
      User directory. The returned string is terminated with the platform dependent file separator.
    • HOME_DIRECTORY

      public static final String HOME_DIRECTORY
      Home directory. The returned string is terminated with the platform dependent file separator.
    • TEMP_DIRECTORY

      public static final String TEMP_DIRECTORY
      Temporary file directory. The returned string is terminated with the platform dependent file separator.
    • USER_LANGUAGE

      public static final String USER_LANGUAGE
      User language. Examples: "en", "fr", "de".
    • DEFAULT_ENCODING

      public static final String DEFAULT_ENCODING
      Default encoding. Example: "UTF-8".
    • JVM_MAJOR_VERSION

      public static final int JVM_MAJOR_VERSION
      JVM major version number
    • JVM_VERSION_NAME

      public static final String JVM_VERSION_NAME
      JVM version name. Example: "Java HotSpot(TM) 64-Bit Server VM - Oracle Corporation"
    • JVM_PLATFORM

      public static final String 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

      public static byte[] decodeBase64(String argBuffer)
      Return decoded Base64 string.
      Parameters:
      argBuffer - Base64 string to decode
      Returns:
      byte[] Decoded string
    • decodeCSV

      public static String decodeCSV(String argBuffer)
      Return decoded CSV string with the delimiter ','
      Parameters:
      argBuffer - String to be decoded
      Returns:
      String Decoded string or null
      Since:
      2024.06.15
    • decodeCSV

      public static String decodeCSV(String argBuffer, char argDelimiter)
      Return decoded CSV string
      Parameters:
      argBuffer - String to be decoded
      argDelimiter - Delimiter character (Example: ',')
      Returns:
      String Decoded string
      Since:
      2024.06.15
    • decodeJSON

      public static String decodeJSON(String argBuffer)
      Return decoded JSON string
      Parameters:
      argBuffer - String to be decoded
      Returns:
      String Decoded string or null
      Since:
      2024.06.15
    • decodeURL

      public static String decodeURL(String argBuffer)
      Return decoded UTF-8 string.
      Parameters:
      argBuffer - is the String to be decoded
      Returns:
      String Decoded string
    • decodeXML

      public static String decodeXML(String argBuffer)
      Return decoded XML String
      Parameters:
      argBuffer - String to be decoded
      Returns:
      String Decoded string
      Since:
      2024.06.16
    • decodeYAML

      public static String decodeYAML(String argBuffer)
      Return decoded YAML string
      Parameters:
      argBuffer - String to be decoded
      Returns:
      String Decoded string or null
      Since:
      2024.09.14
    • 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 buffer
      argSecretKey - Secret key for decryption
      argInitVector - Initialization vector (16 bytes)
      Returns:
      byte[] Decrypted buffer
    • deserialize

      public static Object deserialize(String argString)
      Return base64 decoded and deserialized object.
      Parameters:
      argString - Object to decode and deserialize
      Returns:
      Object or null for errors
      Since:
      2024.08.22
    • encodeBase64

      public static String encodeBase64(byte[] argBuffer)
      Return encoded buffer to Base64 string
      Parameters:
      argBuffer - Buffer to convert
      Returns:
      String Base64 encoded string
    • encodeCSV

      public static String encodeCSV(String argBuffer)
      Return encoded string for CSV with the delimiter ','
      Parameters:
      argBuffer - String to be encoded
      Returns:
      String Encoded string or null
      Since:
      2024.06.15
    • encodeCSV

      public static String encodeCSV(String argBuffer, char argDelimiter)
      Return encoded string for CSV
      Parameters:
      argBuffer - String to be encoded
      argDelimiter - Delimiter character (Example: ',')
      Returns:
      String Encoded string
      Since:
      2024.06.15
    • encodeJSON

      public static String encodeJSON(String argBuffer)
      Return encoded string for JSON. The returned string is always enclosed in double quotes.
      Parameters:
      argBuffer - String to be encoded
      Returns:
      String Encoded string
      Since:
      2024.06.15
      See Also:
    • encodeJSON

      public static String encodeJSON(String argBuffer, boolean argEnforceQuotes)
      Return encoded string for JSON.
      Parameters:
      argBuffer - String to be encoded
      argEnforceQuotes - Flag to enforce surrounding quotes (required for JSON keys, optional for JSON boolean/numeric values)
      Returns:
      String Encoded string
      Since:
      2024.06.28
    • encodeURL

      public static String encodeURL(String argBuffer)
      Return encoded string in UTF-8
      Parameters:
      argBuffer - is the String to be encoded
      Returns:
      String Encoded stringl
    • encodeXML

      public static String encodeXML(String argBuffer)
      Encode string for XML
      Parameters:
      argBuffer - String to be encoded
      Returns:
      String Encoded string
      Since:
      2024.06.16
    • encodeYAML

      public static String encodeYAML(String argBuffer)
      Return encoded string for YAML. The returned string is always enclosed in double quotes.
      Parameters:
      argBuffer - String to be encoded
      Returns:
      String Encoded string
      Since:
      2024.09.14
      See Also:
    • encodeYAML

      public static String encodeYAML(String argBuffer, boolean argEnforceQuotes)
      Return encoded string for YAML. Note: Strings are always enclosed with double quotes.
      Parameters:
      argBuffer - String to be encoded
      argEnforceQuotes - 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 buffer
      argSecretKey - Secret key for encryption
      argInitVector - Initialization vector (16 bytes)
      Returns:
      byte[] Encrypted buffer or empty array
    • formatBytes

      public static String formatBytes(double argSizeInBytes)
      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

      public static byte[] generateHash(String argHashType, byte[] argBuffer)
      Return compute Hash (MD5, SHA-256, SHA-384, SHA-512, SHA3-256, SHA3-384 or SHA3-512)
      Parameters:
      argHashType - Hash algorithm
      argBuffer - argBuffer to hash
      Returns:
      byte[] Hashed data
    • getCertificate

      public static Certificate getCertificate(String argFileName, char[] argFilePassword, String argKey)
      Get certificate from JKS keystore file.
      Parameters:
      argFileName - JKS file name
      argFilePassword - JKS file password
      argKey - Key (alias) name
      Returns:
      Certificate or null for errors
      Since:
      2024.12.06
    • getCurrentDir

      @Deprecated public static String getCurrentDir()
      Deprecated.
      Use K.CURRENT_DIRECTORY instead
      Return current directory.
      Returns:
      Current directory, e.g. "/Users/johnsmith"
      Since:
      2024.05.24
    • getIPAddress

      public static String getIPAddress(String argHostname)
      Return IP address of hostname
      Parameters:
      argHostname - Hostname
      Returns:
      String IP address or null
    • 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 public static String getJVMName()
      Deprecated.
      Use K.JVM_VERSION_NAME instead
      Return JVM name (Example "OpenJDK 64-Bit Server VM - Eclipse Adoptium").
      Returns:
      String JVM version number and vendor
    • getJVMPlatform

      @Deprecated public static String getJVMPlatform()
      Deprecated.
      Use K.JVM_PLATFORM instead
      Return JVM platform (Example: "Mac OS X (Version 14.5/aarch64)").
      Returns:
      String JVM platform
    • getJVMVersion

      @Deprecated public static int getJVMVersion()
      Deprecated.
      Use K.JVM_MAJOR_VERSION instead
      Return 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

      public static String getLastError()
      Return the last error message.
      Returns:
      Last error message or null
      Since:
      2024.12.08
    • getLastErrors

      public static String[] getLastErrors()
      Return the last error messages.
      Returns:
      Array of error messages
      Since:
      2024.12.08
    • getLineSeparator

      @Deprecated public static String getLineSeparator()
      Deprecated.
      Use K.LINE_SEPARATOR instead
      Get line separator
      Returns:
      String Platform dependent line separator (\r, \n or \r\n)
    • getLocalHostAddress

      public static String getLocalHostAddress()
      Return local TCP/IP address.
      Returns:
      IP address
    • getLocalHostName

      public static String getLocalHostName()
      Return local TCP/IP host name
      Returns:
      Host name
    • 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 hashed
      argSalt - 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

      public static byte[] getPasswordHash(String argPassword, String argSalt)
      Generate hash from password with salt. The hashing is repeated 500'000 times with SHA3-512(password + salt).
      Parameters:
      argPassword - Password to be hashed
      argSalt - 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 name
      argFilePassword - JKS file password
      argKey - Key (alias) name
      argKeyPassword - Key password
      Returns:
      Private key or null for errors
      Since:
      2024.12.06
    • getPublicKey

      public static PublicKey getPublicKey(String argFileName, char[] argFilePassword, String argKey)
      Get public key from JKS key store file.
      Parameters:
      argFileName - JKS file name
      argFilePassword - JKS file password
      argKey - Key (alias) name
      Returns:
      Public key or null for errors
      Since:
      2024.12.07
    • 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 public static Calendar getStartTime()
      Deprecated.
      Use K.START_TIME instead
      Get application start time and date.
      Returns:
      Start date and time
      Since:
      2024.05.24
    • getTimeISO8601

      public static String getTimeISO8601()
      Return current date and time in ISO 8601 format (Example: "2024-02-24T14:12:44.234").
      Returns:
      String ISO 8601 date/time
    • getTimeISO8601

      public static String getTimeISO8601(Calendar argDateTime)
      Return date and time in ISO 8601 format (Example: "2024-02-24T14:12:44.234").
      Parameters:
      argDateTime - Date/time
      Returns:
      String ISO 8601 date/time
    • getUniqueID

      public static String getUniqueID()
      Return unique id (Example: 27F1E0F5-186F-48FF-BA46-10E6E4A0FAA0).
      Returns:
      Unique id
      Since:
      2024.05.24
    • getUTCOffsetAsString

      public static String 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

      public static boolean isEmpty(Object argObject)
      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

      public static boolean isInteger(String argString)
      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

      public static boolean isInteger(String argString, int argMinimum, int argMaximum)
      Check whether the passed string contains an integer and is within the allowed range.
      Parameters:
      argString - String to be tested
      argMinimum - Minimum allowed value
      argMaximum - 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

      public static boolean isNumber(String argString)
      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

      public static boolean isNumber(String argString, double argMinimum, double argMaximum)
      Check whether the passed string contains a number and is within the allowed range.
      Parameters:
      argString - String to be tested
      argMinimum - Minimum allowed value
      argMaximum - Maximum allowed value
      Returns:
      True if number, false otherwise
      Since:
      2024.09.12
    • loadClass

      public static Class<?> loadClass(String argClassName)
      Dynamic load a Java class
      Parameters:
      argClassName - Java class name, e.g ch.k43.util.KSocketServerSample
      Returns:
      Class Loaded Java class or null for errors
    • queryDNS

      public static String[] queryDNS(String argDNSRecordType, String argMailDomain)
      Return DNS records for the specified record type.
      Parameters:
      argDNSRecordType - DNS record type (MX, A, etc.)
      argMailDomain - Domain to query
      Returns:
      Array with matching DNS records
      Since:
      2024.05.17
    • replaceParams

      public static String replaceParams(String argData, Object... argObjects)
      Replace parameter holders "{}" with the passed arguments.
      Parameters:
      argData - Message text
      argObjects - Data to be inserted
      Returns:
      Formatted string
      Since:
      2025.01.20
    • round

      public static double round(double argValue, int argPrecision)
      Return rounded value.
      Parameters:
      argValue - Value to be rounded
      argPrecision - 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

      public static void saveError(String argMessage)
      Save error message.
      Parameters:
      argMessage - Error Message
      Since:
      2025.02.02
      See Also:
    • serialize

      public static String serialize(Serializable argObject)
      Return base64 encoded and serialized object.
      Parameters:
      argObject - Object to serialize and encode
      Returns:
      Base64 string
      Since:
      2024.08.22
    • stopThread

      public static boolean stopThread(Thread argThread)
      Signal interrupt to thread.
      Parameters:
      argThread - Thread to interrupt for termination
      Returns:
      True for success, false otherwise
      Since:
      2024.08.29
    • stopThread

      public static boolean stopThread(Thread argThread, int argTimeOutSec)
      Signal interrupt to thread and wait for its termination.
      Parameters:
      argThread - Thread to terminate
      argTimeOutSec - Number of seconds to wait for thread termination (0 to 60)
      Returns:
      True for success, false otherwise
      Since:
      2024.08.29
    • toHex

      public static String toHex(byte[] argBytes)
      Format byte array as hexadecimal string.
      Parameters:
      argBytes - Byte array
      Returns:
      Hexadecimal string
      Since:
      2024.05.24
    • toHex

      public static String toHex(String argString)
      Format string as hexadecimal string representation.
      Parameters:
      argString - String to be formatted
      Returns:
      Hexadecimal string
      Since:
      2024.05.24
    • 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

      public String toString()
      String representation of object.
      Overrides:
      toString in class Object
      Since:
      2024.08.23