com.internationalnetwork.util
Class StringParser

Object
  extended by com.internationalnetwork.util.StringParser

public class StringParser
extends Object

StringParser is a collection of static String parsing methods designed to simplify often complex or especially cumbersome String operations.


Field Summary
static String VERSION
          Version number of this Package (read-only).
 
Method Summary
static String[] atomize(String unparsedString)
          Parses a String, returning all elements (or "atoms") as a String[] array.
static String commas(int number)
          Inserts commas between every three digits in the supplied number, and returns it as a String.
static String commas(long number)
          Inserts commas between every three digits in the supplied number, and returns it as a String.
static String commas(short number)
          Inserts commas between every three digits in the supplied number, and returns it as a String.
static String convertFromRNAME(String rname, String defaultIDN)
          Converts a RNAME string to an eMail address, placing the AT (@) symbol in the proper position.
static String executeBackspaces(String input)
          Simulates the effect of backspace characters ASCII 8 and ASCII 127, and executes both in a destructive manner.
static boolean isCIDRNotation(String address)
          Determines if the specified address is strictly conforms to IPv4 CIDR notation or IPv6 CIDR notation.
static boolean isCIDRNotationRelaxed(String address)
          This method is the same as the isCIDRNotation() method, except that it allows leading zeros in the IPv4 address portion of CIDRs.
static boolean isCIDRv4Notation(String address)
          Determines if the specified address is strictly conforms to IPv4 CIDR notation.
static boolean isCIDRv4NotationRelaxed(String address)
          This method is the same as the isCIDRv4Notation() method, except that it allows leading zeros in the IP address portion of CIDRs.
static boolean isCIDRv6Notation(String address)
          Determines if the specified address is strictly complies with IPv6 CIDR notation.
static boolean isDomainLiteral(String address)
          Determines if the specified address is strictly formatted as a valid IPv4 or IPv6 Domain Literal.
static boolean isDomainLiteral4(String address)
          Determines if the specified address is strictly formatted as a valid IPv4 Domain Literal.
static boolean isDomainLiteral4Relaxed(String address)
          This method is the same as the isDomainLiteral() method, except that it allows leading zeros in the IPv4 address portion of domain literals.
static boolean isDomainLiteral6(String address)
          Determines if the specified address is strictly formatted as a valid IPv6 Domain Literal.
static boolean isDomainLiteralRelaxed(String address)
          This method is the same as the isDomainLiteral() method, except that it allows leading zeros in the IPv4 address portion of domain literals.
static boolean isInternetName(String internetName)
          The same as isInternetName(String, int), but without a maximum length specified.
static boolean isInternetName(String internetName, int maximumLength)
          Tests a String for suitability as an internet name based on rules that are found in a variety of RFCs (such as 1034, 1340, 2822, etc.).
static boolean isIPAddress(String address)
          Determines if the specified address is strictly formatted as a valid IPv4 or IPv6 address.
static boolean isIPAddressRelaxed(String address)
          This method is the same as the isIPAddress() method, except that it allows leading zeros in IPv4 addresses.
static boolean isIPv4Address(String address)
          Determines if the specified address is strictly formatted as a valid IPv4 address.
static boolean isIPv4AddressRelaxed(String address)
          This method is the same as the isIPv4Address() method, except that it allows leading zeros.
static boolean isIPv6Address(String address)
          Determines if the specified address is strictly formatted as a valid IPv6 address.
static boolean isSafeFilename(int flags, String validCharacters, String filename)
          This method checks if the supplied String is a safe filename.  If it complies with the following rules, then it is assumed to be safe on both the Unix/Linux/Mac and DOS/Windows categories of Operating Systems.
static boolean isSafeFilename(String filename)
          This method checks if the supplied String is a safe filename.  If it complies with the following rules, then it is assumed to be safe on both the Unix/Linux/Mac and DOS/Windows categories of Operating Systems.
static String join(String delimiter, String... strings)
          Joins any number of strings (or an array[] of strings) together as one.
static String joinStrings(String delimiter, String... strings)
          Joins any number of strings (or an array[] of strings) together as one.
static String minimumLeadingDigits(int number, int digits)
          Inserts leading zeros in front of the numeric portion of the value provided, while also supporting the sign for negative values.
static String minimumTrailingDigits(int number, int digits)
          Inserts trailing zeros after the numeric portion of the value provided, while also supporting the sign for negative values.
static Object[] options(java.math.BigInteger inheritedFlags, String[] options, String... bitFields)
          Parses a String[] array containing a list of options that were provided by a user or in a configuration file, in the same format and with the same semantics as Apache's HTTPd server "Options" and "IndexOptions" directives.
static Object[] options(long inheritedFlags, String[] options, String... bitFields)
          Parses a String[] array containing a list of options that were provided by a user or in a configuration file, in the same format and with the same semantics as Apache's HTTPd server "Options" and "IndexOptions" directives.
static String padLeft(int minLength, String padding, String data)
          Pads the left-hand side of the specified string with the string provided, and without exceeding the minimum length if the padding string contains more than one character.
static String padRight(int minLength, String data, String padding)
          Pads the right-hand side of the specified string with the string provided, and without exceeding the minimum length if the padding string contains more than one character.
static boolean parseBoolean(String number, boolean exception, String... specials)
          Converts a String containing a state to a special (optional) or a boolean (in that order), and returns the specified boolean in place of throwing java.lang.NumberFormatException.
static byte parseByte(String number, byte exception, String... specials)
          Converts a String containing a number to a special (optional) or a byte integer (in that order), and returns the specified byte integer in place of throwing java.lang.NumberFormatException.
static double parseDouble(String number, double exception, String... specials)
          Converts a String containing a number to a special (optional) or a double (in that order), and returns the specified double in place of throwing java.lang.NumberFormatException.
static float parseFloat(String number, float exception, String... specials)
          Converts a String containing a number to a special (optional) or a float (in that order), and returns the specified float in place of throwing java.lang.NumberFormatException.
static int parseInt(String number, int exception, String... specials)
          Converts a String containing a number to a special (optional) or an integer (in that order), and returns the specified integer in place of throwing java.lang.NumberFormatException.
static long parseLong(String number, long exception, String... specials)
          Converts a String containing a number to a special (optional) or a long integer (in that order), and returns the specified long integer in place of throwing java.lang.NumberFormatException.
static byte parseNybble(String number, byte exception, String... specials)
          Converts a String containing a number to a special (optional) or a nybble (in that order), represented by a byte, and returns the specified nybble (which must also be within the range of a nybble), also represented by a byte, in place of throwing java.lang.NumberFormatException.
static short parseShort(String number, short exception, String... specials)
          Converts a String containing a number to a special (optional) or a short integer (in that order), and returns the specified short integer in place of throwing java.lang.NumberFormatException.
static VeryLong parseVeryLong(String number, VeryLong exception, String... specials)
          Converts a String containing a number to a special (optional) or VeryLong (in that order), and returns the specified VeryLong (which must also be within the range of a nybble), also represented by a byte, in place of throwing java.lang.NumberFormatException.
static String quote(String string)
          Adds quotes around strings (the opposite of the trimQuotes() method, and the de-quoting that the atomize() method performs).
static String quoteMinimal(String string)
          Adds quotes around strings (the opposite of the trimQuotes() method, and the de-quoting that the atomize() method performs).
static String refineDomainLiteral(String address)
          Formats a domain literal to its most acceptable format, that is expected and most easily interpreted by computing systems.  Leading zeros are removed from all octets, and the double colons are replaced with the correct number of single-digit zeros (which eliminates the shortcuts that may be considered unpredictable).
static String refineDomainLiteral4(String address)
          Formats a domain literal to its most acceptable format, that is expected and most easily interpreted by computing systems.  Leading zeros are removed from all octets.
static String refineDomainLiteral6(String address)
          Formats a domain literal to its most acceptable format, that is expected and most easily interpreted by computing systems.  Leading zeros are removed from all octets, and the double colons are replaced with the correct number of single-digit zeros (which eliminates the shortcuts that may be considered unpredictable).
static String refineIPAddress(String address)
          Formats an IP address to its most acceptable format, that is expected and most easily interpreted by computing systems.  Leading zeros are removed from all octets, and the double colons are replaced with the correct number of single-digit zeros (which eliminates the shortcuts that may be considered unpredictable).
static String refineIPv4Address(String address)
          Formats an IP address to its most acceptable format, that is expected and most easily interpreted by computing systems.  Leading zeros are removed from all octets.
static String refineIPv6Address(String address)
          Formats an IP address to its most acceptable format, that is expected and most easily interpreted by computing systems.  Leading zeros are removed from all octets, and the double colons are replaced with the correct number of single-digit zeros (which eliminates the shortcuts that may be considered unpredictable).
