Package oshi.util

Class ParseUtil

java.lang.Object
oshi.util.ParseUtil

@ThreadSafe public final class ParseUtil extends Object
String parsing utility.
  • Field Details

    • whitespacesColonWhitespace

      public static final Pattern whitespacesColonWhitespace
      Constant whitespacesColonWhitespace
    • whitespaces

      public static final Pattern whitespaces
      Constant whitespaces
    • notDigits

      public static final Pattern notDigits
      Constant notDigits
    • startWithNotDigits

      public static final Pattern startWithNotDigits
      Constant startWithNotDigits
    • slash

      public static final Pattern slash
      Constant forwardSlash
  • Method Details

    • parseHertz

      public static long parseHertz(String hertz)
      Parse hertz from a string, eg. "2.00MHz" is 2000000L.
      Parameters:
      hertz - Hertz size.
      Returns:
      Long Hertz value or -1 if not parseable.
    • parseLastInt

      public static int parseLastInt(String s, int i)
      Parse the last element of a space-delimited string to a value
      Parameters:
      s - The string to parse
      i - Default integer if not parsable
      Returns:
      value or the given default if not parsable
    • parseLastLong

      public static long parseLastLong(String s, long li)
      Parse the last element of a space-delimited string to a value
      Parameters:
      s - The string to parse
      li - Default long integer if not parsable
      Returns:
      value or the given default if not parsable
    • parseLastDouble

      public static double parseLastDouble(String s, double d)
      Parse the last element of a space-delimited string to a value
      Parameters:
      s - The string to parse
      d - Default double if not parsable
      Returns:
      value or the given default if not parsable
    • parseLastString

      public static String parseLastString(String s)
      Parse the last element of a space-delimited string to a string
      Parameters:
      s - The string to parse
      Returns:
      last space-delimited element
    • byteArrayToHexString

      public static String byteArrayToHexString(byte[] bytes)
      Parse a byte array into a string of hexadecimal digits including all array bytes as digits
      Parameters:
      bytes - The byte array to represent
      Returns:
      A string of hex characters corresponding to the bytes. The string is upper case.
    • hexStringToByteArray

      public static byte[] hexStringToByteArray(String digits)
      Parse a string of hexadecimal digits into a byte array
      Parameters:
      digits - The string to be parsed
      Returns:
      a byte array with each pair of characters converted to a byte, or empty array if the string is not valid hex
    • asciiStringToByteArray

      public static byte[] asciiStringToByteArray(String text, int length)
      Parse a human readable ASCII string into a byte array, truncating or padding with zeros (if necessary) so the array has the specified length.
      Parameters:
      text - The string to be parsed
      length - Length of the returned array.
      Returns:
      A byte array of specified length, with each of the first length characters converted to a byte. If length is longer than the provided string length, will be filled with zeroes.
    • longToByteArray

      public static byte[] longToByteArray(long value, int valueSize, int length)
      Convert a long value to a byte array using Big Endian, truncating or padding with zeros (if necessary) so the array has the specified length.
      Parameters:
      value - The value to be converted
      valueSize - Number of bytes representing the value
      length - Number of bytes to return
      Returns:
      A byte array of specified length representing the long in the first valueSize bytes
    • strToLong

      public static long strToLong(String str, int size)
      Convert a string to an integer representation.
      Parameters:
      str - A human readable ASCII string
      size - Number of characters to convert to the long. May not exceed 8.
      Returns:
      An integer representing the string where each character is treated as a byte
    • byteArrayToLong

      public static long byteArrayToLong(byte[] bytes, int size)
      Convert a byte array to its (long) integer representation assuming big endian ordering.
      Parameters:
      bytes - An array of bytes no smaller than the size to be converted
      size - Number of bytes to convert to the long. May not exceed 8.
      Returns:
      A long integer representing the byte array
    • byteArrayToLong

      public static long byteArrayToLong(byte[] bytes, int size, boolean bigEndian)
      Convert a byte array to its (long) integer representation in the specified endianness.
      Parameters:
      bytes - An array of bytes no smaller than the size to be converted
      size - Number of bytes to convert to the long. May not exceed 8.
      bigEndian - True to parse big-endian, false to parse little-endian
      Returns:
      An long integer representing the byte array
    • byteArrayToFloat

      public static float byteArrayToFloat(byte[] bytes, int size, int fpBits)
      Convert a byte array to its floating point representation.
      Parameters:
      bytes - An array of bytes no smaller than the size to be converted
      size - Number of bytes to convert to the float. May not exceed 8.
      fpBits - Number of bits representing the decimal
      Returns:
      A float; the integer portion representing the byte array as an integer shifted by the bits specified in fpBits; with the remaining bits used as a decimal
    • unsignedIntToLong

      public static long unsignedIntToLong(int unsignedValue)
      Convert an unsigned integer to a long value. The method assumes that all bits in the specified integer value are 'data' bits, including the most-significant bit which Java normally considers a sign bit. The method must be used only when it is certain that the integer value represents an unsigned integer, for example when the integer is returned by JNA library in a structure which holds unsigned integers.
      Parameters:
      unsignedValue - The unsigned integer value to convert.
      Returns:
      The unsigned integer value widened to a long.
    • unsignedLongToSignedLong

      public static long unsignedLongToSignedLong(long unsignedValue)
      Convert an unsigned long to a signed long value by stripping the sign bit. This method "rolls over" long values greater than the max value but ensures the result is never negative.
      Parameters:
      unsignedValue - The unsigned long value to convert.
      Returns:
      The signed long value.
    • hexStringToString

      public static String hexStringToString(String hexString)
      Parses a string of hex digits to a string where each pair of hex digits represents an ASCII character
      Parameters:
      hexString - A sequence of hex digits
      Returns:
      The corresponding string if valid hex; otherwise the original hexString
    • parseIntOrDefault

      public static int parseIntOrDefault(String s, int defaultInt)
      Attempts to parse a string to an int. If it fails, returns the default
      Parameters:
      s - The string to parse
      defaultInt - The value to return if parsing fails
      Returns:
      The parsed int, or the default if parsing failed
    • parseLongOrDefault

      public static long parseLongOrDefault(String s, long defaultLong)
      Attempts to parse a string to a long. If it fails, returns the default
      Parameters:
      s - The string to parse
      defaultLong - The value to return if parsing fails
      Returns:
      The parsed long, or the default if parsing failed
    • parseUnsignedLongOrDefault

      public static long parseUnsignedLongOrDefault(String s, long defaultLong)
      Attempts to parse a string to an "unsigned" long. If it fails, returns the default
      Parameters:
      s - The string to parse
      defaultLong - The value to return if parsing fails
      Returns:
      The parsed long containing the same 64 bits that an unsigned long would contain (which may produce a negative value)
    • parseDoubleOrDefault

      public static double parseDoubleOrDefault(String s, double defaultDouble)
      Attempts to parse a string to a double. If it fails, returns the default
      Parameters:
      s - The string to parse
      defaultDouble - The value to return if parsing fails
      Returns:
      The parsed double, or the default if parsing failed
    • parseDHMSOrDefault

      public static long parseDHMSOrDefault(String s, long defaultLong)
      Attempts to parse a string of the form [DD-[hh:]]mm:ss[.ddd] to a number of milliseconds. If it fails, returns the default.
      Parameters:
      s - The string to parse
      defaultLong - The value to return if parsing fails
      Returns:
      The parsed number of seconds, or the default if parsing fails
    • parseUuidOrDefault

      public static String parseUuidOrDefault(String s, String defaultStr)
      Attempts to parse a UUID. If it fails, returns the default.
      Parameters:
      s - The string to parse
      defaultStr - The value to return if parsing fails
      Returns:
      The parsed UUID, or the default if parsing fails
    • getSingleQuoteStringValue

      public static String getSingleQuoteStringValue(String line)
      Parses a string key = 'value' (string)
      Parameters:
      line - The entire string
      Returns:
      the value contained between single tick marks
    • getDoubleQuoteStringValue

      public static String getDoubleQuoteStringValue(String line)
      Parse a string key = "value" (string)
      Parameters:
      line - the entire string
      Returns:
      the value contained between double tick marks
    • getStringBetween

      public static String getStringBetween(String line, char c)
      Gets a value between two characters having multiple same characters between them. Examples :
      • "name = 'James Gosling's Java'" returns "James Gosling's Java"
      • "pci.name = 'Realtek AC'97 Audio Device'" returns "Realtek AC'97 Audio Device"
      Parameters:
      line - The "key-value" pair line.
      c - The Trailing And Leading characters of the string line
      Returns:
      : The value having the characters between them.
    • getFirstIntValue

      public static int getFirstIntValue(String line)
      Parses a string such as "10.12.2" or "key = 1 (0x1) (int)" to find the integer value of the first set of one or more consecutive digits
      Parameters:
      line - The entire string
      Returns:
      the value of first integer if any; 0 otherwise
    • getNthIntValue

      public static int getNthIntValue(String line, int n)
      Parses a string such as "10.12.2" or "key = 1 (0x1) (int)" to find the integer value of the nth set of one or more consecutive digits
      Parameters:
      line - The entire string
      n - Which set of integers to return
      Returns:
      the value of nth integer if any; 0 otherwise
    • removeMatchingString

      public static String removeMatchingString(String original, String toRemove)
      Removes all matching sub strings from the string. More efficient than regexp.
      Parameters:
      original - source String to remove from
      toRemove - the sub string to be removed
      Returns:
      The string with all matching substrings removed
    • parseStringToLongArray

      public static long[] parseStringToLongArray(String s, int[] indices, int length, char delimiter)
      Parses a delimited string to an array of longs. Optimized for processing predictable-length arrays such as outputs of reliably formatted Linux proc or sys filesystem, minimizing new object creation. Users should perform other sanity checks of data. As a special case, non-numeric fields (such as UUIDs in OpenVZ) at the end of the list are ignored. Values greater than the max long value return the max long value. The indices parameters are referenced assuming the length as specified, and leading characters are ignored. For example, if the string is "foo 12 34 5" and the length is 3, then index 0 is 12, index 1 is 34, and index 2 is 5.
      Parameters:
      s - The string to parse
      indices - An array indicating which indexes should be populated in the final array; other values will be skipped. This idex is zero-referenced assuming the rightmost delimited fields of the string contain the array.
      length - The total number of elements in the string array. It is permissible for the string to have more elements than this; leading elements will be ignored. This should be calculated once per text format by countStringToLongArray(java.lang.String, char).
      delimiter - The character to delimit by.
      Returns:
      If successful, an array of parsed longs. If parsing errors occurred, will be an array of zeros.
    • countStringToLongArray

      public static int countStringToLongArray(String s, char delimiter)
      Parses a delimited string to count elements of an array of longs. Intended to be called once to calculate the length field for parseStringToLongArray(java.lang.String, int[], int, char). As a special case, non-numeric fields (such as UUIDs in OpenVZ) at the end of the list are ignored.
      Parameters:
      s - The string to parse
      delimiter - The character to delimit by
      Returns:
      The number of parsable long values which follow the last unparsable value.
    • getTextBetweenStrings

      public static String getTextBetweenStrings(String text, String before, String after)
      Get a String in a line of text between two marker strings
      Parameters:
      text - Text to search for match
      before - Start matching after this text
      after - End matching before this text
      Returns:
      Text between the strings before and after, or empty string if either marker does not exist
    • filetimeToUtcMs

      public static long filetimeToUtcMs(long filetime, boolean local)
      Convert a long representing filetime (100-ns since 1601 epoch) to ms since 1970 epoch
      Parameters:
      filetime - A 64-bit value equivalent to FILETIME
      local - True if converting from a local filetime (PDH counter); false if already UTC (WMI PerfRawData classes)
      Returns:
      Equivalent milliseconds since the epoch
    • parseMmDdYyyyToYyyyMmDD

      public static String parseMmDdYyyyToYyyyMmDD(String dateString)
      Parse a date in MM-DD-YYYY or MM/DD/YYYY to YYYY-MM-DD
      Parameters:
      dateString - The date in MM DD YYYY format
      Returns:
      The date in ISO YYYY-MM-DD format if parseable, or the original string
    • parseCimDateTimeToOffset

      public static OffsetDateTime parseCimDateTimeToOffset(String cimDateTime)
      Converts a string in CIM Date Format, as returned by WMI for DateTime types, into a OffsetDateTime.
      Parameters:
      cimDateTime - A non-null DateTime String in CIM date format, e.g., 20160513072950.782000-420
      Returns:
      The parsed OffsetDateTime if the string is parsable, otherwise Constants.UNIX_EPOCH.
    • filePathStartsWith

      public static boolean filePathStartsWith(List<String> prefixList, String path)
      Checks if a file path equals or starts with an prefix in the given list
      Parameters:
      prefixList - A list of path prefixes
      path - a string path to check
      Returns:
      true if the path exactly equals, or starts with one of the strings in prefixList
    • parseMultipliedToLongs

      public static long parseMultipliedToLongs(String count)
      Parses a string like "53G" or "54.904 M" to its long value.
      Parameters:
      count - A count with a multiplyer like "4096 M"
      Returns:
      the count parsed to a long
    • parseDecimalMemorySizeToBinary

      public static long parseDecimalMemorySizeToBinary(String size)
      Parses a string such as "4096 MB" to its long. Used to parse macOS and *nix memory chip sizes. Although the units given are decimal they must parse to binary units.
      Parameters:
      size - A string of memory sizes like "4096 MB"
      Returns:
      the size parsed to a long
    • parseDeviceIdToVendorProductSerial

      public static Triplet<String,String,String> parseDeviceIdToVendorProductSerial(String deviceId)
      Parse a Windows DeviceID to get the vendor ID, product ID, and Serial Number
      Parameters:
      deviceId - The DeviceID
      Returns:
      A Triplet where the first element is the vendor ID, the second element is the product ID, and the third element is either a serial number or empty string if parsing was successful, or null otherwise
    • parseLshwResourceString

      public static long parseLshwResourceString(String resources)
      Parse a Linux lshw resources string to calculate the memory size
      Parameters:
      resources - A string containing one or more elements of the form memory:b00000000-bffffffff
      Returns:
      The number of bytes consumed by the memory in the resources string
    • parseLspciMachineReadable

      public static Pair<String,String> parseLspciMachineReadable(String line)
      Parse a Linux lspci machine readble line to its name and id
      Parameters:
      line - A string in the form Foo [bar]
      Returns:
      A pair separating the String before the square brackets and within them if found, null otherwise
    • parseLspciMemorySize

      public static long parseLspciMemorySize(String line)
      Parse a Linux lspci line containing memory size
      Parameters:
      line - A string in the form Foo [size=256M]
      Returns:
      A the memory size in bytes
    • parseHyphenatedIntList

      public static List<Integer> parseHyphenatedIntList(String str)
      Parse a space-delimited list of integers which include hyphenated ranges to a list of just the integers. For example, 0 1 4-7 parses to a list containing 0, 1, 4, 5, 6, and 7. Also support comma separated entries like 0, 2-5, 7-8, 9 to a list containing 0, 2, 3, 4, 5, 7, 8, 9.
      Parameters:
      str - A string containing space-delimited integers or ranges of integers with a hyphen
      Returns:
      A list of integers representing the provided range(s).
    • parseIntToIP

      public static byte[] parseIntToIP(int ip)
      Parse an integer in big endian IP format to its component bytes representing an IPv4 address
      Parameters:
      ip - The address as an integer
      Returns:
      The address as an array of four bytes
    • parseIntArrayToIP

      public static byte[] parseIntArrayToIP(int[] ip6)
      Parse an integer array in big endian IP format to its component bytes representing an IPv6 address
      Parameters:
      ip6 - The address as an integer array
      Returns:
      The address as an array of sizteen bytes
    • bigEndian16ToLittleEndian

      public static int bigEndian16ToLittleEndian(int port)
      TCP network addresses and ports are in big endian format by definition. The order of the two bytes in the 16-bit unsigned short port value must be reversed
      Parameters:
      port - The port number in big endian order
      Returns:
      The port number
      See Also:
    • parseUtAddrV6toIP

      public static String parseUtAddrV6toIP(int[] utAddrV6)
      Parse an integer array to an IPv4 or IPv6 as appropriate.

      Intended for use on Utmp structures's ut_addr_v6 element.

      Parameters:
      utAddrV6 - An array of 4 integers representing an IPv6 address. IPv4 address uses just utAddrV6[0]
      Returns:
      A string representation of the IP address.
    • hexStringToInt

      public static int hexStringToInt(String hexString, int defaultValue)
      Parses a string of hex digits to an int value.
      Parameters:
      hexString - A sequence of hex digits
      defaultValue - default value to return if parsefails
      Returns:
      The corresponding int value
    • hexStringToLong

      public static long hexStringToLong(String hexString, long defaultValue)
      Parses a string of hex digits to a long value.
      Parameters:
      hexString - A sequence of hex digits
      defaultValue - default value to return if parsefails
      Returns:
      The corresponding long value
    • removeLeadingDots

      public static String removeLeadingDots(String dotPrefixedStr)
      Parses a String "....foo" to "foo"
      Parameters:
      dotPrefixedStr - A string with possibly leading dots
      Returns:
      The string without the dots
    • parseByteArrayToStrings

      public static List<String> parseByteArrayToStrings(byte[] bytes)
      Parse a null-delimited byte array to a list of strings.
      Parameters:
      bytes - A byte array containing Strings delimited by null characters. Two consecutive null characters mark the end of the list.
      Returns:
      A list of Strings between the nulls.
    • parseByteArrayToStringMap

      public static Map<String,String> parseByteArrayToStringMap(byte[] bytes)
      Parse a null-delimited byte array to a map of string keys and values.
      Parameters:
      bytes - A byte array containing String key-value pairs with keys and values delimited by = and pairs delimited by null characters. Two consecutive null characters mark the end of the map.
      Returns:
      A map of String key-value pairs between the nulls.
    • parseCharArrayToStringMap

      public static Map<String,String> parseCharArrayToStringMap(char[] chars)
      Parse a null-delimited char array to a map of string keys and values.
      Parameters:
      chars - A char array containing String key-value pairs with keys and values delimited by = and pairs delimited by null characters. Two consecutive null characters mark the end of the map.
      Returns:
      A map of String key-value pairs between the nulls.
    • stringToEnumMap

      public static <K extends Enum<K>> Map<K,String> stringToEnumMap(Class<K> clazz, String values, char delim)
      Parses a delimited String into an enum map. Multiple consecutive delimiters are treated as one.
      Type Parameters:
      K - a type extending Enum
      Parameters:
      clazz - The enum class
      values - A delimited String to be parsed into the map
      delim - the delimiter to use
      Returns:
      An EnumMap populated in order using the delimited String values. If there are fewer String values than enum values, the later enum values are not mapped. The final enum value will contain the remainder of the String, including excess delimiters.
    • getValueOrUnknown

      public static String getValueOrUnknown(Map<String,String> map, String key)
      Checks if value exists in map for the given key or not and returns value or unknown based on it
      Parameters:
      map - A map of String key-value pairs
      key - Fetch value for the given key
      Returns:
      Returns the value for the key if it exists in the map else it returns unknown