Package Torello.Java

Class SED


  • public class SED
    extends java.lang.Object
    Based on the UNIX 'SED' Command, this class updates files based on either String-Literal matches & replacements, or or Regular-Expression matches.

    The original UNIX 'SED' command was usually used as a Programming Tool for making updates to Source-Code Files, or other types of coding related Text-Files.

    This class provides the ability to update files based on either String-Literal matches, or via matches made using a Regular-Expression Matcher object. This class provides a Text-Based interactive UI when processing these files, and for this reason, the methods are further divided into two categories. The first category of methods process Single-Line String-Literal or Regular-Expression matches, and the second category of methods process Multi-Line Matches. Again, the impetus for this design decision is essentially for the output printing to System.out that occurs.



    Note that all methods in this class accept several identical Configuration-Parameters. Parameters that are identical to all primary methods in this class are listed in the table below.

    Method Parameters

    Parameter Explanation
    Iterable<FileNode> files Accepts any Java Iterable containing files for 'SED' Processing. These files are intended to be Text-Files, and the updating that occurs will be based on String-Matches.

    Non-deterministic results will occur if a file is processed that cannot properly be loaded into a java.lang.String
    boolean askFirst Provides the user the option of skipping the System.out interactive process, and performing any / all updates without asking the user anything.

    When TRUE is passed to this parameter, the programmer will be queried before each File-System update. When passed FALSE, this parameter asks that all Update-Processing be done automatically, without any pauses to ask for permission.
    IOExceptionHandler ioeh Each file listed in Iterable Parameter 'files' will be loaded from the File-System, which is an operation that potentially throws Java's IOException. This handler is provided to allow a user to decide what to do if this exception is thrown during a File-System read or write.
    Appendable outputSaver In order to save a record / log of the output Terminal-Output sent by SED, pass any Appendable instance to this parameter. Text will be transmitted to this Appendable instance, in addition to being written to Standard-Output (System.out).

    This parameter may be passed null, and if it is, it will be silently ignored. Text output will continue to be sent to System.out (Standard-Output).

    Java's Appendable interface's append(...) methods allow for an IOException throw. If 'outputSaver' throws any IOException's, they will be wrapped in an AppendableError as the Cause-Throwable, and then re-thrown.
    boolean useUNIXColors When this parameter is passed TRUE, UNIX-Terminal Color Codes will be included in the User-Output. These color codes may be viewed in class C. When FALSE is passed, the Color-Code Terminal Escape-Sequences will be left out.
    Verbosity verbosity Sets the Verbosity Level. This parameter may be null, and if it is the level will default to Verbosity.Normal.

    NOTE: If Verbosity.Silent is chosen, parameter 'askFirst' must be passed FALSE, or an IllegalArgumentException will throw. This is because the option to query a user cannot function without Output Text.



    Stateless Class:
    This class neither contains any program-state, nor can it be instantiated. The @StaticFunctional Annotation may also be called 'The Spaghetti Report'. Static-Functional classes are, essentially, C-Styled Files, without any constructors or non-static member fields. It is a concept very similar to the Java-Bean's @Stateless Annotation.

    • 1 Constructor(s), 1 declared private, zero-argument constructor
    • 10 Method(s), 10 declared static
    • 2 Field(s), 2 declared static, 2 declared final


    • Field Summary

       
      FilenameFilter's for class FileNode's loadTree Methods
      Modifier and Type Field
      static FilenameFilter filterFilesHTML
      static FilenameFilter filterFilesJava
    • Method Summary

       
      Replace all instances of a Single-Line String in a list of Files
      Modifier and Type Method
      static List<FileNode> singleLine​(
         Iterable<FileNode> files,
         String matchStr,
         String replaceStr
      )
      static List<FileNode> singleLine​(
         Iterable<FileNode> files,
         String matchStr,
         String replaceStr,
         boolean askFirst,
         IOExceptionHandler ioeh,
         boolean useUNIXColors,
         Verbosity verbosity,
         Appendable outputSaver
      )
       
      Replace all instances of a Single-Line Regular-Expression in a list of Files
      Modifier and Type Method
      static List<FileNode> singleLine​(
         Iterable<FileNode> files,
         Pattern regEx,
         Function<MatchResult,​String> replaceFunction
      )
      static List<FileNode> singleLine​(
         Iterable<FileNode> files,
         Pattern regEx,
         Function<MatchResult,​String> replaceFunction,
         boolean askFirst,
         IOExceptionHandler ioeh,
         boolean useUNIXColors,
         Verbosity verbosity,
         Appendable outputSaver
      )
       
      Replace all instances of a Multi-Line String in a list of Files
      Modifier and Type Method
      static List<FileNode> multiLine​(
         Iterable<FileNode> files,
         String matchStr,
         String replaceStr
      )
      static List<FileNode> multiLine​(
         Iterable<FileNode> files,
         String matchStr,
         String replaceStr,
         boolean askFirst,
         IOExceptionHandler ioeh,
         boolean useUNIXColors,
         Verbosity verbosity,
         Appendable outputSaver
      )
       
      Replace all instances of a Multi-Line Regular-Expression in a list of Files
      Modifier and Type Method
      static List<FileNode> multiLine​(
         Iterable<FileNode> files,
         Pattern regEx,
         Function<MatchResult,​String> replaceFunction
      )
      static List<FileNode> multiLine​(
         Iterable<FileNode> files,
         Pattern regEx,
         Function<MatchResult,​String> replaceFunction,
         boolean askFirst,
         IOExceptionHandler ioeh,
         boolean useUNIXColors,
         Verbosity verbosity,
         Appendable outputSaver
      )
      • Methods inherited from class java.lang.Object

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

      • filterFilesHTML

        🡇     🗕  🗗  🗖
        public static final java.io.FilenameFilter filterFilesHTML
        A java.io.FilenameFilter that looks for JavaDoc Upgrader HTML-Files.
        Code:
        Exact Field Declaration Expression:
         public static final FilenameFilter filterFilesHTML = (File dir, String fileName) ->
             {
                 if (! fileName.endsWith(".html")) return false;
        
                 if (! StrCmpr.containsAND(dir.getPath(), "upgrade-files", "external-html")) return false;
        
                 return true;
             };
        
      • filterFilesJava

        🡅  🡇     🗕  🗗  🗖
        public static final java.io.FilenameFilter filterFilesJava
        A java.io.FilenameFilter that looks for '.java' Files.
        Code:
        Exact Field Declaration Expression:
         public static final FilenameFilter filterFilesJava = (File dir, String fileName) ->
             {
                 if (! fileName.endsWith(".java")) return false;
        
                 return true;
             };
        
    • Method Detail

      • singleLine

        🡅  🡇         External-Java:      🗕  🗗  🗖
        public static java.util.List<FileNodesingleLine​
                    (java.lang.Iterable<FileNode> files,
                     java.lang.String matchStr,
                     java.lang.String replaceStr)
                throws java.io.IOException
        
        Find Single-Line String-Matches, and Substitue each match with a Replacement-String
        Passed Values to Configuration-Record:  
           
        askFirst: TRUE
        ioeh: null
        useUNIXColors: TRUE
        verbosity: Verbosity.Normal
        outputSaver: null
        Throws:
        java.io.IOException
        Code:
        Exact Method Body:
         CHECK_NULL(files, matchStr, replaceStr);
         SingleLineStrMatch.CHECK_STRS(matchStr, replaceStr);
        
         final CONFIG_RECORD userConfig = new CONFIG_RECORD(
             matchStr,
             replaceStr,
             true,               // askFirst
             null,               // ioeh
             true,               // useUNIXColors
             Verbosity.Normal,   // verbosity
             null                // outputSaver
         );
        
         return InternalSED.run(files, userConfig, SingleLineStrMatch::handleOneFile);
        
      • singleLine

        🡅  🡇         External-Java:      🗕  🗗  🗖
        public static java.util.List<FileNodesingleLine​
                    (java.lang.Iterable<FileNode> files,
                     java.lang.String matchStr,
                     java.lang.String replaceStr,
                     boolean askFirst,
                     IOExceptionHandler ioeh,
                     boolean useUNIXColors,
                     Verbosity verbosity,
                     java.lang.Appendable outputSaver)
                throws java.io.IOException
        
        Makes updates to Text-Files listed in parameter 'files'.

        In the example below, all '.java' Source-Code Files in the Java-HTML Library are loaded into a Vector<FileNode>. Using this particular 'SED' method, each substring that looks like <B>TRUE</B> (in all '.java' Source-Files) is converted to look like {@code TRUE}

        Example:
         StringBuilder log = new StringBuilder();
         
         // Load all Java-HTML Source-Files (in all packages) into a FileNode-Vector
         Vector<FileNode> files = FileNode
              .createRoot("Torello/")
              .loadTree(-1, SED.filterFilesJava, null)
              .flattenJustFiles(RTC.VECTOR());
         
         // Invoke this method
         singleLine(files, "<B>TRUE</B>", "{@code TRUE}", true, null, true, Verbosity.Normal, log);
         
         // Save the Changes that were made to a log
         FileRW.writeFile(log, "ChangesMade.log.txt");
        
        Parameters:
        matchStr - Any Java String-Literal. It is required that this String not contain any new-line ('\n') characters, or an IllegalArgumentException will throw.
        replaceStr - For all 'files', each instance of the String-Literal parameter 'matchStr' found in any file will be replaced by 'replaceStr'.

        As with parameter 'matchStr', if this String contains any new-line ('\n') characters, an IllegalArgumentException will throw.
        Returns:
        A list of FileNode instances whose File-Contents were modified / updated by this method.
        Throws:
        java.lang.IllegalArgumentException - If either of the String parameters 'matchStr' or 'replaceStr' contain any newline ('\n') characters.

        If a 'SED' replacement needs to be done using a String-Match that spans more than one line, use the Multi-Line method provided in this class.
        AppendableError - If the Appendable parameter 'outputSaver' throws an IOException, then that exception is wrapped in an AppendableError (it is set as the Cause-Throwable) and re-thrown.
        java.io.IOException - On File-System read / write error.
        Code:
        Exact Method Body:
         CHECK_NULL(files, matchStr, replaceStr);
         SingleLineStrMatch.CHECK_STRS(matchStr, replaceStr);
        
         final CONFIG_RECORD userConfig = new CONFIG_RECORD
             (matchStr, replaceStr, askFirst, ioeh, useUNIXColors, verbosity, outputSaver);
        
         return InternalSED.run(files, userConfig, SingleLineStrMatch::handleOneFile);
        
      • singleLine

        🡅  🡇         External-Java:        🗕  🗗  🗖
        public static java.util.List<FileNodesingleLine​
                    (java.lang.Iterable<FileNode> files,
                     java.util.regex.Pattern regEx,
                     java.util.function.Function<java.util.regex.MatchResult,​java.lang.String> replaceFunction)
                throws java.io.IOException
        
        Find Reg-Ex Matches on a Line-By-Line Basis, and Apply a Replacement-Function
        Passed Values to Configuration-Record:  
           
        askFirst: TRUE
        ioeh: null
        useUNIXColors: TRUE
        verbosity: Verbosity.Normal
        outputSaver: null
        Throws:
        java.io.IOException
        Code:
        Exact Method Body:
         CHECK_NULL(files, regEx, replaceFunction);
        
         final CONFIG_RECORD userConfig = new CONFIG_RECORD(
             regEx,
             replaceFunction,
             true,               // askFirst
             null,               // ioeh
             true,               // useUNIXColors
             Verbosity.Normal,   // verbosity
             null                // outputSaver
         );
        
         return InternalSED.run(files, userConfig, SingleLineRegExMatch_ONE_FILE::handleOneFile);
        
      • singleLine

        🡅  🡇         External-Java:        🗕  🗗  🗖
        public static java.util.List<FileNodesingleLine​
                    (java.lang.Iterable<FileNode> files,
                     java.util.regex.Pattern regEx,
                     java.util.function.Function<java.util.regex.MatchResult,​java.lang.String> replaceFunction,
                     boolean askFirst,
                     IOExceptionHandler ioeh,
                     boolean useUNIXColors,
                     Verbosity verbosity,
                     java.lang.Appendable outputSaver)
                throws java.io.IOException
        
        Makes updates to Text-Files listed in parameter 'files'. Matches that are eligible for replacement are identified using the Regular-Expression parameter 'regEx'.

        Replacement-String's are obtained by invoking the 'replaceFunction' parameter.

        This method will, first, break up the input text into separate lines of textual data, demarcated by the '\n' new-line character, and then apply the provided 'regEx' parameter to each of these lines of text. In essence, the standard Java 'String.split("\n")' is first invoked, and aftewards a loop iterates each line of text against the supplied Regular-Expression.

        Note: The caret (`^`) and dollar-sign (`$`) characters - also known as line anchors - do not require the use of the Pattern.MULTILINE flag because, as was just mentioned, each line of text is split, manually (with String.split("\n")), before matching begins.

        When applied to individual lines of String-data, '^' matches the start of the line, and '$' matches just before the newline, even without the MULTILINE flag.


        In the example below, all Java HTML Library Source-Files are loaded into a Vector<FileNode>, and then iterated by this method. In each file, any instances of an EMBED-Tag that contains a FILE-ID Data-Attribute whose value is wrapped in Double Quotation-Marks has that value extracted and re-inserted without any Quotation-Marks.

        Example:
         StringBuilder log = new StringBuilder();
         
         // Load all Java-HTML Source-Files (in all packages) into a FileNode-Vector
         Vector<FileNode> files = FileNode
              .createRoot("Torello/")
              .loadTree(-1, filterFilesJava, null)
              .flattenJustFiles(RTC.VECTOR());
         
         // Matches an <EMBED> Tag's FILE-ID Data-Attribute.  There are parenthesis placed around the
         // actual ID-Name.  The contents of the parenthesis are "Reg-Ex Match-Group #1"
         
         Pattern regEx = Pattern.compile("DATA-FILE-ID=\"(\\w+)\"");
         
         // This Function extracts Reg-Ex Group-1, and re-inserts it **WITHOUT** the Double
         // Quotation-Marks that were placed around it.  Look Closely at Previous Line of Code, the
         // 'replacer' function does not include the Double-Quotes.
         
         Function<MatchResult, String> replacer = (MatchResult mr) -> "DATA-FILE-ID=" + mr.group(1);
        
         // Invoke this method
         singleLine(files, regEx, replacer, true, null, true, Verbosity.Normal, log);
         
         // Write the changes that have been made to a log-file
         FileRW.writeFile(log, "ChangesMade.log.txt");
        
        Parameters:
        regEx - Any Java Regular-Expression. This will be used to match against the text inside each file returned by the Iterable parameter 'files'.
        replaceFunction - Any Lambda-Expression or Function-Pointer that accepts a java.util.regex.MatchResult, and returns a Replacement-String.

        This function may return 'null' - and if or when it does, whatever pending Match-Text is being processed shall be ignored, and left unchanged. The original Match-Text shall remain in the output file for any match in which 'replaceFunction' returns null.

        If this Replace-Function returns a match that contains any newline '\n' characters, this method will throw a RegExException.
        Returns:
        A list of FileNode instances whose File-Contents were modified / updated by this method.
        Throws:
        RegExExpression - Throws if the Lambda-Target / Function-Pointer parameter 'replaceFunction' ever returns a String that spans multiple lines.

        The logic simply checks for the presence of a newline '\n' character.
        AppendableError - If the Appendable parameter 'outputSaver' throws an IOException, then that exception is wrapped in an AppendableError (it is set as the Cause-Throwable) and re-thrown.
        java.io.IOException - On File-System read / write error.
        Code:
        Exact Method Body:
         CHECK_NULL(files, regEx, replaceFunction);
        
         final CONFIG_RECORD userConfig = new CONFIG_RECORD
             (regEx, replaceFunction, askFirst, ioeh, useUNIXColors, verbosity, outputSaver);
        
         return InternalSED.run(files, userConfig, SingleLineRegExMatch_ONE_FILE::handleOneFile);
        
      • multiLine

        🡅  🡇         External-Java:      🗕  🗗  🗖
        public static java.util.List<FileNodemultiLine​
                    (java.lang.Iterable<FileNode> files,
                     java.lang.String matchStr,
                     java.lang.String replaceStr)
                throws java.io.IOException
        
        Find Multi-Line String-Matches, and Substitue each match with a Replacement-String
        Passed Values to Configuration-Record:  
           
        askFirst: TRUE
        ioeh: null
        useUNIXColors: TRUE
        verbosity: Verbosity.Normal
        outputSaver: null
        Throws:
        java.io.IOException
        Code:
        Exact Method Body:
         CHECK_NULL(files, matchStr, replaceStr);
         MultiLineStrMatch.CHECK_STRS(matchStr, replaceStr);
        
         final CONFIG_RECORD userConfig = new CONFIG_RECORD(
             matchStr,
             replaceStr,
             true,               // askFirst
             null,               // ioeh
             true,               // useUNIXColors
             Verbosity.Normal,   // verbosity
             null                // outputSaver
         );
        
         return InternalSED.run(files, userConfig, MultiLineStrMatch::handleOneFile);
        
      • multiLine

        🡅  🡇         External-Java:      🗕  🗗  🗖
        public static java.util.List<FileNodemultiLine​
                    (java.lang.Iterable<FileNode> files,
                     java.lang.String matchStr,
                     java.lang.String replaceStr,
                     boolean askFirst,
                     IOExceptionHandler ioeh,
                     boolean useUNIXColors,
                     Verbosity verbosity,
                     java.lang.Appendable outputSaver)
                throws java.io.IOException
        
        Makes updates to Text-Files listed in parameter 'files'.

        Single-Line & Multi-Line:
        If either parameters 'matchStr' or 'replaceStr' receive a String that does not actually contain any new-line characters ('\n'), this method will not throw any exceptions. All User-Requested Text-Updates will be processed to completion!

        This somewhat in contrast to method 'singleLine' which will, indeed, throw an IllegalArgumentException if either 'matchStr' or 'replaceStr' contain newline characters.
        Parameters:
        matchStr - Any Java String-Literal.
        replaceStr - For all 'files', each instance of the String-Literal parameter 'matchStr' found in any file will be replaced by 'replaceStr'.
        Returns:
        A list of FileNode instances whose File-Contents were modified / updated by this method.
        Throws:
        AppendableError - If the Appendable parameter 'outputSaver' throws an IOException, then that exception is wrapped in an AppendableError (it is set as the Cause-Throwable) and re-thrown.
        java.io.IOException - On File-System read / write error.
        Code:
        Exact Method Body:
         CHECK_NULL(files, matchStr, replaceStr);
        
         final CONFIG_RECORD userConfig = new CONFIG_RECORD
             (matchStr, replaceStr, askFirst, ioeh, useUNIXColors, verbosity, outputSaver);
        
         return InternalSED.run(files, userConfig, MultiLineStrMatch::handleOneFile);
        
      • multiLine

        🡅  🡇         External-Java:      🗕  🗗  🗖
        public static java.util.List<FileNodemultiLine​
                    (java.lang.Iterable<FileNode> files,
                     java.util.regex.Pattern regEx,
                     java.util.function.Function<java.util.regex.MatchResult,​java.lang.String> replaceFunction)
                throws java.io.IOException
        
        Find Multi-Line Reg-Ex-Matches, and Apply a Replacement-Function
        Passed Values to Configuration-Record:  
           
        askFirst: TRUE
        ioeh: null
        useUNIXColors: TRUE
        verbosity: Verbosity.Normal
        outputSaver: null
        Throws:
        java.io.IOException
        Code:
        Exact Method Body:
         CHECK_NULL(files, regEx, replaceFunction);
        
         final CONFIG_RECORD userConfig = new CONFIG_RECORD(
             regEx,
             replaceFunction,
             true,               // askFirst
             null,               // ioeh
             true,               // useUNIXColors
             Verbosity.Normal,   // verbosity
             null                // outputSaver
         );
        
         return InternalSED.run(files, userConfig, MultiLineRegExMatch::handleOneFile);
        
      • multiLine

        🡅         External-Java:      🗕  🗗  🗖
        public static java.util.List<FileNodemultiLine​
                    (java.lang.Iterable<FileNode> files,
                     java.util.regex.Pattern regEx,
                     java.util.function.Function<java.util.regex.MatchResult,​java.lang.String> replaceFunction,
                     boolean askFirst,
                     IOExceptionHandler ioeh,
                     boolean useUNIXColors,
                     Verbosity verbosity,
                     java.lang.Appendable outputSaver)
                throws java.io.IOException
        
        Makes updates to Text-Files listed in parameter 'files'.

        Single-Line & Multi-Line:
        When unsure whether to use the 'singleLine' versus the 'multiLine' variants class , given a 'regEx' that might match either one or many lines of text - always use the Multi-Line Version (this method) to avoid exception throws!

        The main differences between methods 'singleLine' and 'multiLine' lays with the formatting of the User-Output Text that is printed by this method as matches are found.

        This method can easily handle falling back to printing only one line of Matching-Text. However, 'singleLine' is simply incapable of printing a Multi-Line Regular-Expression Match, and will instead throw an exception if such a match is identified.
        Parameters:
        regEx - Any Java Regular-Expression. This will be used to match against the text inside each file returned by the Iterable parameter 'files'. The Regular-Expression passed may match any number of characters or lines in the Source-File. If just one line of the original file is matched by 'regEx', this is perfectly fine and will not produce any exception throws.

        This method's User Output-Text Printing-Mechanism is written to handle 'regEx' Match-Text of any size.
        replaceFunction - Any Lambda-Expression or Function-Pointer that accepts a java.util.regex.MatchResult, and returns a Replacement-String.

        This function may return 'null' - and if or when it does, whatever pending Match-Text is being processed shall be ignored, and left unchanged. The original Match-Text shall remain in the output file for any match in which 'replaceFunction' returns null.
        Returns:
        A list of FileNode instances whose File-Contents were modified / updated by this method.
        Throws:
        AppendableError - If the Appendable parameter 'outputSaver' throws an IOException, then that exception is wrapped in an AppendableError (it is set as the Cause-Throwable) and re-thrown.
        java.io.IOException - On File-System read / write error.
        Code:
        Exact Method Body:
         CHECK_NULL(files, regEx, replaceFunction);
        
         final CONFIG_RECORD userConfig = new CONFIG_RECORD
             (regEx, replaceFunction, askFirst, ioeh, useUNIXColors, verbosity, outputSaver);
        
         return InternalSED.run(files, userConfig, MultiLineRegExMatch::handleOneFile);