static HashMap<String,String[]> refineSASLExchange(String unparsedString)
          Parses a SASL Exchange (must not be Base64-encoded), as demonstrated in RFC 2831, returning all elements as a HashMap object containing String[] arrays.
static String[] splitPairs(String pairs, String... keys)
          Parses a String containing white-space delimited "key=value" pairs, and returns a String[] array containing only values that correspond with the specified key(s), thus consistently placing every value in a specific position in the array to simplify string parsing, in a flexible manner.
static String substring(String string, int beginIndex)
          An improved version of java.lang.String.substring() that handles negative values logically by processing from the end of the string.
static boolean transmuteBoolean(String phrase, boolean exception, String... specials)
          Transmutes a String to a boolean based on the list of specials (the phrases and their corresponding values), and returns the specified boolean.
static byte transmuteByte(String phrase, byte exception, String... specials)
          Transmutes a String to a byte integer based on the list of specials (the phrases and their corresponding values), and returns the specified byte integer.
static double transmuteDouble(String phrase, double exception, String... specials)
          Transmutes a String to a double based on the list of specials (the phrases and their corresponding values), and returns the specified double.
static float transmuteFloat(String phrase, float exception, String... specials)
          Transmutes a String to a float based on the list of specials (the phrases and their corresponding values), and returns the specified float.
static int transmuteInt(String phrase, int exception, String... specials)
          Transmutes a String to an integer based on the list of specials (the phrases and their corresponding values), and returns the specified integer.
static long transmuteLong(String phrase, long exception, String... specials)
          Transmutes a String to a long integer based on the list of specials (the phrases and their corresponding values), and returns the specified long integer.
static byte transmuteNybble(String phrase, byte exception, String... specials)
          Transmutes a String to a nybble integer based on the list of specials (the phrases and their corresponding values), and returns the specified nybble integer represented by a byte.
static short transmuteShort(String phrase, short exception, String... specials)
          Transmutes a String to a short integer based on the list of specials (the phrases and their corresponding values), and returns the specified short integer.
