Class StringUtils


  • public class StringUtils
    extends Object
    A very heavily used class. This centralizes many idioms about strings, plus it has a lot of simplified formatting utilities.

    Created by Jeff Gaynor
    on 4/23/20 at 6:34 AM

    • Field Detail

      • blanks

        protected static String blanks
      • DEFAULT_DISPLAY_WIDTH

        protected static int DEFAULT_DISPLAY_WIDTH
      • JUSTIFY_LEFT

        public static boolean JUSTIFY_LEFT
      • JUSTIFY_RIGHT

        public static boolean JUSTIFY_RIGHT
      • ELLIPSIS

        public static String ELLIPSIS
      • STARS

        protected static String STARS
    • Constructor Detail

      • StringUtils

        public StringUtils()
    • Method Detail

      • RJustify

        public static String RJustify​(String x,
                                      int width)
        Right justify, so for the given width, the string is padded on the right. Note that if width < x.length, the string is returned unchanged.
        Parameters:
        x -
        width -
        Returns:
      • LJustify

        public static String LJustify​(String x,
                                      int width)
        Left justify, padding the string on the right. See note in RJustify(String, int)
        Parameters:
        x -
        width -
        Returns:
      • getBlanks

        public static String getBlanks​(int width)
        Get a string of blanks for the given width. If the width is non-positive, the empty string is returned.
        Parameters:
        width -
        Returns:
      • getNBSpaces

        public static String getNBSpaces​(int width)
      • justify

        public static String justify​(String x,
                                     int width,
                                     boolean rightJustify)
        Right or right justify a snippet of text to the given width, e.g. for right justify:
             x = "abc";
             width = 5;
             output then is
             "  abc"
         
        Left justify effectively pads it on the
        Parameters:
        x -
        width -
        Returns:
      • isTrivial

        public static boolean isTrivial​(String x)
        If the string is either null or empty. This is a very common idiom for testing strings but the built in String.isEmpty() of course cannot be used on a null object...
        Parameters:
        x -
        Returns:
      • main

        public static void main​(String[] args)
        Some quick tests for this class. Used for development, debugging or just run it if you are curious and look at the output.
        Parameters:
        args -
      • testWrap

        protected static void testWrap()
      • truncate

        public static String truncate​(String x,
                                      int width)
        Truncate with the default ELLIPSIS.
        Parameters:
        x -
        width -
        Returns:
      • truncate

        public static String truncate​(String x)
        Truncate with all the defaults.
        Parameters:
        x -
        Returns:
      • truncate

        public static String truncate​(String x,
                                      int width,
                                      String ellipsis)
        truncate the string x to the given width. If the string is too long, use the ellipsis, e.g.
             x = "abcdefghijklmnopqrs";
             ellipsis = "...";
             width = 10;
         
        Then this would yield
             abcdefg...
         
        If width < 0, then do not truncate.
        If ellipsis is null or empty, use the default ELLIPSIS
        Parameters:
        x -
        width -
        ellipsis -
        Returns:
      • justify

        public static String justify​(int leftMargin,
                                     String source,
                                     int rightMargin)
        Left and right margin are column numbers, so 10, string 80 means the resulting string will be padded with 10 characters on the left and 80 and the right. Each line will be justifid within the margins separately
        Parameters:
        leftMargin -
        source -
        rightMargin -
        Returns:
      • justify

        public static List<String> justify​(int leftMargin,
                                           List<String> source,
                                           int rightMargin)
      • wrap

        public static List<String> wrap​(int offset,
                                        List<String> source,
                                        int rightMargin)
        For output like
             abc : foo
          swwe e : bar fgd
                   ddd ryf
         
        This outdents the first line and indents to rest for the wrap.
        Parameters:
        offset - length of whole left block
        source -
        rightMargin -
        Returns:
      • wrap

        public static String wrap​(String source,
                                  int width)
        Convience to wrap a single string.
        Parameters:
        source -
        width -
        Returns:
      • toList

        public static List<String> toList​(String x)
        Convert a string with embedded line feeds to a list os strings. Inverse of fromList(List)
        Parameters:
        x -
        Returns:
      • fromList

        public static String fromList​(List<String> listOfStrings)
        Convert a list of strings into a single string with linefeeds. Inverse of toList(String).
        Parameters:
        listOfStrings -
        Returns:
      • equals

        public static boolean equals​(String x,
                                     String y,
                                     boolean ignoreCase,
                                     boolean trimEnds)
        Checks if towo strings have equal content.
        Parameters:
        x -
        y -
        ignoreCase - ignore case. Everything is converted to lower case before checking
        trimEnds - remove any lead or trailing whitespace before checking
        Returns:
      • equals

        public static boolean equals​(String x,
                                     String y)
      • pad

        public static String pad​(String s,
                                 int commandBufferMaxWidth)
        Pad a string with blanks as needed. This does not truncate if the string is too long. If you want truncation, use pad2(String, int).
        Parameters:
        s -
        commandBufferMaxWidth -
        Returns:
      • pad2

        public static String pad2​(int value,
                                  int commandBufferMaxWidth)
      • pad2

        public static String pad2​(Date value,
                                  boolean isISO,
                                  int commandBufferMaxWidth)
      • pad2

        public static String pad2​(Date value,
                                  int commandBufferMaxWidth)
        Default is ISO 8601 dates
        Parameters:
        value -
        commandBufferMaxWidth -
        Returns:
      • pad2

        public static String pad2​(String s,
                                  int commandBufferMaxWidth)
        Pad the string to the given length with blanks. This makes sure every line is the same length. If the line is too long, it is truncated
        Parameters:
        s -
        commandBufferMaxWidth -
        Returns:
      • pad2

        public static String pad2​(String s,
                                  boolean isTruncate,
                                  int commandBufferMaxWidth)
      • formatMap

        public static List<String> formatMap​(Map map,
                                             List<String> keySubset,
                                             boolean sortKeys,
                                             boolean multiLine,
                                             int indent,
                                             int displayWidth)
        Format a map of objects as easily readable key value pairs.
        Parameters:
        map - The map to be displayed
        keySubset - An optional (may be null or empty) subset of keys. Only these will be used id present
        sortKeys - if true, the keys in the map will be sorted.
        multiLine - Split the formatting of the values in the map over several lines (true) or truncate with ellipses (false)
        indent - The amount for the whole thing to be indented from the left
        displayWidth - The total width that this must fit in.
        Returns:
      • formatMap

        public static List<String> formatMap​(Map map,
                                             List<String> keySubset,
                                             boolean sortKeys,
                                             boolean multiLine,
                                             int indent,
                                             int displayWidth,
                                             boolean tryJSON)
        The tryJSON flag means that if an entry might be JSON, try to interpret it and use JSON formatting guidelines. This should be set false in cases where you know that is not the case, e.g., in calls from QDL.
        Parameters:
        map -
        keySubset -
        sortKeys -
        multiLine -
        indent -
        displayWidth -
        tryJSON -
        Returns:
      • formatMapEntry

        public static String formatMapEntry​(String key,
                                            String value,
                                            int indentWidth,
                                            int displayWidth,
                                            int leftColumWidth,
                                            boolean multiLine)
        Format an entry from a map. This will take a (key, value) pair within margins so that colons align and format it as a line of the form (multiLine false):
             key : value...
         
        This truncates the value to fit on a single line and within the displayWidth. If multiLine is true it will be of the form:
             key : value split
                   over several lines as
                   needed.
         
        Note that the leftColumWidth is the length of the longest key in the map, usually. The key will be right justified within this field and hence all the colons will end up in the same place, making the output extremely readable.
        Parameters:
        key - The key from the entry
        value - The value of the entry
        indentWidth - The indent on the left of the whole entry
        displayWidth - The actual width that this is to fit in
        leftColumWidth - The total width of the key field.
        multiLine - Split the value over several lines if too long, otherwise truncate with ellipsis.
        Returns:
      • listToString

        public static String listToString​(List<String> list)
        Converts a list of strings to a single string with embedded linefeeds.
        Parameters:
        list -
        Returns:
      • stringToList

        public static List<String> stringToList​(String s)
        Converts a string with embedded linefeeds into a list of strings, one per line. The line editor needs this.
        Parameters:
        s -
        Returns:
      • formatTable

        public static List<String> formatTable​(List<String> headers,
                                               List<List<String>> table,
                                               int maxFieldWidth,
                                               boolean showDelimiter)
        Takes a table -- defined as a list of rows, each row is a separate column amd returns a list of formatted rows that can just be printed (piped through a stream or whatever) It is assumed there are no missing columns, though null columns are fine and are rendered as blank.
        Parameters:
        table -
        maxFieldWidth - maximum width of a column. Output is truncated if positive.
        showDelimiter -
      • toUnicode

        public static String toUnicode​(char ch)
        Returns the unicode for a single character
        Parameters:
        ch -
        Returns:
      • formatByteCount

        public static String formatByteCount​(long count)
        Make E.g. byte counts from files human readable.
        Parameters:
        count -
        Returns:
      • formatCount

        public static String formatCount​(long count,
                                         String unit)
        Formats the count and units with the correct unit prefix, formatting the count. So if formatCount(54321, "b") --> 54.321 Kb, here "b" is the unit
        Parameters:
        count -
        unit -
        Returns:
      • formatElapsedTime

        public static String formatElapsedTime​(long elapsedTime)
        Makes elapsed times in milliseconds human readable.
        Parameters:
        elapsedTime - The actual elapsed time in ms. E.g. 1000 is 1 sec.
        Returns:
      • formatHerz

        public static String formatHerz​(long cycles,
                                        long startTime)
        Formats the number of cycles from the starting time. This will return properly formatted results to 4 places with units e.g. 12345 Hz is returned as 12.345 KHz
        Parameters:
        cycles -
        startTime -
        Returns:
      • center

        public static String center​(String text,
                                    int width)
        Centers the string within the width. If the string is longer than the width, nothing is done and no truncation results. The result is a string of length equal to width, with the text in centered.
        Parameters:
        text -
        width -
        Returns: