java.lang.Object
oshi.util.ParseUtil
String parsing utility.
-
Field Summary
-
Method Summary
Modifier and TypeMethodDescriptionstatic 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.static int
bigEndian16ToLittleEndian
(int port) TCP network addresses and ports are in big endian format by definition.static float
byteArrayToFloat
(byte[] bytes, int size, int fpBits) Convert a byte array to its floating point representation.static String
byteArrayToHexString
(byte[] bytes) Parse a byte array into a string of hexadecimal digits including all array bytes as digitsstatic long
byteArrayToLong
(byte[] bytes, int size) Convert a byte array to its (long) integer representation assuming big endian ordering.static long
byteArrayToLong
(byte[] bytes, int size, boolean bigEndian) Convert a byte array to its (long) integer representation in the specified endianness.static int
countStringToLongArray
(String s, char delimiter) Parses a delimited string to count elements of an array of longs.static boolean
filePathStartsWith
(List<String> prefixList, String path) Checks if a file path equals or starts with an prefix in the given liststatic long
filetimeToUtcMs
(long filetime, boolean local) Convert a long representing filetime (100-ns since 1601 epoch) to ms since 1970 epochstatic String
Parse a string key = "value" (string)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 digitsstatic 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 digitsstatic String
Parses a string key = 'value' (string)static String
getStringBetween
(String line, char c) Gets a value between two characters having multiple same characters between them.static String
getTextBetweenStrings
(String text, String before, String after) Get a String in a line of text between two marker stringsstatic 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 itstatic byte[]
hexStringToByteArray
(String digits) Parse a string of hexadecimal digits into a byte arraystatic int
hexStringToInt
(String hexString, int defaultValue) Parses a string of hex digits to an int value.static long
hexStringToLong
(String hexString, long defaultValue) Parses a string of hex digits to a long value.static String
hexStringToString
(String hexString) Parses a string of hex digits to a string where each pair of hex digits represents an ASCII characterstatic 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.parseByteArrayToStringMap
(byte[] bytes) Parse a null-delimited byte array to a map of string keys and values.parseByteArrayToStrings
(byte[] bytes) Parse a null-delimited byte array to a list of strings.parseCharArrayToStringMap
(char[] chars) Parse a null-delimited char array to a map of string keys and values.static OffsetDateTime
parseCimDateTimeToOffset
(String cimDateTime) Converts a string in CIM Date Format, as returned by WMI for DateTime types, into aOffsetDateTime
.static long
Parses a string such as "4096 MB" to its long.parseDeviceIdToVendorProductSerial
(String deviceId) Parse a Windows DeviceID to get the vendor ID, product ID, and Serial Numberstatic long
parseDHMSOrDefault
(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
(String s, double defaultDouble) Attempts to parse a string to a double.static long
parseHertz
(String hertz) Parse hertz from a string, eg. "2.00MHz" is 2000000L.Parse a space-delimited list of integers which include hyphenated ranges to a list of just the integers.static byte[]
parseIntArrayToIP
(int[] ip6) Parse an integer array in big endian IP format to its component bytes representing an IPv6 addressstatic int
parseIntOrDefault
(String s, int defaultInt) Attempts to parse a string to an int.static byte[]
parseIntToIP
(int ip) Parse an integer in big endian IP format to its component bytes representing an IPv4 addressstatic double
parseLastDouble
(String s, double d) Parse the last element of a space-delimited string to a valuestatic int
parseLastInt
(String s, int i) Parse the last element of a space-delimited string to a valuestatic long
parseLastLong
(String s, long li) Parse the last element of a space-delimited string to a valuestatic String
Parse the last element of a space-delimited string to a stringstatic long
parseLongOrDefault
(String s, long defaultLong) Attempts to parse a string to a long.static long
parseLshwResourceString
(String resources) Parse a Linux lshw resources string to calculate the memory sizeParse a Linux lspci machine readble line to its name and idstatic long
parseLspciMemorySize
(String line) Parse a Linux lspci line containing memory sizestatic String
parseMmDdYyyyToYyyyMmDD
(String dateString) Parse a date in MM-DD-YYYY or MM/DD/YYYY to YYYY-MM-DDstatic long
parseMultipliedToLongs
(String count) Parses a string like "53G" or "54.904 M" to its long value.static long[]
parseStringToLongArray
(String s, int[] indices, int length, char delimiter) Parses a delimited string to an array of longs.static long
parseUnsignedLongOrDefault
(String s, long defaultLong) Attempts to parse a string to an "unsigned" long.static String
parseUtAddrV6toIP
(int[] utAddrV6) Parse an integer array to an IPv4 or IPv6 as appropriate.static String
parseUuidOrDefault
(String s, String defaultStr) Attempts to parse a UUID.static String
removeLeadingDots
(String dotPrefixedStr) Parses a String "....foo" to "foo"static String
removeMatchingString
(String original, String toRemove) Removes all matching sub strings from the string.stringToEnumMap
(Class<K> clazz, String values, char delim) Parses a delimited String into an enum map.static long
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.
-
Field Details
-
whitespacesColonWhitespace
ConstantwhitespacesColonWhitespace
-
whitespaces
Constantwhitespaces
-
notDigits
ConstantnotDigits
-
startWithNotDigits
ConstantstartWithNotDigits
-
slash
ConstantforwardSlash
-
-
Method Details
-
parseHertz
Parse hertz from a string, eg. "2.00MHz" is 2000000L.- Parameters:
hertz
- Hertz size.- Returns:
Long
Hertz value or -1 if not parseable.
-
parseLastInt
Parse the last element of a space-delimited string to a value- Parameters:
s
- The string to parsei
- Default integer if not parsable- Returns:
- value or the given default if not parsable
-
parseLastLong
Parse the last element of a space-delimited string to a value- Parameters:
s
- The string to parseli
- Default long integer if not parsable- Returns:
- value or the given default if not parsable
-
parseLastDouble
Parse the last element of a space-delimited string to a value- Parameters:
s
- The string to parsed
- Default double if not parsable- Returns:
- value or the given default if not parsable
-
parseLastString
Parse the last element of a space-delimited string to a string- Parameters:
s
- The string to parse- Returns:
- last space-delimited element
-
byteArrayToHexString
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
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
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 parsedlength
- 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 convertedvalueSize
- Number of bytes representing the valuelength
- Number of bytes to return- Returns:
- A byte array of specified length representing the long in the first valueSize bytes
-
strToLong
Convert a string to an integer representation.- Parameters:
str
- A human readable ASCII stringsize
- 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 convertedsize
- 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 convertedsize
- 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 convertedsize
- 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
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
Attempts to parse a string to an int. If it fails, returns the default- Parameters:
s
- The string to parsedefaultInt
- The value to return if parsing fails- Returns:
- The parsed int, or the default if parsing failed
-
parseLongOrDefault
Attempts to parse a string to a long. If it fails, returns the default- Parameters:
s
- The string to parsedefaultLong
- The value to return if parsing fails- Returns:
- The parsed long, or the default if parsing failed
-
parseUnsignedLongOrDefault
Attempts to parse a string to an "unsigned" long. If it fails, returns the default- Parameters:
s
- The string to parsedefaultLong
- 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
Attempts to parse a string to a double. If it fails, returns the default- Parameters:
s
- The string to parsedefaultDouble
- The value to return if parsing fails- Returns:
- The parsed double, or the default if parsing failed
-
parseDHMSOrDefault
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 parsedefaultLong
- The value to return if parsing fails- Returns:
- The parsed number of seconds, or the default if parsing fails
-
parseUuidOrDefault
Attempts to parse a UUID. If it fails, returns the default.- Parameters:
s
- The string to parsedefaultStr
- The value to return if parsing fails- Returns:
- The parsed UUID, or the default if parsing fails
-
getSingleQuoteStringValue
Parses a string key = 'value' (string)- Parameters:
line
- The entire string- Returns:
- the value contained between single tick marks
-
getDoubleQuoteStringValue
Parse a string key = "value" (string)- Parameters:
line
- the entire string- Returns:
- the value contained between double tick marks
-
getStringBetween
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
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
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 stringn
- Which set of integers to return- Returns:
- the value of nth integer if any; 0 otherwise
-
removeMatchingString
Removes all matching sub strings from the string. More efficient than regexp.- Parameters:
original
- source String to remove fromtoRemove
- the sub string to be removed- Returns:
- The string with all matching substrings removed
-
parseStringToLongArray
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 parseindices
- 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 bycountStringToLongArray(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
Parses a delimited string to count elements of an array of longs. Intended to be called once to calculate thelength
field forparseStringToLongArray(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 parsedelimiter
- The character to delimit by- Returns:
- The number of parsable long values which follow the last unparsable value.
-
getTextBetweenStrings
Get a String in a line of text between two marker strings- Parameters:
text
- Text to search for matchbefore
- Start matching after this textafter
- 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 FILETIMElocal
- True if converting from a local filetime (PDH counter); false if already UTC (WMI PerfRawData classes)- Returns:
- Equivalent milliseconds since the epoch
-
parseMmDdYyyyToYyyyMmDD
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
Converts a string in CIM Date Format, as returned by WMI for DateTime types, into aOffsetDateTime
.- 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, otherwiseConstants.UNIX_EPOCH
.
-
filePathStartsWith
Checks if a file path equals or starts with an prefix in the given list- Parameters:
prefixList
- A list of path prefixespath
- a string path to check- Returns:
- true if the path exactly equals, or starts with one of the strings in prefixList
-
parseMultipliedToLongs
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
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
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, ornull
otherwise
-
parseLshwResourceString
Parse a Linux lshw resources string to calculate the memory size- Parameters:
resources
- A string containing one or more elements of the formmemory:b00000000-bffffffff
- Returns:
- The number of bytes consumed by the memory in the
resources
string
-
parseLspciMachineReadable
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
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
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
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
Parses a string of hex digits to an int value.- Parameters:
hexString
- A sequence of hex digitsdefaultValue
- default value to return if parsefails- Returns:
- The corresponding int value
-
hexStringToLong
Parses a string of hex digits to a long value.- Parameters:
hexString
- A sequence of hex digitsdefaultValue
- default value to return if parsefails- Returns:
- The corresponding long value
-
removeLeadingDots
Parses a String "....foo" to "foo"- Parameters:
dotPrefixedStr
- A string with possibly leading dots- Returns:
- The string without the dots
-
parseByteArrayToStrings
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
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
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 classvalues
- A delimited String to be parsed into the mapdelim
- 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
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 pairskey
- Fetch value for the given key- Returns:
- Returns the value for the key if it exists in the map else it returns unknown
-