static VeryLong transmuteVeryLong(String phrase, VeryLong exception, String... specials)
          Transmutes a String to a VeryLong object based on the list of specials (the phrases and their corresponding values), and returns the specified VeryLong object represented by a VeryLong object (because a native equiviliant isn't currently available).
static String trimQuotes(String string)
          Removes the outer-most/enclosing set of quotation marks from the beginning and end of the specified String, but only if both are present.
static String x(String string, int repeat)
          Works like Perl's x operator in that it returns the string repeated and joined immediately to itself x times.
 
Methods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

VERSION

public static final String VERSION
Version number of this Package (read-only).

See Also:
Constant Field Values
Method Detail

atomize

public static String[] atomize(String unparsedString)
Parses a String, returning all elements (or "atoms") as a String[] array.

The rules for parsing are:

The String called "unparsedString" in the following example could be a command line with parameters, as entered by a user or extracted from a script or configuration file, etc., but in this case contains the some hard-coded text:

String unparsedString = "The answer is \"fourty two\"";
String[] args = StringParser.atomize(unparsedString);

The resulting args[] array contains four elements (not five):

  1. The
  2. answer
  3. is
  4. fourty two

Parameters:
unparsedString - The string to parse
Returns:
Array of strings (array may be empty, but will never be null)

commas

public static String commas(int number)
Inserts commas between every three digits in the supplied number, and returns it as a String.

Parameters:
number - Number to format
Returns:
String, formatted with commas between every three digits

commas

public static String commas(long number)
Inserts commas between every three digits in the supplied number, and returns it as a String.

Parameters:
number - Number to format
Returns:
String, formatted with commas between every three digits

commas

public static String commas(short number)
Inserts commas between every three digits in the supplied number, and returns it as a String.

Parameters:
number - Number to format
Returns:
String, formatted with commas between every three digits

convertFromRNAME

public static String convertFromRNAME(String rname,
                                      String defaultIDN)
                               throws java.text.ParseException
Converts a RNAME string to an eMail address, placing the AT (@) symbol in the proper position. Support for multiple "\." character sequences, which denote literal periods that should not be converted to AT symbols, is included in this method.

It's important to note that only one AT symbol is permitted in an eMail address, which logically implies that "\." delimiter sequences cannot be used again after a regular "." delimiter; if this inconsistency is encountered, a runtime exception will be thrown.

No validity checks are performed on the eMail address. If the domain-part is missing, the optional default domain-part will be used instead (if it is provided).

Trailing periods will be omitted automatically.

Parameters:
rname - The raw String for RNAME data, as it appears in a Bind zone file (most commonly found in SOA record definitions); if null, this String will be converted to an empty string for normal processing instead of throwing a null pointer exception.
defaultIDN - The "default" Internet Domain Name to append if one wasn't provided in the RNAME data string (specify null to indicate no default)
Returns:
String, converted to an eMail address
Throws:
java.text.ParseException - When a "\." delimiter is encountered in an inappropriate position; the offset will reference the offending element in an array as produced by rname.split("\\\\.")

executeBackspaces

public static String executeBackspaces(String input)
Simulates the effect of backspace characters ASCII 8 and ASCII 127, and executes both in a destructive manner. The returned string will not only have the backspace characters removed, but their preceeding characters as well, and in a simulated fashion as if they were typed by a user.

All leading backspaces will disappear completely without generating errors, because this is the natural expectation from users on how a GUI typically handles excessive leading backspaces.

Parameters:
input - String to execute backspaces in
Returns:
An updated version of the original input string

isCIDRNotation

public static boolean isCIDRNotation(String address)
Determines if the specified address is strictly conforms to IPv4 CIDR notation or IPv6 CIDR notation. No attempts are made to verify that the specified address is reachable since this is purely a means of determining if the format is correct. This can be a very important step from a security standpoint for certain applications, or for enforcing a "no hostnames may be specified" rule in a configuration file or command line parameter, etc.

See the documentation for the isCIDRv4Notation and isCIDRv6Notation methods for CIDR notation formatting details for IPv4 and IPv6 respectively.

Parameters:
address - String containing the CIDR address to test
Returns:
True, only if the address is completely valid as per IPv4 CIDR notation or IPv6 CIDR notation, False otherwise
See Also:
isCIDRNotationRelaxed(java.lang.String)

isCIDRNotationRelaxed

public static boolean isCIDRNotationRelaxed(String address)
This method is the same as the isCIDRNotation() method, except that it allows leading zeros in the IPv4 address portion of CIDRs.

Parameters:
address - String containing the CIDR address to test
Returns:
True, only if the address is valid as per IPv4 CIDR notation or completely valid as per IPv6 CIDR notation, False otherwise
See Also:
isCIDRNotation(java.lang.String)

isCIDRv4Notation

public static boolean isCIDRv4Notation(String address)
Determines if the specified address is strictly conforms to IPv4 CIDR notation. No attempts are made to verify that the specified address is reachable since this is purely a means of determining if the format is correct. This can be a very important step from a security standpoint for certain applications, or for enforcing a "no hostnames may be specified" rule in a configuration file or command line parameter, etc.

IPv4 CIDR notation is comprised of up to four octets, each ranging from 0 to 255 (in decimal {base 10} notation), each delimited by exactly one period, followed by a slash, and the number of bits in the mask (0 through 32, in decimal {base 10} notation). For example:

Leading and trailing white space is not valid (java.lang.String.trim() can be used to correct this ahead of time), and leading zeros are not permitted in octets.

Parameters:
address - String containing the IPv4 CIDR address to test
Returns:
True, only if the address is completely valid as per IPv4 CIDR notation, False otherwise
See Also:
isCIDRv4NotationRelaxed(java.lang.String)

isCIDRv4NotationRelaxed

public static boolean isCIDRv4NotationRelaxed(String address)
This method is the same as the isCIDRv4Notation() method, except that it allows leading zeros in the IP address portion of CIDRs.

Parameters:
address - String containing the IPv4 CIDR address to test
Returns:
True, only if the address is valid as per IPv4 CIDR notation, False otherwise
See Also:
isCIDRv4Notation(java.lang.String)

isCIDRv6Notation

public static boolean isCIDRv6Notation(String address)
Determines if the specified address is strictly complies with IPv6 CIDR notation. No attempts are made to verify that the specified address is reachable since this is purely a means of determining if the format is correct. This can be a very important step from a security standpoint for certain applications, or for enforcing a "no hostnames may be specified" rule in a configuration file or command line parameter, etc.

IPv6 notation is comprised of 8 octets, comprised of 1 to 4 nybbles ranging from 0 to FFFF (in hexadecimal {base 16} notation), each delimited by a colon (only one pair of delimiting colons that represents two or more 0-value octets is permitted), followed by a slash, and the number of bits in the mask (0 through 128, in decimal {base 10} notation). For example:

Leading and trailing white space is not valid (java.lang.String.trim() can be used to correct this ahead of time), but leading zeros are permitted in octets as long as the total length doesn't exceed 4 nybbles.

Parameters:
address - String containing the IPv6 CIDR address to test
Returns:
True, only if the address is completely valid as per IPv6 CIDR notation, False otherwise

isDomainLiteral

public static boolean isDomainLiteral(String address)
Determines if the specified address is strictly formatted as a valid IPv4 or IPv6 Domain Literal. No attempts are made to verify that the specified address is reachable since this is purely a means of determining if the format is correct. This can be a very important step from a security standpoint for certain applications, or for enforcing a "no hostnames may be specified" rule in a configuration file or command line parameter, etc.

See the documentation for the isDomainLiteral4 and isDomainLiteral6 methods for IP address notation formatting details.

Parameters:
address - String containing the IPv4 or IPv6 Domain Literal to test
Returns:
True, only if the address is completely valid as either an IPv4 or IPv6 Domain Literal, False otherwise
See Also:
isDomainLiteralRelaxed(java.lang.String)

isDomainLiteral4

public static boolean isDomainLiteral4(String address)
Determines if the specified address is strictly formatted as a valid IPv4 Domain Literal. No attempts are made to verify that the specified address is reachable since this is purely a means of determining if the format is correct. This can be a very important step from a security standpoint for certain applications, or for enforcing a "no hostnames may be specified" rule in a configuration file or command line parameter, etc.

An IPv4 Domain Literal is an IPv4 address enclosed within a single set of square brackets.  It is most commonly used by SMTP servers as an alternative replacement for the internet domain name portion of an eMail address (useful when a message needs to be sent back to the postmaster of an SMTP server when the internet domain name is unknown or unresolvable).

IPv4 Domain Literal examples:

Leading and trailing white space is not valid (java.lang.String.trim() can be used to correct this ahead of time), and leading zeros are not permitted in octets.

Parameters:
address - String containing the IPv4 Domain Literal to test
Returns:
True, only if the Domain Literal is completely valid, False otherwise

isDomainLiteral4Relaxed

public static boolean isDomainLiteral4Relaxed(String address)
This method is the same as the isDomainLiteral() method, except that it allows leading zeros in the IPv4 address portion of domain literals.

Parameters:
address - String containing the IPv4 Domain Literal to test
Returns:
True, only if the Domain Literal is valid, False otherwise
See Also:
isDomainLiteral4(java.lang.String)

isDomainLiteral6

public static boolean isDomainLiteral6(String address)
Determines if the specified address is strictly formatted as a valid IPv6 Domain Literal. No attempts are made to verify that the specified address is reachable since this is purely a means of determining if the format is correct. This can be a very important step from a security standpoint for certain applications, or for enforcing a "no hostnames may be specified" rule in a configuration file or command line parameter, etc.

An IPv6 Domain Literal is an IPv6 address enclosed within a single set of square brackets.  It is most commonly used by SMTP servers as an alternative replacement for the internet domain name portion of an eMail address (useful when a message needs to be sent back to the postmaster of an SMTP server when the internet domain name is unknown or unresolvable).

IPv6 Domain Literal examples:

Leading and trailing white space is not valid (java.lang.String.trim() can be used to correct this ahead of time), but leading zeros are permitted in octets as long as the total length doesn't exceed 4 nybbles.

Parameters:
address - String containing the IPv6 Domain Literal to test
Returns:
True, only if the Domain Literal is completely valid, False otherwise

isDomainLiteralRelaxed

public static boolean isDomainLiteralRelaxed(String address)
This method is the same as the isDomainLiteral() method, except that it allows leading zeros in the IPv4 address portion of domain literals.

Parameters:
address - String containing the IPv4 or IPv6 Domain Literal to test
Returns:
True, only if the address is valid as either an IPv4 Domain Literal, or completely valid as an IPv6 Domain Literal, False otherwise
See Also:
isDomainLiteral(java.lang.String)

isInternetName

public static boolean isInternetName(String internetName)
The same as isInternetName(String, int), but without a maximum length specified.

Parameters:
internetName - String to test
Returns:
True, if the internet name complies with the rules as listed above

isInternetName

public static boolean isInternetName(String internetName,
                                     int maximumLength)
Tests a String for suitability as an internet name based on rules that are found in a variety of RFCs (such as 1034, 1340, 2822, etc.).

For example, service names and protocol names are described on page 88 in RFC1340 with the following rules:

"A protocol or service may be up to 40 characters taken from the set of uppercase letters, digits, and the punctuation character hyphen. It must start with a letter, and end with a letter or digit."

There are other examples as well, with varying maximum lengths, such as the "label" rule in RFC1034 which has the same requirements for characters, but which has a longer maximum length of 63 characters.

The rules for testing a String using this method are:

The value of n is the maximum length that you specify, which makes this method valuable since these types of strings are extremely useful for a very wide range of cross-platform purposes.

Clarifications of interpretations due to exceptions to some of the rules which could otherwise result in potential conflicts:

  1. Sometimes the minimum length in an RFC is stated as zero character instead of one. This method always assumes a minimum length of one character.
     
  2. Many RFCs use letters of the English alphabet in a case-insensitive manner. This method is not case-sensitive, and assumes that both upper-case and lower-case letters are equally valid.

Although creating a Regular Expression to test for these rules is a simple matter, this method checks every character sequentially in an optimized loop to reduce processor overhead (a Regular Expression is compiled before a matcher, which also checks for special characters, commences validation).

Additional tests are performed to avoid throwing run-time exceptions, which can result from a null or empty string, or an invalid maximumLength value.

Parameters:
internetName - String to test
maximumLength - Maximum number of characters allowed (or n)
Returns:
True, if the internet name complies with the rules as listed above

isIPAddress

public static boolean isIPAddress(String address)
Determines if the specified address is strictly formatted as a valid IPv4 or IPv6 address. No attempts are made to verify that the specified address is reachable since this is purely a means of determining if the format is correct. This can be a very important step from a security standpoint for certain applications, or for enforcing a "no hostnames may be specified" rule in a configuration file or command line parameter, etc.

See the documentation for the isIPv4Address and isIPv6Address methods for IP address notation formatting details.

Parameters:
address - String containing the IPv4 or IPv6 address to test
Returns:
True, only if the address is completely valid as either an IPv4 or IPv6 address, False otherwise
See Also:
isIPAddressRelaxed(java.lang.String)

isIPAddressRelaxed

public static boolean isIPAddressRelaxed(String address)
This method is the same as the isIPAddress() method, except that it allows leading zeros in IPv4 addresses.

Parameters:
address - String containing the IPv4 or IPv6 address to test
Returns:
True, only if the address is valid as either an IPv4 or completely valid as an IPv6 address, False otherwise
See Also:
isIPAddress(java.lang.String)

isIPv4Address

public static boolean isIPv4Address(String address)
Determines if the specified address is strictly formatted as a valid IPv4 address. No attempts are made to verify that the specified address is reachable since this is purely a means of determining if the format is correct. This can be a very important step from a security standpoint for certain applications, or for enforcing a "no hostnames may be specified" rule in a configuration file or command line parameter, etc.

An IPv4 address is comprised of four octets, each ranging from 0 to 255 (in decimal {base 10} notation), each delimited by exactly one period. For example:

Leading and trailing white space is not valid (java.lang.String.trim() can be used to correct this ahead of time), and leading zeros are not permitted in octets.

Parameters:
address - String containing the IPv4 address to test
Returns:
True, only if the address is completely valid, False otherwise
See Also:
isIPv4AddressRelaxed(java.lang.String)

isIPv4AddressRelaxed

public static boolean isIPv4AddressRelaxed(String address)
This method is the same as the isIPv4Address() method, except that it allows leading zeros.

Parameters:
address - String containing the IPv4 address to test
Returns:
True, only if the address is valid, False otherwise
See Also:
isIPv4Address(java.lang.String)

isIPv6Address

public static boolean isIPv6Address(String address)
Determines if the specified address is strictly formatted as a valid IPv6 address. No attempts are made to verify that the specified address is reachable since this is purely a means of determining if the format is correct. This can be a very important step from a security standpoint for certain applications, or for enforcing a "no hostnames may be specified" rule in a configuration file or command line parameter, etc.

An IPv6 address is comprised of 8 octets, comprised of 1 to 4 nybbles ranging from 0 to FFFF (in hexadecimal {base 16} notation), each delimited by a colon (only one pair of delimiting colons that represents two or more 0-value octets is permitted). For example:

Leading and trailing white space is not valid (java.lang.String.trim() can be used to correct this ahead of time), but leading zeros are permitted in octets as long as the total length doesn't exceed 4 nybbles.

Parameters:
address - String containing the IPv6 address to test
Returns:
True, only if the address is completely valid, False otherwise

isSafeFilename

public static boolean isSafeFilename(int flags,
                                     String validCharacters,
                                     String filename)
This method checks if the supplied String is a safe filename.  If it complies with the following rules, then it is assumed to be safe on both the Unix/Linux/Mac and DOS/Windows categories of Operating Systems.

This method does not test filename length, and certainly doesn't enforce the DOS 14-character (8 characters, a period, and 3 characters) naming conventions since the only DOS implementation of Java overcomes this limit with a low-level work-around in the JVM (this JVM was available for one of the final releases of Netscape Navigator for Windows 3.10 and 3.11, and ran Java applets successfully without underlying long filename support by intercepting all Java filename API calls and "faking" it).

Rules:

The filename must comply with all these rules (exceptions are possible by using flags).

Valid characters:

The last four characters are a period (dot), a hyphen (dash or minus sign), a plus sign, and an underscore.

Flags:

To be defined.  Currently not supported, and must be zero for now to ensure consistent behaviour with a future release.

Parameters:
flags - Bit field specifying the exclusion of certain tests
validCharacters - String containing a list of valid characters to use instead of the default list (if NULL, the default list will be used)
filename - String containing the filename to test
Returns:
True, if the filename complies with all the rules, otherwise False if it could potentially cause unpredictable OS-level behaviour outside of the JVM

isSafeFilename

public static boolean isSafeFilename(String filename)
This method checks if the supplied String is a safe filename.  If it complies with the following rules, then it is assumed to be safe on both the Unix/Linux/Mac and DOS/Windows categories of Operating Systems.

This method does not test filename length, and certainly doesn't enforce the DOS 14-character (8 characters, a period, and 3 characters) naming conventions since the only DOS implementation of Java overcomes this limit with a low-level work-around in the JVM (this JVM was available for one of the final releases of Netscape Navigator for Windows 3.10 and 3.11, and ran Java applets successfully without underlying long filename support by intercepting all Java filename API calls and "faking" it).

Rules:

The filename must comply with all these rules, without exceptions.

Valid characters:

The last four characters are a period (dot), a hyphen (dash or minus sign), a plus sign, and an underscore.

Parameters:
filename - String containing the filename to test
Returns:
True, if the filename complies with all the rules, otherwise False if it could potentially cause unpredictable OS-level behaviour outside of the JVM

join

public static String join(String delimiter,
                          String... strings)
Joins any number of strings (or an array[] of strings) together as one. Nulls will be treated as empty strings.

Parameters:
delimiter - The separator string to insert between the joined strings (including empty strings, and nulls)
strings - One or more strings (or an array[] of strings) to join
Returns:
The joined strings as a single string (never returns null)

joinStrings

public static String joinStrings(String delimiter,
                                 String... strings)
Joins any number of strings (or an array[] of strings) together as one. Nulls will be skipped (and not treated as empty strings), and without introducing extra delimiters, since they are not strings.

Parameters:
delimiter - The separator string to insert between the joined strings (including empty strings, excluding nulls)
strings - One or more strings (or an array[] of strings) to join
Returns:
The joined strings as a single string (never returns null)

minimumLeadingDigits

public static String minimumLeadingDigits(int number,
                                          int digits)
Inserts leading zeros in front of the numeric portion of the value provided, while also supporting the sign for negative values.

Parameters:
number - The value
digits - The desired minimum number of digits
Returns:
The value, as a string, with leading zeros inserted as needed

minimumTrailingDigits

public static String minimumTrailingDigits(int number,
                                           int digits)
Inserts trailing zeros after the numeric portion of the value provided, while also supporting the sign for negative values.

Parameters:
number - The value
digits - The desired minimum number of digits
Returns:
The value, as a string, with trailing zeros added as needed

options

public static Object[] options(java.math.BigInteger inheritedFlags,
                               String[] options,
                               String... bitFields)
                        throws java.text.ParseException
Parses a String[] array containing a list of options that were provided by a user or in a configuration file, in the same format and with the same semantics as Apache's HTTPd server "Options" and "IndexOptions" directives.

Options are case-insensitive, but the key names must conform to containing only letters, digits, and hyphens, must only begin with a letter, and must end with a letter or a digit.  A maximum length is not imposed.

The following example code demonstrates an application of this method using a variety of "key=value" pair definitions.  Two options are supplied to show how bits 1 and 8 (equivilant to the number 9) are set:

      BigInteger flags = BigInteger.valueOf(0); // Flags (could be inherited
                                                // from a previous assignment)
      String[] args = new String[] {"North", "West"}; // Example options
      Object[] obj; // Multi-dimensional array to be returned
      obj = StringParser.options(flags, args,     // Flags, and user options
                                 "North=1",       // Bit 1        (1)
                                 "East=2",        // Bit 2        (2)
                                 "South=4",       // Bit 3        (4)
                                 "West=8",        // Bit 4        (8)
                                 "NorthEast=3",   // Bits 1 and 2 (1 + 2)
                                 "NorthWest=9",   // Bits 1 and 4 (1 + 8)
                                 "SouthEast=6",   // Bits 2 and 3 (2 + 4)
                                 "SouthWest=12",  // Bits 3 and 4 (4 + 8)
                                 "DebugLevel=+",  // A special parameter
                                 "Nowhere=0",     // Special bit clearing
                                 "None=0");       // Special bit clearing
       flags = (BigInteger)obj[0];
       System.out.println("Flag value: " + flags);
       String[] ary = (String[])obj[1];
       System.out.println("Array size: " + ary.length);
    

Options associated with an asterisk ("*") or a plus sign ("+") support values immediately following the equal sign (the equal sign is only required if a value is specified as "required"):

Options associated with a value of zero cause all bits to be cleared. If this option is combined with other options, or the "+" or "-" prefixes are used, a ParseException exception will be thrown because this type of use is invalid.

Multiple bit field "key=value" pairs may set the same bit(s), which could allow your users to use, for example, abbreviations such as E, SE, etc.

The values that indicate which bit(s) to set are accessed using java.math.BigInteger.testBit(int index) as a convenience to developers.

Parameters:
inheritedFlags - The bit-field to be modified (specify BigInteger.valueOf(0) or NULL if not inheriting an existing bit-field)
options - list of options (each may have an option "+" or "-" prefix); there is no limit to the number of options that can be specified
bitFields - one or more Strings, or an array of Strings, containing case-sensitive "key=value" pairs (using values, rather than a bit number, makes it possible for an option to effect multiple bits); there is no limit to the number of "key=value" pair definitions that can be specified
Returns:
An Object[] array containing one BigInteger object (the flags), and String[] array containing zero or more key=value pairs that don't set any bitFields (because they're defined in "options" with "=?"):

  • Object[0]: BigInteger -- the bit-field of modified flags
  • Object[1]: String[] -- non-bitField options

