Class StringUtilities
- java.lang.Object
-
- com.biomatters.geneious.publicapi.utilities.StringUtilities
-
public class StringUtilities extends java.lang.Object
Provides utility methods for creating and manipulating Strings.
-
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static java.lang.String
bytesToString(long bytes)
Format a byte count to be human friendly.static java.lang.String
capitalize(java.lang.String text)
static <T> java.lang.String
collectionToString(java.util.Collection<T> values)
A generic method for turning a collection into a pretty looking String.static java.lang.String
commaFormat(double value, int decimalPlaces)
Formats the given number with commas every 3rd digit and the specified number of decimal places of accuracy.static java.lang.String
commaFormat(long value)
Formats the given number with commas every 3rd digit.static java.lang.String
createHyperlink(java.lang.String linkText, java.lang.String url)
Returns a hyperlink from the given text to the url for use in html, by surrounding the linkText with an href tag.static java.lang.String
createString(char[] characters)
Creates a new String from a character array by calling the String package private constructor:String#String(int, int, char[])
which shares the char[] value array for speed and lowers memory usage since we don't need to have 2 copies of the char[] in memory at once.static java.lang.String
createString(int offset, int length, char[] characters)
Creates a new String from a character array by calling the String package private constructor:String#String(int,int,char[])
which shares the char[] value array for speed and lowers memory usage since we don't need to have 2 copies of the char[] in memory at once.static java.lang.String
delete(java.lang.String stringToDeleteCharacterFrom, char charToDelete)
Creates a new string identical to stringToDeleteCharacterFrom except with all instances of the given character removed.static java.lang.String
escapeHtmlCharacters(java.lang.String text)
Escapes all of the HTML reserved characters in the given string, replacing them with equivalent HTML entities.static java.lang.String
extract(java.lang.StringBuilder builder)
Extracts the result of a StringBuilder using less memory than StringBuilder.toString().static java.lang.String
formatDateNicely(java.util.Date date, boolean displayRelativeTimes)
Nicely formats a Date in the Geneious style.static java.lang.String
formatDouble(double value, int decimalPlaces, boolean commasEveryThirdDigit)
Formats the given number with optional commas every 3rd digit and the specified number of decimal places of accuracy.static java.lang.String
formatElement(org.jdom.Element element)
Prints an Element in pretty format (Format.getPrettyFormat()
) to a String and returns that String.static java.lang.String
formatElementPreserveText(org.jdom.Element element)
Prints an Element in pretty format similar to (Format.getPrettyFormat()
) and returns that String.static java.lang.String
formatElementRaw(org.jdom.Element element)
Prints an Element in raw format (Format.getRawFormat()
) to a String and returns that String.static java.lang.String
formatPercentage(double percentage, int digitsAfterDecimalPoint)
Format a percentage to the number of decimal places specified.static java.lang.String
formatStackTrace(java.lang.Throwable throwable)
Prints the stacktrace associated with a Throwable to a String and returns the String.static java.lang.String
getHexString(byte[] bytes)
static java.lang.String
getNicelyFormattedDuration(long durationInMicroSeconds)
Converts microseconds into a nicely formatted millisecond stringstatic java.lang.String
getTextFromInputStream(java.io.InputStream stream, boolean closeInputStream)
Reads an InputStream into a string until the end of the stream is reached.static java.lang.String
getTextFromReader(java.io.Reader reader, boolean closeReader)
Reads a reader into a string until the end of the stream is reached.static java.lang.String
humanJoin(java.lang.Iterable values)
Like join(", ", values), except that the last value is separated with " and " instead of ", ".static java.lang.String
join(java.lang.String separator, java.lang.Iterable values)
Concatenates values (calling toString() on each of them), interleaved with the separator string.static java.lang.String
listToString(java.util.List<java.lang.String> list)
Converts a list of Strings into a single String which can be converted back to a list viastringToList(String)
static java.lang.String
listToString(java.util.List<java.lang.String> list, int maxLength)
Converts a list of Strings into a single String which can be converted back to a list viastringToList(String)
static org.jdom.Element
parseElement(java.lang.String elementText)
Parses some XML.static org.jdom.Element
parseElementPreserveText(java.lang.String elementText)
Parses some XML text which was generated usingformatElementPreserveText(org.jdom.Element)
.static java.util.List<java.lang.String>
splitIntoLines(java.lang.String s)
Splits a String into the lines it consists of, with any of the standard newlines (\r, \n or \r\n) being accepted (as by a BufferedReader).static java.util.List<java.lang.String>
stringToList(java.lang.String string)
Converts a String created usinglistToString(java.util.List)
back into a list of Strings.static java.lang.String
stripHtmlTags(java.lang.String string, boolean onlyIfStartsWithHtmlTag)
Strips all html tags and their contents from the provided Stringstatic java.lang.String
trimToLength(java.lang.String string, int maximumLength, boolean appendDotsIfTruncated)
Trims this string so that it is at most maximumLength characters long.
-
-
-
Method Detail
-
extract
public static java.lang.String extract(java.lang.StringBuilder builder)
Extracts the result of a StringBuilder using less memory than StringBuilder.toString(). Normally, StringBuilder.toString() allocates new memory for a string, so it effectively requires twice as much memory as the String requires to build a string using StringBuilder. By using this method instead, the memory into which the StringBuilder builds the String is used for the returned String. This method has the additional side effect of clearing the contents of the StringBuilder. Implementing this requires the package private constructor String(int,int,char[]) which is package private so that nothing can corrupt the contents of a String once it has been created. This method is implemented safely so that it discards the char[] used to initialise the String immediately to prevent this happening. Note: accessing the package private String constructor is slow, so this method only uses the efficient call if the StringBuilder's length is greater than 100,000 characters. On smaller StringBuilder's the memory inefficient (but faster)StringBuilder.toString()
method is used.- Parameters:
builder
- the StringBuilder from which to extract the String. This StringBuilder must have capacity equal to its length to avoid excessive memory usage problems. The contents of this StringBuilder will be cleared before this method returns.- Returns:
- the extracted String.
- Throws:
java.lang.IllegalArgumentException
- if the StringBuilder'scapacity
is not the same as itslength
.
-
collectionToString
public static <T> java.lang.String collectionToString(java.util.Collection<T> values)
A generic method for turning a collection into a pretty looking String.- Type Parameters:
T
- The Type of this Collection- Parameters:
values
- The Collection- Returns:
- A nicely formatted string of this collection
- Since:
- API 4.202220 (Geneious 2022.2.0)
-
getNicelyFormattedDuration
public static java.lang.String getNicelyFormattedDuration(long durationInMicroSeconds)
Converts microseconds into a nicely formatted millisecond string- Parameters:
durationInMicroSeconds
- The time to format in microseconds- Returns:
- The nicely formatted String in milliseconds
- Since:
- API 4.202220 (Geneious 2022.2.0)
-
createString
public static java.lang.String createString(char[] characters)
Creates a new String from a character array by calling the String package private constructor:String#String(int, int, char[])
which shares the char[] value array for speed and lowers memory usage since we don't need to have 2 copies of the char[] in memory at once. The created String is equal in length the supplied character array. WARNING: take extreme care when using this method, anything that uses this should not modify Mcharacters
afterwards and should probably immediately discard any reference to it. The package private String constructor was removed in Java 9, so this method just uses the inefficient String constructor. Since Java 9 Strings are backed by bytes instead of chars when possible, this isn't that bad.- Parameters:
characters
- the characters to create the String from.- Returns:
- the newly created string
- See Also:
createString(int, int, char[])
-
formatPercentage
public static java.lang.String formatPercentage(double percentage, int digitsAfterDecimalPoint)
Format a percentage to the number of decimal places specified. But if this would round it to 100% or 0%, then it is rounded to enough decimal places such that it does not display 100% or 0% unless it actually is 100% or 0%- Parameters:
percentage
- the percentage to display between 0.0 and 100.0digitsAfterDecimalPoint
- the number of decimal places to display, this might be more if we need to avoid rounding to 0 or 100 percent.- Returns:
- the percentage as a string with a % sign appended.
- Since:
- API 4.202302 (Geneious 2023.0.2)
-
createString
public static java.lang.String createString(int offset, int length, char[] characters)
Creates a new String from a character array by calling the String package private constructor:String#String(int,int,char[])
which shares the char[] value array for speed and lowers memory usage since we don't need to have 2 copies of the char[] in memory at once. WARNING: take extreme care when using this method, anything that uses this should not modifycharacters
afterwards and should probably immediately discard any reference to it. The package private String constructor was removed in Java 9, so this method just uses the inefficient String constructor. Since Java 9 Strings are backed by bytes instead of chars when possible, this isn't that bad.- Parameters:
characters
- the characters to create the String from.offset
- an offset into the character array to being the String fromlength
- the length of the String to create.- Returns:
- the newly created string
- See Also:
createString(char[])
-
join
public static java.lang.String join(java.lang.String separator, java.lang.Iterable values)
Concatenates values (calling toString() on each of them), interleaved with the separator string. So the separator string gets put before and after each value, but not before the first nor after the last value. For example, if l is a list holding the strings "foo", "bar" and "baz", then join(", ", l) will be "foo, bar, baz". Results longer thanInteger.MAX_VALUE
- 2 will be truncated- Parameters:
separator
- String to put between the valuesvalues
- Values to concatenate, interleaved with the separator- Returns:
- Concatenated values separated by separator string.
-
trimToLength
public static java.lang.String trimToLength(java.lang.String string, int maximumLength, boolean appendDotsIfTruncated)
Trims this string so that it is at most maximumLength characters long.If it exceeds this length and appendDotsIfTruncated==false then the string returned is just truncated to maximumLength.
If it exceeds this length and appendDotsIfTruncated==true then the string returned is just truncated to maximumLength-3 and "..." is appended.- Parameters:
string
- the string to possible trimmaximumLength
- the maximum length of the returned string.appendDotsIfTruncated
- true to append "..." to the string if it is truncated.- Returns:
- a string which is as most maximumLength characters long
- Throws:
java.lang.IllegalArgumentException
- if maximumLength<3 and appendDotsIfTruncated==true- Since:
- API 4.50 (Geneious 5.5.0)
-
humanJoin
public static java.lang.String humanJoin(java.lang.Iterable values)
Like join(", ", values), except that the last value is separated with " and " instead of ", ".- Parameters:
values
- Values with a meaningful toString() method, to list in a human readable format.- Returns:
- A String containing the String values of all values in a human readable format
-
splitIntoLines
public static java.util.List<java.lang.String> splitIntoLines(java.lang.String s)
Splits a String into the lines it consists of, with any of the standard newlines (\r, \n or \r\n) being accepted (as by a BufferedReader). A line is defined as a maximal (can't be extended to either side) subsequence of s that ends immediately before either the end of s or a newline. This means that if s starts in a newline, the returned list will start with an empty String, if s ends in a newline, the returned list will be the same as if that newline wasn't there, i.e. the returned list will only end in an empty String if s ends in two or more newlines (note that the sequence \r\n is only a single newline). Also, this implies that elements of the returned lists will never themselves end in a newline. Note: This method was only introduced in Geneious 3.8, i.e. a plugin must not use it if it wants to depend only on Geneious API version 4 (used in Geneious 3.7) or earlier.- Parameters:
s
- A string- Returns:
- A list of Strings, each corresponding to one line in s in order, as returned by a new BufferedReader(new StringReader(s)).
- Since:
- Geneious 3.8
-
formatStackTrace
public static java.lang.String formatStackTrace(java.lang.Throwable throwable)
Prints the stacktrace associated with a Throwable to a String and returns the String. The exception class and exception message make up the first line of the stack trace. The returned String is of the form:java.io.IOException: exception reason at com.biomatters.geneious.publicapi.utilities.GeneralUtilitiesTest.testStackTrace(GeneralUtilitiesTest.java:112) at ...
- Parameters:
throwable
- the throwable to get a stracktrace for.- Returns:
- The stacktrace for the throwable as a String
-
formatDateNicely
public static java.lang.String formatDateNicely(java.util.Date date, boolean displayRelativeTimes)
Nicely formats a Date in the Geneious style.- Parameters:
date
- the Date to formatdisplayRelativeTimes
- if true, will display a time as relative to today when appropriate. For example "Yesterday at 13:21:02" or "Thursday at 10:00:00". Otherwise, will always display the date in the standard geneious format- Returns:
- the formatted String.
- Since:
- API 4.60 (Geneious 5.6.0)
-
formatElement
public static java.lang.String formatElement(org.jdom.Element element)
Prints an Element in pretty format (Format.getPrettyFormat()
) to a String and returns that String.- Parameters:
element
- the element to print to a String. May be null, in which case "(null)" is returned.- Returns:
- a String containing the given Element printed in pretty format.
- See Also:
formatElementPreserveText(org.jdom.Element)
,formatElementRaw(org.jdom.Element)
-
formatElementRaw
public static java.lang.String formatElementRaw(org.jdom.Element element)
Prints an Element in raw format (Format.getRawFormat()
) to a String and returns that String.- Parameters:
element
- the element to print to a String. May be null, in which case "(null)" is returned.- Returns:
- a String containing the given Element printed in raw format.
- Since:
- API 4.700 (Geneious 7.0.0)
- See Also:
formatElement(org.jdom.Element)
,formatElementPreserveText(org.jdom.Element)
-
formatElementPreserveText
public static java.lang.String formatElementPreserveText(org.jdom.Element element)
Prints an Element in pretty format similar to (Format.getPrettyFormat()
) and returns that String. UnlikeformatElement(org.jdom.Element)
this method does not trim whitespace from the start and end of text elements.When parsing text generated by this method,
parseElementPreserveText(String)
should be used so that whitespace produced for pretty formatting does not appear during parsing.- Parameters:
element
- the element to print to a String. May be null, in which case "(null)" is returned.- Returns:
- a String containing the given Element printed in pretty format.
- Since:
- API 4.700 (Geneious 7.0.0)
- See Also:
formatElementPreserveText(org.jdom.Element)
,formatElementRaw(org.jdom.Element)
,parseElementPreserveText(String)
-
parseElement
public static org.jdom.Element parseElement(java.lang.String elementText) throws org.jdom.JDOMException
Parses some XML.- Parameters:
elementText
- a String representation of the XML (for example returned fromformatElement(org.jdom.Element)
).- Returns:
- the XML
- Throws:
org.jdom.JDOMException
- if it cannot be parsed.
-
parseElementPreserveText
public static org.jdom.Element parseElementPreserveText(java.lang.String elementText) throws org.jdom.JDOMException
Parses some XML text which was generated usingformatElementPreserveText(org.jdom.Element)
. Text elements with siblings have their whitespace trimmed.- Parameters:
elementText
- a String representation of the XML returned fromformatElementPreserveText(org.jdom.Element)
).- Returns:
- the XML
- Throws:
org.jdom.JDOMException
- if it cannot be parsed.- Since:
- API 4.700 (Geneious 7.0.0)
- See Also:
formatElementPreserveText(org.jdom.Element)
,parseElement(String)
-
getTextFromInputStream
public static java.lang.String getTextFromInputStream(java.io.InputStream stream, boolean closeInputStream) throws java.io.IOException
Reads an InputStream into a string until the end of the stream is reached. This method will block if necessary. Line endings will be imported as they are provided by the stream (platform dependent) so you may get\r\n
which can cause problems.- Parameters:
stream
- the stream to read from.closeInputStream
- true to close the stream when complete or when an exception occurs, false to leave it open- Returns:
- the text read from the InputStream.
- Throws:
java.io.IOException
- if any method calls to the InputStream throw an IOException- See Also:
FileUtilities.getTextFromFile(java.io.File)
,getTextFromReader(java.io.Reader, boolean)
-
getTextFromReader
public static java.lang.String getTextFromReader(java.io.Reader reader, boolean closeReader) throws java.io.IOException
Reads a reader into a string until the end of the stream is reached. This method will block if necessary. Line endings will be imported as they are provided by the reader (platform dependent) so you may get\r\n
which can cause problems.- Parameters:
reader
- the reader to read fromcloseReader
- true to close the reader when complete or when an exception occurs, false to leave it open- Returns:
- a string containing all data read from the reader.
- Throws:
java.io.IOException
- if any method calls to the Reader throw an IOException, or the file has length greater than Integer.MAX_VALUE- See Also:
FileUtilities.getTextFromFile(java.io.File)
,getTextFromInputStream(java.io.InputStream,boolean)
-
commaFormat
public static java.lang.String commaFormat(long value)
Formats the given number with commas every 3rd digit. This is equivalent toString.format("%,d",value)
but this method is about 25 times faster.- Parameters:
value
- the value to format- Returns:
- the given number with commas every 3rd digit
-
commaFormat
public static java.lang.String commaFormat(double value, int decimalPlaces)
Formats the given number with commas every 3rd digit and the specified number of decimal places of accuracy. Equivalent toString.format("%,0.2f", value)
(when decimalPlaces==2), but this method is around 10 times faster- Parameters:
value
- the value to formatdecimalPlaces
- the number of decimal places to display- Returns:
- the given number with commas every 3rd digit
- Since:
- API 4.202210 (Geneious 2022.1.0)
-
formatDouble
public static java.lang.String formatDouble(double value, int decimalPlaces, boolean commasEveryThirdDigit)
Formats the given number with optional commas every 3rd digit and the specified number of decimal places of accuracy. Equivalent toString.format("%,0.2f", value)
orString.format("%0.2f", value)
(when decimalPlaces==2), but this method is around 10 times faster- Parameters:
value
- the value to formatdecimalPlaces
- the number of decimal places to displaycommasEveryThirdDigit
- whether to insert commas every 3rd digit (only before the decimal place)- Returns:
- the given number with optional commas every 3rd digit
- Since:
- API 4.202510 (Geneious 2025.1.0)
-
bytesToString
public static java.lang.String bytesToString(long bytes)
Format a byte count to be human friendly. eg. 1.5 MB or 10 KB.- Parameters:
bytes
- byte count to format- Returns:
- formatted string representing the byte count
-
delete
public static java.lang.String delete(java.lang.String stringToDeleteCharacterFrom, char charToDelete)
Creates a new string identical to stringToDeleteCharacterFrom except with all instances of the given character removed. This is much faster than usingString.relace
- Parameters:
stringToDeleteCharacterFrom
- the string to remove occurances fromcharToDelete
- the character to remove all occurances of- Returns:
- new string identical to stringToDeleteCharacterFrom except with all instances of the given character removed. If stringToDeleteCharacterFrom does not contain charToDelete, then stringToDeleteCharacterFrom is returned.
-
listToString
public static java.lang.String listToString(java.util.List<java.lang.String> list)
Converts a list of Strings into a single String which can be converted back to a list viastringToList(String)
- Parameters:
list
- the list to convert to a String- Returns:
- the list encoded as a single String which can be converted back to a list via
stringToList(String)
- Since:
- API 4.700 (Geneious 7.0.0)
-
listToString
public static java.lang.String listToString(java.util.List<java.lang.String> list, int maxLength)
Converts a list of Strings into a single String which can be converted back to a list viastringToList(String)
- Parameters:
list
- the list to convert to a StringmaxLength
- the maximum length for the returned String. Only the first values from list are used to ensure the returned String is not longer than this.- Returns:
- the list encoded as a single String which can be converted back to a list via
stringToList(String)
- Since:
- API 4.202020 (Geneious 2020.2.0)
-
stringToList
public static java.util.List<java.lang.String> stringToList(java.lang.String string)
Converts a String created usinglistToString(java.util.List)
back into a list of Strings.- Parameters:
string
- a string returned fromlistToString(java.util.List)
- Returns:
- the list originally passed to
listToString(java.util.List)
- Since:
- API 4.700 (Geneious 7.0.0)
-
stripHtmlTags
public static java.lang.String stripHtmlTags(java.lang.String string, boolean onlyIfStartsWithHtmlTag)
Strips all html tags and their contents from the provided String- Parameters:
string
- the string to strip html tags fromonlyIfStartsWithHtmlTag
- if this is true, then only if the string starts with an html tag (<html;>) will any tags be stripped- Returns:
- the string without any html tags
- Since:
- API 4.800 (Geneious 8.0.0)
-
escapeHtmlCharacters
public static java.lang.String escapeHtmlCharacters(java.lang.String text)
Escapes all of the HTML reserved characters in the given string, replacing them with equivalent HTML entities.- Parameters:
text
- The string to escape the characters in- Returns:
- a new string with reserved characters replaces by HTML safe entities
- Since:
- API 4.910 (Geneious 9.1.0)
-
createHyperlink
public static java.lang.String createHyperlink(java.lang.String linkText, java.lang.String url)
Returns a hyperlink from the given text to the url for use in html, by surrounding the linkText with an href tag.- Parameters:
linkText
- the text to display to the userurl
- the url to go to when the link is clicked- Returns:
- a hyperlink from the given text to the url for use in html, by surrounding the linkText with an href tag.
- Since:
- API 4.1000 (Geneious 10.0.0)
-
capitalize
public static java.lang.String capitalize(java.lang.String text)
- Returns:
- text with its first letter capitalized (converted to uppercase)
- Since:
- API 4.1011 (Geneious 10.1.1)
-
getHexString
public static java.lang.String getHexString(byte[] bytes)
- Parameters:
bytes
- the bytes to get a hex string for- Returns:
- A hex string (0123456789ABCDEF) of the given bytes
- Since:
- API 4.202500 (Geneious 2025.0.0)
-
-