Package oshi.util

Class ParseUtil

java.lang.Object
oshi.util.ParseUtil

@ThreadSafe
public final class ParseUtil
extends java.lang.Object
String parsing utility.
  • Field Summary

    Fields 
    Modifier and Type Field Description
    static java.util.regex.Pattern notDigits
    Constant notDigits
    static java.util.regex.Pattern startWithNotDigits
    Constant startWithNotDigits
    static java.util.regex.Pattern whitespaces
    Constant whitespaces
    static java.util.regex.Pattern whitespacesColonWhitespace
    Constant whitespacesColonWhitespace
  • Method Summary

    Modifier and Type Method Description
    static byte[] asciiStringToByteArray​(java.lang.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.
    static float byteArrayToFloat​(byte[] bytes, int size, int fpBits)
    Convert a byte array to its floating point representation.
    static java.lang.String byteArrayToHexString​(byte[] bytes)
    Parse a byte aray into a string of hexadecimal digits including leading zeros
    static long byteArrayToLong​(byte[] bytes, int size)
    Convert a byte array to its integer representation.
    static int countStringToLongArray​(java.lang.String s, char delimiter)
    Parses a delimited string to count elements of an array of longs.
    static boolean filePathStartsWith​(java.util.List<java.lang.String> prefixList, java.lang.String path)
    Checks if a file path equals or starts with an prefix in the given list
    static long filetimeToUtcMs​(long filetime, boolean local)
    Convert a long representing filetime (100-ns since 1601 epoch) to ms since 1970 epoch
    static java.lang.String getDoubleQuoteStringValue​(java.lang.String line)
    Parse a string key = "value" (string)
    static int getFirstIntValue​(java.lang.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
    static int getNthIntValue​(java.lang.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
    static java.lang.String getSingleQuoteStringValue​(java.lang.String line)
    Parses a string key = 'value' (string)
    static java.lang.String getStringBetween​(java.lang.String line, char c)
    Gets a value between two characters having multiple same characters between them.
    static java.lang.String getTextBetweenStrings​(java.lang.String text, java.lang.String before, java.lang.String after)
    Get a String in a line of text between two marker strings
    static byte[] hexStringToByteArray​(java.lang.String digits)
    Parse a string of hexadecimal digits into a byte array
    static java.lang.String hexStringToString​(java.lang.String hexString)
    Parses a string of hex digits to a string where each pair of hex digits represents an ASCII character
    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.
    static java.time.OffsetDateTime parseCimDateTimeToOffset​(java.lang.String cimDateTime)
    Converts a string in CIM Date Format, as returned by WMI for DateTime types, into a OffsetDateTime.
    static long parseDecimalMemorySizeToBinary​(java.lang.String size)
    Parses a string such as "4096 MB" to its long.
    static long parseDHMSOrDefault​(java.lang.String s, long defaultLong)
    Attempts to parse a string of the form [DD-[hh:]]mm:ss[.ddd] to a number of milliseconds.
    static double parseDoubleOrDefault​(java.lang.String s, double defaultDouble)
    Attempts to parse a string to a double.
    static long parseHertz​(java.lang.String hertz)
    Parse hertz from a string, eg.
    static java.util.List<java.lang.Integer> parseHyphenatedIntList​(java.lang.String str)
    Parse a space-delimited list of integers which include hyphenated ranges to a list of just the integers.
    static int parseIntOrDefault​(java.lang.String s, int defaultInt)
    Attempts to parse a string to an int.
    static double parseLastDouble​(java.lang.String s, double d)
    Parse the last element of a space-delimited string to a value
    static int parseLastInt​(java.lang.String s, int i)
    Parse the last element of a space-delimited string to a value
    static long parseLastLong​(java.lang.String s, long li)
    Parse the last element of a space-delimited string to a value
    static java.lang.String parseLastString​(java.lang.String s)
    Parse the last element of a space-delimited string to a string
    static long parseLongOrDefault​(java.lang.String s, long defaultLong)
    Attempts to parse a string to a long.
    static long parseLshwResourceString​(java.lang.String resources)
    Parse a Linux lshw resources string to calculate the memory size
    static Pair<java.lang.String,​java.lang.String> parseLspciMachineReadable​(java.lang.String line)
    Parse a Linux lspci machine readble line to its name and id
    static long parseLspciMemorySize​(java.lang.String line)
    Parse a Linux lspci line containing memory size
    static java.lang.String parseMmDdYyyyToYyyyMmDD​(java.lang.String dateString)
    Parse a date in MM-DD-YYYY or MM/DD/YYYY to YYYY-MM-DD
    static Pair<java.lang.String,​java.lang.String> parsePnPDeviceIdToVendorProductId​(java.lang.String pnpDeviceId)
    Parse a Windows PnPDeviceID to get the vendor ID and product ID.
    static long[] parseStringToLongArray​(java.lang.String s, int[] indices, int length, char delimiter)
    Parses a delimited string to an array of longs.
    static long parseUnsignedLongOrDefault​(java.lang.String s, long defaultLong)
    Attempts to parse a string to an "unsigned" long.
    static java.lang.String parseUtAddrV6toIP​(int[] utAddrV6)
    Parse an integer array to an IPv4 or IPv6 as appropriate.
    static java.lang.String parseUuidOrDefault​(java.lang.String s, java.lang.String defaultStr)
    Attempts to parse a UUID.
    static java.lang.String removeMatchingString​(java.lang.String original, java.lang.String toRemove)
    Removes all matching sub strings from the string.
    static long strToLong​(java.lang.String str, int size)
    Convert a string to an integer representation.
    static long unsignedIntToLong​(int unsignedValue)
    Convert an unsigned integer to a long value.
    static long unsignedLongToSignedLong​(long unsignedValue)
    Convert an unsigned long to a signed long value by stripping the sign bit.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Field Details

    • whitespacesColonWhitespace

      public static final java.util.regex.Pattern whitespacesColonWhitespace
      Constant whitespacesColonWhitespace
    • whitespaces

      public static final java.util.regex.Pattern whitespaces
      Constant whitespaces
    • notDigits

      public static final java.util.regex.Pattern notDigits
      Constant notDigits
    • startWithNotDigits

      public static final java.util.regex.Pattern startWithNotDigits
      Constant startWithNotDigits
  • Method Details

    • parseHertz

      public static long parseHertz​(java.lang.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​(java.lang.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​(java.lang.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​(java.lang.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 java.lang.String parseLastString​(java.lang.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 java.lang.String byteArrayToHexString​(byte[] bytes)
      Parse a byte aray into a string of hexadecimal digits including leading zeros
      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​(java.lang.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​(java.lang.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​(java.lang.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 integer representation.
      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:
      An integer representing the byte array as a 64-bit number
    • 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 java.lang.String hexStringToString​(java.lang.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​(java.lang.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​(java.lang.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​(java.lang.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​(java.lang.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​(java.lang.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 java.lang.String parseUuidOrDefault​(java.lang.String s, java.lang.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 java.lang.String getSingleQuoteStringValue​(java.lang.String line)
      Parses a string key = 'value' (string)
      Parameters:
      line - The entire string
      Returns:
      the value contained between single tick marks
    • getDoubleQuoteStringValue

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

      public static java.lang.String getStringBetween​(java.lang.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​(java.lang.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​(java.lang.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 java.lang.String removeMatchingString​(java.lang.String original, java.lang.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​(java.lang.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​(java.lang.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 java.lang.String getTextBetweenStrings​(java.lang.String text, java.lang.String before, java.lang.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 java.lang.String parseMmDdYyyyToYyyyMmDD​(java.lang.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 java.time.OffsetDateTime parseCimDateTimeToOffset​(java.lang.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​(java.util.List<java.lang.String> prefixList, java.lang.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
    • parseDecimalMemorySizeToBinary

      public static long parseDecimalMemorySizeToBinary​(java.lang.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
    • parsePnPDeviceIdToVendorProductId

      public static Pair<java.lang.String,​java.lang.String> parsePnPDeviceIdToVendorProductId​(java.lang.String pnpDeviceId)
      Parse a Windows PnPDeviceID to get the vendor ID and product ID.
      Parameters:
      pnpDeviceId - The PnPDeviceID
      Returns:
      A Pair where the first element is the vendor ID and second element is the product ID, if parsing was successful, or null otherwise
    • parseLshwResourceString

      public static long parseLshwResourceString​(java.lang.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<java.lang.String,​java.lang.String> parseLspciMachineReadable​(java.lang.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​(java.lang.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 java.util.List<java.lang.Integer> parseHyphenatedIntList​(java.lang.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.
      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).
    • parseUtAddrV6toIP

      public static java.lang.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.