A minimal mount of type-casting will be required to access these variables, as demonstrated above, unless you're accessing only the flags (in which case the Java compiler will probably assume all objects are of type java.math.BigInteger).

Throws:
java.text.ParseException - When an invalid option is encountered (the offset will reference the offending element in the options[] array)
NumberFormatException - When an invalid number is defined in the list of bitFields (this is a run-time exception that doesn't need to be caught when the bitFields are not user-defined)

options

public static Object[] options(long inheritedFlags,
                               String[] options,
                               String... bitFields)
                        throws java.text.ParseException
Parses a String[] array containing a list of options that were provided by a user or in a configuration file, in the same format and with the same semantics as Apache's HTTPd server "Options" and "IndexOptions" directives.

Options are case-insensitive, but the key names must conform to containing only letters, digits, and hyphens, must only begin with a letter, and must end with a letter or a digit.  A maximum length is not imposed.

The following example code demonstrates an application of this method using a variety of "key=value" pair definitions.  Two options are supplied to show how bits 1 and 8 (equivilant to the number 9) are set:

      long flags = 0; // Flags (could be inherited from a previous assignment)
      String[] args = new String[] {"North", "West"}; // Example options
      Object[] obj; // Multi-dimensional array to be returned
      obj = StringParser.options(flags, args,     // Flags, and user options
                                 "North=1",       // Bit 1        (1)
                                 "East=2",        // Bit 2        (2)
                                 "South=4",       // Bit 3        (4)
                                 "West=8",        // Bit 4        (8)
                                 "NorthEast=3",   // Bits 1 and 2 (1 + 2)
                                 "NorthWest=9",   // Bits 1 and 4 (1 + 8)
                                 "SouthEast=6",   // Bits 2 and 3 (2 + 4)
                                 "SouthWest=12",  // Bits 3 and 4 (4 + 8)
                                 "DebugLevel=+",  // A special parameter
                                 "Nowhere=0",     // Special bit clearing
                                 "None=0");       // Special bit clearing
       flags = (Long)obj[0];
       System.out.println("Flag value: " + flags);
       String[] ary = (String[])obj[1];
       System.out.println("Array size: " + ary.length);
    

Options associated with an asterisk ("*") or a plus sign ("+") support values immediately following the equal sign (the equal sign is only required if a value is specified as "required"):

Options associated with a value of zero cause all bits to be cleared. If this option is combined with other options, or the "+" or "-" prefixes are used, a ParseException exception will be thrown because this type of use is invalid.

Multiple bit field "key=value" pairs may set the same bit(s), which could allow your users to use, for example, abbreviations such as E, SE, etc.

The values that indicate which bit(s) to set are decoded using java.lang.Long.decode() as a convenience to developers who are used to working with bits in different numbering systems such as hexadecimal.

Parameters:
inheritedFlags - The 64-bit field to be modified (specify 0 if not inheriting an existing bit-field)
options - list of options (each may have an option "+" or "-" prefix); there is no limit to the number of options that can be specified
bitFields - one or more Strings, or an array of Strings, containing case-sensitive "key=value" pairs (using values, rather than a bit number, makes it possible for an option to effect multiple bits); there is no limit to the number of "key=value" pair definitions that can be specified
Returns:
An Object[] array containing one Long value (the flags), and String[] array containing zero or more key=value pairs that don't set any bitFields (because they're defined in "options" with "=?"):

  • Object[0]: Long -- the 64-bit-field of modified flags
  • Object[1]: String[] -- non-bitField options

A minimal mount of type-casting will be required to access these variables, as demonstrated above, unless you're accessing only the flags (in which case the Java compiler will probably assume all objects are of type Long).

Throws:
java.text.ParseException - When an invalid option is encountered (the offset will reference the offending element in the options[] array)
NumberFormatException - When an invalid number is defined in the list of bitFields (this is a run-time exception that doesn't need to be caught when the bitFields are not user-defined)

padLeft

public static String padLeft(int minLength,
                             String padding,
                             String data)
Pads the left-hand side of the specified string with the string provided, and without exceeding the minimum length if the padding string contains more than one character.

If the string provided is longer than the specified minimum, or the minimum length is less than or equal to 0, then no padding will be added and the original string will be returned.

If either string is null, then a padded string will be returned instead of throwing a Null Pointer exception.

Parameters:
minLength - The minimum length of the resulting string
padding - The character to use for padding
data - The original string that needs padding
Returns:
The padded version of the original string

padRight

public static String padRight(int minLength,
                              String data,
                              String padding)
Pads the right-hand side of the specified string with the string provided, and without exceeding the minimum length if the padding string contains more than one character.

If the string provided is longer than the specified minimum, or the minimum length is less than or equal to 0, then no padding will be added and the original string will be returned.

If either string is null, then a padded string will be returned instead of throwing a Null Pointer exception.

Parameters:
minLength - The minimum length of the resulting string
data - The original string that needs padding
padding - The character to use for padding
Returns:
The padded version of the original string

parseBoolean

public static boolean parseBoolean(String number,
                                   boolean exception,
                                   String... specials)
Converts a String containing a state to a special (optional) or a boolean (in that order), and returns the specified boolean in place of throwing java.lang.NumberFormatException.

The special "key=value" pairs can either be passed as one or more separate strings, or as a String[] array. To set a special value for a null String, use a blank key as in "=value" (e.g., "=false" to have it set to false).

This method can be particularly useful in a "switch" code block since Java does not support the use of strings. For example:

String text = "on";
boolean value = ParseLong(text, false, "=false", "on=true", "1=true", "one=true", "yes=true", "valid=true", "enable=true", "enabled=true");
switch (value) {
  case false: { ...code for false... };
  case true: { ...code for true... };
}

A String containing the text "null" is not the same as a null (undefined) String, and this method differentiates between the two by requiring that an empty key name be used to set a value for an undefined String object.

Parameters:
number - The String containing a set of digits to be converted
exception - The boolean to return if the String provided does not contain a parsable number
specials - Optional, one or more Strings, or an array of Strings, containing case-sensitive "key=value" pairs
Returns:
Primitive boolean

parseByte

public static byte parseByte(String number,
                             byte exception,
                             String... specials)
Converts a String containing a number to a special (optional) or a byte integer (in that order), and returns the specified byte integer in place of throwing java.lang.NumberFormatException.

The special "key=value" pairs can either be passed as one or more separate strings, or as a String[] array. To set a special value for a null String, use a blank key as in "=value" (e.g., "=0" to have it set to zero).

This method can be particularly useful in a "switch" code block since Java does not support the use of strings. For example:

String text = "unlimited";
byte value = ParseLong(text, -1, "unlimited=-2", "=0", "one=1", "two=2");
switch (value) {
  case -2: { ...code for unlimited selection... };
  case -1: { ...code for invalid number format... };
  case  0: { ...code for zero... };
  case  1: { ...code for one... };
  case  2: { ...code for two... };
  default: { ...code for all other valid numbers... };
}

A String containing the text "null" is not the same as a null (undefined) String, and this method differentiates between the two by requiring that an empty key name be used to set a value for an undefined String object.

Parameters:
number - The String containing a set of digits to be converted
exception - The byte integer to return if the String provided does not contain a parsable number
specials - Optional, one or more Strings, or an array of Strings, containing case-sensitive "key=value" pairs
Returns:
Primitive byte integer

parseDouble

public static double parseDouble(String number,
                                 double exception,
                                 String... specials)
Converts a String containing a number to a special (optional) or a double (in that order), and returns the specified double in place of throwing java.lang.NumberFormatException.

The special "key=value" pairs can either be passed as one or more separate strings, or as a String[] array. To set a special value for a null String, use a blank key as in "=value" (e.g., "=0" to have it set to zero).

This method can be particularly useful in a "switch" code block since Java does not support the use of strings. For example:

String text = "unlimited";
double value = ParseLong(text, -1, "unlimited=-2", "=0", "one=1", "two=2");
switch (value) {
  case -2: { ...code for unlimited selection... };
  case -1: { ...code for invalid number format... };
  case  0: { ...code for zero... };
  case  1: { ...code for one... };
  case  2: { ...code for two... };
  default: { ...code for all other valid numbers... };
}

A String containing the text "null" is not the same as a null (undefined) String, and this method differentiates between the two by requiring that an empty key name be used to set a value for an undefined String object.

Parameters:
number - The String containing a set of digits to be converted
exception - The double to return if the String provided does not contain a parsable number
specials - Optional, one or more Strings, or an array of Strings, containing case-sensitive "key=value" pairs
Returns:
Primitive double

parseFloat

public static float parseFloat(String number,
                               float exception,
                               String... specials)
Converts a String containing a number to a special (optional) or a float (in that order), and returns the specified float in place of throwing java.lang.NumberFormatException.

The special "key=value" pairs can either be passed as one or more separate strings, or as a String[] array. To set a special value for a null String, use a blank key as in "=value" (e.g., "=0" to have it set to zero).

This method can be particularly useful in a "switch" code block since Java does not support the use of strings. For example:

String text = "unlimited";
float value = ParseLong(text, -1, "unlimited=-2", "=0", "one=1", "two=2");
switch (value) {
  case -2: { ...code for unlimited selection... };
  case -1: { ...code for invalid number format... };
  case  0: { ...code for zero... };
  case  1: { ...code for one... };
  case  2: { ...code for two... };
  default: { ...code for all other valid numbers... };
}

A String containing the text "null" is not the same as a null (undefined) String, and this method differentiates between the two by requiring that an empty key name be used to set a value for an undefined String object.

Parameters:
number - The String containing a set of digits to be converted
exception - The float to return if the String provided does not contain a parsable number
specials - Optional, one or more Strings, or an array of Strings, containing case-sensitive "key=value" pairs
Returns:
Primitive float

parseInt

public static int parseInt(String number,
                           int exception,
                           String... specials)
Converts a String containing a number to a special (optional) or an integer (in that order), and returns the specified integer in place of throwing java.lang.NumberFormatException.

The special "key=value" pairs can either be passed as one or more separate strings, or as a String[] array. To set a special value for a null String, use a blank key as in "=value" (e.g., "=0" to have it set to zero).

This method can be particularly useful in a "switch" code block since Java does not support the use of strings. For example:

String text = "unlimited"; // We expect a special value of -2...
int value = ParseInt(text, -1, "unlimited=-2", "=0", "one=1", "two=2");
switch (value) {
  case -2: { ...code for unlimited selection... };
  case -1: { ...code for invalid number format... };
  case  0: { ...code for zero... };
  case  1: { ...code for one... };
  case  2: { ...code for two... };
  default: { ...code for all other valid numbers... };
}

A String containing the text "null" is not the same as a null (undefined) String, and this method differentiates between the two by requiring that an empty key name be used to set a value for an undefined String object.

Parameters:
number - The String containing a set of digits to be converted
exception - The integer to return if the String provided does not contain a parsable number
specials - Optional, one or more Strings, or an array of Strings, containing case-sensitive "key=value" pairs
Returns:
Primitive integer

parseLong

public static long parseLong(String number,
                             long exception,
                             String... specials)
Converts a String containing a number to a special (optional) or a long integer (in that order), and returns the specified long integer in place of throwing java.lang.NumberFormatException.

The special "key=value" pairs can either be passed as one or more separate strings, or as a String[] array. To set a special value for a null String, use a blank key as in "=value" (e.g., "=0" to have it set to zero).

This method can be particularly useful in a "switch" code block since Java does not support the use of strings. For example:

String text = "unlimited";
long value = ParseLong(text, -1, "unlimited=-2", "=0", "one=1", "two=2");
switch (value) {
  case -2: { ...code for unlimited selection... };
  case -1: { ...code for invalid number format... };
  case  0: { ...code for zero... };
  case  1: { ...code for one... };
  case  2: { ...code for two... };
  default: { ...code for all other valid numbers... };
}

A String containing the text "null" is not the same as a null (undefined) String, and this method differentiates between the two by requiring that an empty key name be used to set a value for an undefined String object.

Parameters:
number - The String containing a set of digits to be converted
exception - The long integer to return if the String provided does not contain a parsable number
specials - Optional, one or more Strings, or an array of Strings, containing case-sensitive "key=value" pairs
Returns:
Primitive long integer

parseNybble

public static byte parseNybble(String number,
                               byte exception,
                               String... specials)
Converts a String containing a number to a special (optional) or a nybble (in that order), represented by a byte, and returns the specified nybble (which must also be within the range of a nybble), also represented by a byte, in place of throwing java.lang.NumberFormatException. Since there is no primitive type in Java for a nybble, byte is used instead.

The special "key=value" pairs can either be passed as one or more separate strings, or as a String[] array. To set a special value for a null String, use a blank key as in "=value" (e.g., "=0" to have it set to zero).

This method can be particularly useful in a "switch" code block since Java does not support the use of strings. For example:

String text = "unlimited";
byte value = ParseNybble(text, -1, "unlimited=-2", "=0", "one=1", "two=2");
switch (value) {
  case -2: { ...code for unlimited selection... };
  case -1: { ...code for invalid number format... };
  case  0: { ...code for zero... };
  case  1: { ...code for one... };
  case  2: { ...code for two... };
  default: { ...code for all other valid numbers... };
}

A String containing the text "null" is not the same as a null (undefined) String, and this method differentiates between the two by requiring that an empty key name be used to set a value for an undefined String object.

Parameters:
number - The String containing a set of digits to be converted
exception - The nybble, represented as a byte, to return if the String provided does not contain a parsable number (if "exception" is out of range for a Nybble, then excess bits will be truncated automatically)
specials - Optional, one or more Strings, or an array of Strings, containing case-sensitive "key=value" pairs
Returns:
Primitive byte, representing a nybble

parseShort

public static short parseShort(String number,
                               short exception,
                               String... specials)
Converts a String containing a number to a special (optional) or a short integer (in that order), and returns the specified short integer in place of throwing java.lang.NumberFormatException.

The special "key=value" pairs can either be passed as one or more separate strings, or as a String[] array. To set a special value for a null String, use a blank key as in "=value" (e.g., "=0" to have it set to zero).

This method can be particularly useful in a "switch" code block since Java does not support the use of strings. For example:

String text = "unlimited";
short value = ParseLong(text, -1, "unlimited=-2", "=0", "one=1", "two=2");
switch (value) {
  case -2: { ...code for unlimited selection... };
  case -1: { ...code for invalid number format... };
  case  0: { ...code for zero... };
  case  1: { ...code for one... };
  case  2: { ...code for two... };
  default: { ...code for all other valid numbers... };
}

A String containing the text "null" is not the same as a null (undefined) String, and this method differentiates between the two by requiring that an empty key name be used to set a value for an undefined String object.

Parameters:
number - The String containing a set of digits to be converted
exception - The short integer to return if the String provided does not contain a parsable number
specials - Optional, one or more Strings, or an array of Strings, containing case-sensitive "key=value" pairs
Returns:
Primitive short integer

parseVeryLong

public static VeryLong parseVeryLong(String number,
                                     VeryLong exception,
                                     String... specials)
Converts a String containing a number to a special (optional) or VeryLong (in that order), and returns the specified VeryLong (which must also be within the range of a nybble), also represented by a byte, in place of throwing java.lang.NumberFormatException. Since there is no primitive type in Java for a VeryLong, a VeryLong object is simply returned.

The special "key=value" pairs can either be passed as one or more separate strings, or as a String[] array. To set a special value for a null String, use a blank key as in "=value" (e.g., "=0" to have it set to zero).

A String containing the text "null" is not the same as a null (undefined) String, and this method differentiates between the two by requiring that an empty key name be used to set a value for an undefined String object.

Parameters:
number - The String containing a set of digits to be converted
exception - The VeryLong object to return if the String provided does not contain a parsable number
specials - Optional, one or more Strings, or an array of Strings, containing case-sensitive "key=value" pairs
Returns:
VeryLong object

quote

public static String quote(String string)
Adds quotes around strings (the opposite of the trimQuotes() method, and the de-quoting that the atomize() method performs).

Unlike the quoteMinimal() method, quotes are always added regardless of the existence of tabs or spaces in the original string.  Every quotation mark (") and backslash (\) in the original string will be prefixed by a backslash before the final set of enclosing quotation marks is added:

" becomes \"
\ becomes \\

No other characters in the string will be effected.

Parameters:
string - The original String
Returns:
The string, quoted

quoteMinimal

public static String quoteMinimal(String string)
Adds quotes around strings (the opposite of the trimQuotes() method, and the de-quoting that the atomize() method performs).

Quotes are only added if any tabs or spaces are encountered in the original string.  Every quotation mark (") and backslash (\) in the original string will be prefixed by a backslash before the final set of enclosing quotation marks is added:

" becomes \"
\ becomes \\

No other characters in the string will be effected.

Parameters:
string - The original String
Returns:
The string, quoted as needed

refineDomainLiteral

public static String refineDomainLiteral(String address)
Formats a domain literal to its most acceptable format, that is expected and most easily interpreted by computing systems.  Leading zeros are removed from all octets, and the double colons are replaced with the correct number of single-digit zeros (which eliminates the shortcuts that may be considered unpredictable).

The refined domain literal is useful where the predictable form of a domain literal is needed, such as for a list that is used to prevent duplicate addresses from being specified by a user despite all their efforts to circumvent your policies by using inconsistent data entry styles.

A runtime Exception is thrown if the format is invalid, so you only need to catch this exception if there is any possibility that it may be invalid (if it already passed an isDomainLiteral() method test, then it won't fail).

Parameters:
address - String containing IPv4 or IPv6 domain literal to refine
Returns:
String The refined domain literal
Throws:
IllegalArgumentException - (Catch is not required unless there is any possibility that the format could be invalid)
See Also:
isDomainLiteral(java.lang.String)

refineDomainLiteral4

public static String refineDomainLiteral4(String address)
Formats a domain literal to its most acceptable format, that is expected and most easily interpreted by computing systems.  Leading zeros are removed from all octets.

The refined domain literal is useful where the predictable form of a domain literal is needed, such as for a list that is used to prevent duplicate addresses from being specified by a user despite all their efforts to circumvent your policies by using inconsistent data entry styles.

A runtime Exception is thrown if the format is invalid, so you only need to catch this exception if there is any possibility that it may be invalid (if it already passed an isDomainLiteral4() method test, then it won't fail).

Parameters:
address - String containing IPv4 domain literal to refine
Returns:
String The refined IPv4 domain literal
Throws:
IllegalArgumentException - (Catch is not required unless there is any possibility that the format could be invalid)
See Also:
isDomainLiteral4(java.lang.String)

refineDomainLiteral6

public static String refineDomainLiteral6(String address)
Formats a domain literal to its most acceptable format, that is expected and most easily interpreted by computing systems.  Leading zeros are removed from all octets, and the double colons are replaced with the correct number of single-digit zeros (which eliminates the shortcuts that may be considered unpredictable).

The refined domain literal is useful where the predictable form of a domain literal is needed, such as for a list that is used to prevent duplicate addresses from being specified by a user despite all their efforts to circumvent your policies by using inconsistent data entry styles.

A runtime Exception is thrown if the format is invalid, so you only need to catch this exception if there is any possibility that it may be invalid (if it already passed an isDomainLiteral6() method test, then it won't fail).

Parameters:
address - String containing IPv6 domain literal to refine
Returns:
String The refined domain literal
Throws:
IllegalArgumentException - (Catch is not required unless there is any possibility that the format could be invalid)
See Also:
isDomainLiteral6(java.lang.String)

refineIPAddress

public static String refineIPAddress(String address)
Formats an IP address to its most acceptable format, that is expected and most easily interpreted by computing systems.  Leading zeros are removed from all octets, and the double colons are replaced with the correct number of single-digit zeros (which eliminates the shortcuts that may be considered unpredictable).

The refined address is useful where the predictable form of an IP address is needed, such as for a list that is used to prevent duplicate addresses from being specified by a user despite all their efforts to circumvent your policies by using inconsistent data entry styles.

A runtime Exception is thrown if the format is invalid, so you only need to catch this exception if there is any possibility that it may be invalid (if it already passed an isIPAddress() method test, then it won't fail).

Parameters:
address - String containing IPv4 or IPv6 address to refine
Returns:
String The refined IP address
Throws:
IllegalArgumentException - (Catch is not required unless there is any possibility that the format could be invalid)
See Also:
isIPAddressRelaxed(java.lang.String)

refineIPv4Address

public static String refineIPv4Address(String address)
Formats an IP address to its most acceptable format, that is expected and most easily interpreted by computing systems.  Leading zeros are removed from all octets.

The refined address is useful where the predictable form of an IP address is needed, such as for a list that is used to prevent duplicate addresses from being specified by a user despite all their efforts to circumvent your policies by using inconsistent data entry styles.

A runtime Exception is thrown if the format is invalid, so you only need to catch this exception if there is any possibility that it may be invalid (if it already passed an isIPv4Address() method test, then it won't fail).

Parameters:
address - String containing IPv4 address to refine
Returns:
String The refined IPv4 address
Throws:
IllegalArgumentException - (Catch is not required unless there is any possibility that the format could be invalid)
See Also:
isIPv4AddressRelaxed(java.lang.String)

refineIPv6Address

public static String refineIPv6Address(String address)
Formats an IP address to its most acceptable format, that is expected and most easily interpreted by computing systems.  Leading zeros are removed from all octets, and the double colons are replaced with the correct number of single-digit zeros (which eliminates the shortcuts that may be considered unpredictable).

The refined address is useful where the predictable form of an IP address is needed, such as for a list that is used to prevent duplicate addresses from being specified by a user despite all their efforts to circumvent your policies by using inconsistent data entry styles.

A runtime Exception is thrown if the format is invalid, so you only need to catch this exception if there is any possibility that it may be invalid (if it already passed an isIPv6Address() method test, then it won't fail).

Parameters:
address - String containing IPv6 address to refine
Returns:
String The refined IP address
Throws:
IllegalArgumentException - (Catch is not required unless there is any possibility that the format could be invalid)
See Also:
isIPv6Address(java.lang.String)

refineSASLExchange

public static HashMap<String,String[]> refineSASLExchange(String unparsedString)
                                                   throws java.text.ParseException
Parses a SASL Exchange (must not be Base64-encoded), as demonstrated in RFC 2831, returning all elements as a HashMap object containing String[] arrays.

A "SASL Exchange" is a string of comma-delimited "key=value" pairs (some RFCs use the word "token" instead of "key") which may not contain any extraneous whitespace characters [except within pairs of quotation marks], and only values may be enclosed within quotation marks (usually only seen for values that are not purely numeric).

Although RFC 2831 mentions that a quotation mark may be escaped, it doesn't directly define the escape mechanism. However, since a back-slash ("\") character does indicate that the next character to follow is literal, we interpret this as what was implied. Such literal character sequences are supported accordingly.

Depending on the application, certain values may only be defined once, or have some other similar limit imposed. Testing the length of the String[] array associated with a particular key in the returned HashMap is probably the simplest way for a developer to implement such requirements.

Parameters:
unparsedString - The SASL Exchange string to parse (if NULL, an empty HashMap will be returned)
Returns:
java.util.HashMap containing the refined SASL Exchange (every String[] array will contain 1 or more elements), with one additional "null" entry that yields an array of key names as a convenience for easy processing in a foreach loop (all key names are case-sensitive)
Throws:
java.text.ParseException - When an invalid character or a formatting error is encountered in; the offset will reference the position in the unparsedString where the error was encountered
See Also:
Hash.SASLDigestResponse(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, boolean, java.lang.String, java.lang.String)

splitPairs

public static String[] splitPairs(String pairs,
                                  String... keys)
Parses a String containing white-space delimited "key=value" pairs, and returns a String[] array containing only values that correspond with the specified key(s), thus consistently placing every value in a specific position in the array to simplify string parsing, in a flexible manner.

The rules for parsing are:

The "pairs" String in the following example of an imaginary internet server configuration file directive's parameters demonstrates how the order of the keys takes precedence:

String pairs = "ip=10.88.88.88 backlog=128 port=8";
String[] values = StringParser.splitPairs(pairs, "ip", "port", "backlog");

The resulting values[] String array contains the following three elements (notice that the order is, as expected, consistent with the key order, rather than the original "pairs" String):

  1. 10.88.88.88
  2. 8
  3. 128

The size of the resulting array will always match the number of keys that were specified, thus an empty array will result if no keys are specified.

Parameters:
pairs - White-space delimited "key=value" pairs (can be in any order)
keys - One or more keys (or a String[] array of keys) which are valid
Returns:
A string array[] of values in "key" order

substring

public static String substring(String string,
                               int beginIndex)
An improved version of java.lang.String.substring() that handles negative values logically by processing from the end of the string.

If the index is higher than the length of the string, a blank string is returned instead of throwing an Exception.

If the [mathematically] absolute value of the index is higher than the length of the string, the entire string is returned instead of throwing an Exception.

Parameters:
string - The original String
beginIndex - The beginning index, inclusive, or the number of characters to return from the end of the String if the value is negative
Returns:
The specified substring

transmuteBoolean

public static boolean transmuteBoolean(String phrase,
                                       boolean exception,
                                       String... specials)
Transmutes a String to a boolean based on the list of specials (the phrases and their corresponding values), and returns the specified boolean.

The special "key=value" pairs can either be passed as one or more separate strings, or as a String[] array. To set a special value for a null String, use a blank key as in "=value" (e.g., "=0" to have it set to zero).

This method can be particularly useful in a "switch" code block since Java does not support the use of strings. For example:

String text = "on";
boolean value = transmuteBoolean(text, false, "=false", "on=true", "1=true", "one=true", "yes=true", "valid=true", "enable=true", "enabled=true");
switch (value) {
  case false: { ...code for false... };
  case true: { ...code for true... };
}

A String containing the text "null" is not the same as a null (undefined) String, and this method differentiates between the two by requiring that an empty key name be used to set a value for an undefined String object.

Parameters:
phrase - The String containing a phrase to be transmuted
exception - The boolean to return if the String provided is not included in the list of phrases
specials - Optional (although not specifying any specials is pointless), one or more Strings, or an array of Strings, containing case-sensitive "key=value" pairs
Returns:
Primitive boolean

transmuteByte

public static byte transmuteByte(String phrase,
                                 byte exception,
                                 String... specials)
Transmutes a String to a byte integer based on the list of specials (the phrases and their corresponding values), and returns the specified byte integer.

The special "key=value" pairs can either be passed as one or more separate strings, or as a String[] array. To set a special value for a null String, use a blank key as in "=value" (e.g., "=0" to have it set to zero).

This method can be particularly useful in a "switch" code block since Java does not support the use of strings. For example:

String text = "unlimited";
byte value = transmuteByte(text, -1, "unlimited=-2", "=0", "one=1", "two=2");
switch (value) {
  case -2: { ...code for unlimited selection... };
  case -1: { ...code for all invalid strings... };
  case  0: { ...code for zero... };
  case  1: { ...code for one... };
  case  2: { ...code for two... };
}

A String containing the text "null" is not the same as a null (undefined) String, and this method differentiates between the two by requiring that an empty key name be used to set a value for an undefined String object.

Parameters:
phrase - The String containing a phrase to be transmuted
exception - The byte integer to return if the String provided is not included in the list of phrases
specials - Optional (although not specifying any specials is pointless), one or more Strings, or an array of Strings, containing case-sensitive "key=value" pairs
Returns:
Primitive byte integer

transmuteDouble

public static double transmuteDouble(String phrase,
                                     double exception,
                                     String... specials)
Transmutes a String to a double based on the list of specials (the phrases and their corresponding values), and returns the specified double.

The special "key=value" pairs can either be passed as one or more separate strings, or as a String[] array. To set a special value for a null String, use a blank key as in "=value" (e.g., "=0" to have it set to zero).

This method can be particularly useful in a "switch" code block since Java does not support the use of strings. For example:

String text = "unlimited";
double value = transmuteDouble(text, -1, "unlimited=-2", "=0", "one=1", "two=2");
switch (value) {
  case -2: { ...code for unlimited selection... };
  case -1: { ...code for all invalid strings... };
  case  0: { ...code for zero... };
  case  1: { ...code for one... };
  case  2: { ...code for two... };
}

A String containing the text "null" is not the same as a null (undefined) String, and this method differentiates between the two by requiring that an empty key name be used to set a value for an undefined String object.

Parameters:
phrase - The String containing a phrase to be transmuted
exception - The double to return if the String provided is not included in the list of phrases
specials - Optional (although not specifying any specials is pointless), one or more Strings, or an array of Strings, containing case-sensitive "key=value" pairs
Returns:
Primitive double

transmuteFloat

public static float transmuteFloat(String phrase,
                                   float exception,
                                   String... specials)
Transmutes a String to a float based on the list of specials (the phrases and their corresponding values), and returns the specified float.

The special "key=value" pairs can either be passed as one or more separate strings, or as a String[] array. To set a special value for a null String, use a blank key as in "=value" (e.g., "=0" to have it set to zero).

This method can be particularly useful in a "switch" code block since Java does not support the use of strings. For example:

String text = "unlimited";
float value = transmuteFloat(text, -1, "unlimited=-2", "=0", "one=1", "two=2");
switch (value) {
  case -2: { ...code for unlimited selection... };
  case -1: { ...code for all invalid strings... };
  case  0: { ...code for zero... };
  case  1: { ...code for one... };
  case  2: { ...code for two... };
}

A String containing the text "null" is not the same as a null (undefined) String, and this method differentiates between the two by requiring that an empty key name be used to set a value for an undefined String object.

Parameters:
phrase - The String containing a phrase to be transmuted
exception - The float to return if the String provided is not included in the list of phrases
specials - Optional (although not specifying any specials is pointless), one or more Strings, or an array of Strings, containing case-sensitive "key=value" pairs
Returns:
Primitive float

transmuteInt

public static int transmuteInt(String phrase,
                               int exception,
                               String... specials)
Transmutes a String to an integer based on the list of specials (the phrases and their corresponding values), and returns the specified integer.

The special "key=value" pairs can either be passed as one or more separate strings, or as a String[] array. To set a special value for a null String, use a blank key as in "=value" (e.g., "=0" to have it set to zero).

This method can be particularly useful in a "switch" code block since Java does not support the use of strings. For example:

String text = "unlimited";
int value = transmuteInt(text, -1, "unlimited=-2", "=0", "one=1", "two=2");
switch (value) {
  case -2: { ...code for unlimited selection... };
  case -1: { ...code for all invalid strings... };
  case  0: { ...code for zero... };
  case  1: { ...code for one... };
  case  2: { ...code for two... };
}

A String containing the text "null" is not the same as a null (undefined) String, and this method differentiates between the two by requiring that an empty key name be used to set a value for an undefined String object.

Parameters:
phrase - The String containing a phrase to be transmuted
exception - The integer to return if the String provided is not included in the list of phrases
specials - Optional (although not specifying any specials is pointless), one or more Strings, or an array of Strings, containing case-sensitive "key=value" pairs
Returns:
Primitive integer

transmuteLong

public static long transmuteLong(String phrase,
                                 long exception,
                                 String... specials)
Transmutes a String to a long integer based on the list of specials (the phrases and their corresponding values), and returns the specified long integer.

The special "key=value" pairs can either be passed as one or more separate strings, or as a String[] array. To set a special value for a null String, use a blank key as in "=value" (e.g., "=0" to have it set to zero).

This method can be particularly useful in a "switch" code block since Java does not support the use of strings. For example:

String text = "unlimited";
long value = transmuteLong(text, -1, "unlimited=-2", "=0", "one=1", "two=2");
switch (value) {
  case -2: { ...code for unlimited selection... };
  case -1: { ...code for all invalid strings... };
  case  0: { ...code for zero... };
  case  1: { ...code for one... };
  case  2: { ...code for two... };
}

A String containing the text "null" is not the same as a null (undefined) String, and this method differentiates between the two by requiring that an empty key name be used to set a value for an undefined String object.

Parameters:
phrase - The String containing a phrase to be transmuted
exception - The long integer to return if the String provided is not included in the list of phrases
specials - Optional (although not specifying any specials is pointless), one or more Strings, or an array of Strings, containing case-sensitive "key=value" pairs
Returns:
Primitive long integer

transmuteNybble

public static byte transmuteNybble(String phrase,
                                   byte exception,
                                   String... specials)
Transmutes a String to a nybble integer based on the list of specials (the phrases and their corresponding values), and returns the specified nybble integer represented by a byte.

The special "key=value" pairs can either be passed as one or more separate strings, or as a String[] array. To set a special value for a null String, use a blank key as in "=value" (e.g., "=0" to have it set to zero).

This method can be particularly useful in a "switch" code block since Java does not support the use of strings. For example:

String text = "unlimited";
byte value = transmuteNybble(text, -1, "unlimited=-2", "=0", "one=1", "two=2");
switch (value) {
  case -2: { ...code for unlimited selection... };
  case -1: { ...code for all invalid strings... };
  case  0: { ...code for zero... };
  case  1: { ...code for one... };
  case  2: { ...code for two... };
}

A String containing the text "null" is not the same as a null (undefined) String, and this method differentiates between the two by requiring that an empty key name be used to set a value for an undefined String object.

Parameters:
phrase - The String containing a phrase to be transmuted
exception - The nybble integer, represented as a byte, to return if the String provided is not included in the list of phrases
specials - Optional (although not specifying any specials is pointless), one or more Strings, or an array of Strings, containing case-sensitive "key=value" pairs
Returns:
Primitive byte integer representing a nybble

transmuteShort

public static short transmuteShort(String phrase,
                                   short exception,
                                   String... specials)
Transmutes a String to a short integer based on the list of specials (the phrases and their corresponding values), and returns the specified short integer.

The special "key=value" pairs can either be passed as one or more separate strings, or as a String[] array. To set a special value for a null String, use a blank key as in "=value" (e.g., "=0" to have it set to zero).

This method can be particularly useful in a "switch" code block since Java does not support the use of strings. For example:

String text = "unlimited";
short value = transmuteShort(text, -1, "unlimited=-2", "=0", "one=1", "two=2");
switch (value) {
  case -2: { ...code for unlimited selection... };
  case -1: { ...code for all invalid strings... };
  case  0: { ...code for zero... };
  case  1: { ...code for one... };
  case  2: { ...code for two... };
}

A String containing the text "null" is not the same as a null (undefined) String, and this method differentiates between the two by requiring that an empty key name be used to set a value for an undefined String object.

Parameters:
phrase - The String containing a phrase to be transmuted
exception - The short integer to return if the String provided is not included in the list of phrases
specials - Optional (although not specifying any specials is pointless), one or more Strings, or an array of Strings, containing case-sensitive "key=value" pairs
Returns:
Primitive short integer

transmuteVeryLong

public static VeryLong transmuteVeryLong(String phrase,
                                         VeryLong exception,
                                         String... specials)
Transmutes a String to a VeryLong object based on the list of specials (the phrases and their corresponding values), and returns the specified VeryLong object represented by a VeryLong object (because a native equiviliant isn't currently available).

The special "key=value" pairs can either be passed as one or more separate strings, or as a String[] array. To set a special value for a null String, use a blank key as in "=value" (e.g., "=0" to have it set to zero).

A String containing the text "null" is not the same as a null (undefined) String, and this method differentiates between the two by requiring that an empty key name be used to set a value for an undefined String object.

Parameters:
phrase - The String containing a phrase to be transmuted
exception - The VeryLong object to return if the String provided is not included in the list of phrases
specials - Optional (although not specifying any specials is pointless), one or more Strings, or an array of Strings, containing case-sensitive "key=value" pairs
Returns:
VeryLong object

trimQuotes

public static String trimQuotes(String string)
Removes the outer-most/enclosing set of quotation marks from the beginning and end of the specified String, but only if both are present.

Parameters:
string - The original String
Returns:
The string, but without the outer-most/enclosing set of quotation marks

x

public static String x(String string,
                       int repeat)
Works like Perl's x operator in that it returns the string repeated and joined immediately to itself x times.

Parameters:
string - The original String
repeat - Number of times to repeat the string (any value less than 1 will return an empty string)
Returns:
The repeated string (or an empty string, will never be null)