Package Torello.Java

Class OSResponse


  • public class OSResponse
    extends java.lang.Object
    OS (Operating-System) Response - Documentation.

    This Object is a short data-record Object that is returned as a result from the invocation of nearly all the methods in class Shell, GSUTIL, etc.. This class contains three public, final fields that contain all available information about the results of an Operating-System invocation of the UNIX / Shell / MS-DOS Commands provided in this class.

    Whenever an Operating-System Process is invoked using Java's class java.lang.Process, the invocation of that Process will yield three data results:

    1. A response-code, which is just an integer. This is an old protocol that writers of operating-system commands used where an integer is returned to the invoking caller for every O/S call.
    2. A transcript of the text/character data that has been sent to Standard-Output. This text output is made available by this class using a public String field named 'stdOut'.
    3. A transcript of the text/character data that has been sent to Standard-Error. This text output is made available by this class using a public String field named 'stdErr'.


    NOTE: The information returned by this class may be immediately discarded, and is solely provided for convenience. If the invocation of the command (not its results) were the only reason for calling an O/S Process, simply ignoring and discarding this response Object would have no effect on the java.lang.Process routine, itself.



    • Constructor Summary

      Constructors 
      Constructor
      OSResponse​(int response, String stdOut, String stdErr)
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method
      static void PRINT_CMD​(String[] cmd, Appendable a)
      static OSResponse PRINT_CMD_RUN_CMD_PRINT_OUTPUT​(java.io.File currentWorkingDirectory, boolean mergeStdErrorAndStdOut, ProcessBuilder.Redirect outputRedirect, ProcessBuilder.Redirect inputRedirect, ProcessBuilder.Redirect errorRedirect, Consumer<Map<String,​String>> environmentVariableUpdater, String[] command, Appendable appendable)
      static OSResponse PRINT_CMD_RUN_CMD_PRINT_OUTPUT​(String[] command, Appendable appendable)
      static OSResponse RUN_CMD_PRINT_OUTPUT​(java.io.File currentWorkingDirectory, boolean mergeStdErrorAndStdOut, ProcessBuilder.Redirect outputRedirect, ProcessBuilder.Redirect inputRedirect, ProcessBuilder.Redirect errorRedirect, Consumer<Map<String,​String>> environmentVariableUpdater, String[] cmd, Appendable a)
      static OSResponse RUN_CMD_PRINT_OUTPUT​(String[] cmd, Appendable a)
      • Methods inherited from class java.lang.Object

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

      • response

        public final int response
        This public, final, int field will hold the "response code" reported by the operating-system. The response-code is a number returned by the invocation of the command to the OS. A value of -1 usually signifies that the process terminated with errors. If this field contains a value of Shell.INTERRUPTED, it will mean that the process was interrupted.
        Code:
        Exact Field Declaration Expression:
        1
        public final int response;
        
      • stdOut

        public final java.lang.String stdOut
        This public, final, String field will contain a transcript of the text-character data that the Operating-System process sent to Standard-Output.
        Code:
        Exact Field Declaration Expression:
        1
        public final String stdOut;
        
      • stdErr

        public final java.lang.String stdErr
        This public, final, String field will contain a transcript of the text-character data that the Operating-System process sent to Standard-Error.
        Code:
        Exact Field Declaration Expression:
        1
        public final String stdErr;
        
      • INTERRUPTED

        public static final int INTERRUPTED
        This integer-value is used as a response code indicating that the process that was called was interrupted, not completed. This should not be a common occurrence.
        See Also:
        Constant Field Values
        Code:
        Exact Field Declaration Expression:
        1
        public static final int INTERRUPTED = Integer.MIN_VALUE;
        
    • Constructor Detail

      • OSResponse

        public OSResponse​(int response,
                          java.lang.String stdOut,
                          java.lang.String stdErr)
        Builds an instance of this short return class
        Parameters:
        response - The integer returned by the O/S command invocation.
        stdOut - The text/character data (as a String) sent to Standard-Output.
        stdErr - The text/character data (as a String) sent to Standard-Error.
    • Method Detail

      • PRINT_CMD

        public static void PRINT_CMD​(java.lang.String[] cmd,
                                     java.lang.Appendable a)
                              throws java.io.IOException
        This merely prints the finalized UNIX/Bash/Linux command as a String to an instance of java.lang.Appendable
        Parameters:
        cmd - Is an array of String's that form the UNIX command.
        a - This is any implementation of the interface java.lang.Appendable. Text can be sent to any output, as long as it works with the interface. This parameter expects an implementation of Java's interface java.lang.Appendable which allows for a wide range of options when logging intermediate messages.
        Class or Interface InstanceUse & Purpose
        'System.out'Sends text to the standard-out terminal
        Torello.Java.StorageWriterSends text to System.out, and saves it, internally.
        FileWriter, PrintWriter, StringWriterGeneral purpose java text-output classes
        FileOutputStream, PrintStreamMore general-purpose java text-output classes

        IMPORTANT: The interface Appendable requires that the check exception IOException must be caught when using its append(CharSequence) methods.
        Throws:
        java.io.IOException - The interface Appendable requires / allows for a possible IOException, so if this exception is thrown while printing output, this method will throw it too.
        Code:
        Exact Method Body:
        1
         for (int i=0; i < cmd.length; i++) a.append(cmd[i] + " "); a.append("\n");
        
      • PRINT_CMD_RUN_CMD_PRINT_OUTPUT

        public static OSResponse PRINT_CMD_RUN_CMD_PRINT_OUTPUT​
                    (java.io.File currentWorkingDirectory,
                     boolean mergeStdErrorAndStdOut,
                     java.lang.ProcessBuilder.Redirect outputRedirect,
                     java.lang.ProcessBuilder.Redirect inputRedirect,
                     java.lang.ProcessBuilder.Redirect errorRedirect,
                     java.util.function.Consumer<java.util.Map<java.lang.String,​java.lang.String>> environmentVariableUpdater,
                     java.lang.String[] command,
                     java.lang.Appendable appendable)
                throws java.io.IOException
        
        Code:
        Exact Method Body:
        1
        2
        3
        4
        5
        6
         PRINT_CMD(command, appendable);
        
         return RUN_CMD_PRINT_OUTPUT(
             currentWorkingDirectory, mergeStdErrorAndStdOut, outputRedirect, inputRedirect,
             errorRedirect, environmentVariableUpdater, command, appendable
         );
        
      • RUN_CMD_PRINT_OUTPUT

        public static OSResponse RUN_CMD_PRINT_OUTPUT​
                    (java.io.File currentWorkingDirectory,
                     boolean mergeStdErrorAndStdOut,
                     java.lang.ProcessBuilder.Redirect outputRedirect,
                     java.lang.ProcessBuilder.Redirect inputRedirect,
                     java.lang.ProcessBuilder.Redirect errorRedirect,
                     java.util.function.Consumer<java.util.Map<java.lang.String,​java.lang.String>> environmentVariableUpdater,
                     java.lang.String[] cmd,
                     java.lang.Appendable a)
                throws java.io.IOException
        
        This will run the command named by String-Array parameter 'cmd', using the specified adjustment-parameters.
        Parameters:
        currentWorkingDirectory - This UNIX Shell command will be run with 'currentWorkingDirectory' set as the directory from whence this command is initiated. null may be passed to this parameter. If it is, it will be ignored, and the process will be run in the whatever directory the O/S has asserted is the current working directory.
        mergeStdErrorAndStdOut - If this boolean is TRUE, both Standard Output and Error Output will be merged into a single stream of text. This can be helpful since error messages are usually printed adjacent-to or immediately-after relevant text from the standard output stream.

        NOTE: The value of this boolean supersedes any redirect reference passed to parameter outputRedirect. When TRUE is passed here, the error stream will be empty, and the error redirect file or pipe will also remain empty. (And vice-versa, when FALSE, Standard Output and Error Output are printed to independent output streams, and both heed the redirect parameters).
        outputRedirect - Read the Java-Doc information for Java class java.lang.ProcessBuilder.Redirect to learn how to redirect this Process' STANDARD OUTPUT to a file on the file-system. null may be passed to this parameter. If it is, it will be ignored.
        inputRedirect - Read the Java-Doc information for Java class java.lang.ProcessBuilder.Redirect to learn how to redirect file-system files as INPUT to this Process. This parameter may receive 'null'.
        errorRedirect - Read the Java-Doc information for Java class java.lang.ProcessBuilder.Redirect to learn how to redirect this Process' ERROR OUTPUT to a file on the file-system. null may be passed to this parameter. If it is, it will be ignored.
        environmentVariableUpdater - This java.util.function.Consumer shall recieve a java.util.Map<String, String> containing all relevant environment variables, and their values. It may be modified to suit the purposes of this UNIX command. Any implementing class, or a lambda expression, is acceptable here. null may be passed to this parameter. If it is, it will be ignored - and no environment-variable modifications shall occur.
        cmd - Is an array of String's that form the UNIX command.
        a - where the text-output is sent. This parameter may be null, and if it is, text will be sent to the NOPRINT.np instance. This parameter expects an implementation of Java's interface java.lang.Appendable which allows for a wide range of options when logging intermediate messages.
        Class or Interface InstanceUse & Purpose
        'System.out'Sends text to the standard-out terminal
        Torello.Java.StorageWriterSends text to System.out, and saves it, internally.
        FileWriter, PrintWriter, StringWriterGeneral purpose java text-output classes
        FileOutputStream, PrintStreamMore general-purpose java text-output classes

        IMPORTANT: The interface Appendable requires that the check exception IOException must be caught when using its append(CharSequence) methods.
        Returns:
        Returns an instance of OSResponse. This response-Object (data-record) class holds three public, final fields:
        Process response-code
        Text sent to Standard-Output (as a java.lang.String)
        Text sent to Error-Output (also as a String)

        This OSResponse instance may be discarded without any effect on Process Execution. It is only provided as a convenience in case more information is required about the results of the O/S command invocation.

        Process Status: Upon completion of this method, the Operating-System java.lang.Process is guaranteed to have run to completion.
        Throws:
        java.io.IOException
        See Also:
        RUN_CMD_PRINT_OUTPUT(String[], Appendable)
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        38
        39
        40
        41
        42
        43
        44
        45
        46
        47
        48
        49
        50
        51
        52
        53
        54
        55
        56
        57
        58
        59
        60
        61
        62
        63
        64
        65
        66
        67
        68
        69
        70
        71
         if (a == null) a = NOPRINT.np;
        
         // MORE INFORMATIVE Null Check...
         // It reads better than Runtime.exec(..)'s NullPointerException message
         for (int i=0; i < cmd.length; i++) if (cmd[i] == null) throw new NullPointerException(
             "The " + i + StringParse.ordinalIndicator(i) + " array element in the 'cmd' " +
             "(O/S Command) array-parameter that was passed to this method was 'null'.  " +
             "Java's method Runtime.getRuntime().exec(cmd) will not accept a 'cmd' array " +
             "that contains any nulls."
         );
        
         if (! currentWorkingDirectory.isDirectory()) throw new IllegalArgumentException(
             "The file-system has stated that the reference passed to parameter " +
             "'currentWorkingDirectory' was not a valid directory on the file-system: " +
             '[' + currentWorkingDirectory.getAbsolutePath() + ']'
         );
        
         AppendableTap   stdOutTap   = new AppendableTap(a);
         AppendableTap   stdErrTap   = new AppendableTap(a); 
        
         try
         {
             // This will create a process with specified modifications
             ProcessBuilder b = new ProcessBuilder(cmd);
        
             if (currentWorkingDirectory != null)    b.directory(currentWorkingDirectory);
             if (mergeStdErrorAndStdOut)             b.redirectErrorStream(true);
             if (outputRedirect != null)             b.redirectOutput(outputRedirect);
             if (inputRedirect != null)              b.redirectInput(inputRedirect);
             if (errorRedirect != null)              b.redirectError(errorRedirect);
             if (environmentVariableUpdater != null) environmentVariableUpdater.accept(b.environment());
        
             // Starts the OS Command
             Process     pro         = b.start();
        
             // These 3 lines create a "Completion Monitor" instance, and then register the
             // "Reader Threads" for reading from Standard-Out and Standard-Error from the Process.
        
             Completed   completed   = new Completed();
        
             ISPT        stdOut      = new ISPT(pro.getInputStream(), stdOutTap, completed,
                                         "Thread for Reading from Standard Out"
                                      );
        
             ISPT        stdErr      = new ISPT(pro.getErrorStream(), stdErrTap, completed,
                                         "Thread for Reading from Standard Error"
                                      );
        
             // NOTE: The process, once it is instantiated, is already running.  There is no
             // need to "start" the process, the call to Runtime.exec (above does that).  Here
             // we can just wait for the reader threads to receive the EOF messages, which  is
             // how they terminate.
             completed.waitForCompletionOfAllThreads();
        
             // In this scenario, it is much more likely that Standard-Out and Error-Out will
             // finish printing before the process is actually finished - due to the redirects.
             int response = pro.waitFor();
        
             // This prints a friendly little message at the end stating what the response-code was
             a.append("Command exit with return value " + response + '\n');
        
             completed.ifExceptionThrowException();
                    
             return new OSResponse
                 (Integer.valueOf(response), stdOutTap.getString(), stdErrTap.getString());
         }
         catch (InterruptedException e)
         {
             return new OSResponse
                 (INTERRUPTED, stdOutTap.getString(), stdErrTap.getString());
         }
        
      • RUN_CMD_PRINT_OUTPUT

        public static OSResponse RUN_CMD_PRINT_OUTPUT​(java.lang.String[] cmd,
                                                      java.lang.Appendable a)
                                               throws java.io.IOException
        This will run the command named by String-Array parameter 'cmd'.
        Parameters:
        cmd - Is an array of String's that form the UNIX command.
        a - where the text-output is sent. This parameter may be null, and if it is, text will be sent to the NOPRINT.np instance. This parameter expects an implementation of Java's interface java.lang.Appendable which allows for a wide range of options when logging intermediate messages.
        Class or Interface InstanceUse & Purpose
        'System.out'Sends text to the standard-out terminal
        Torello.Java.StorageWriterSends text to System.out, and saves it, internally.
        FileWriter, PrintWriter, StringWriterGeneral purpose java text-output classes
        FileOutputStream, PrintStreamMore general-purpose java text-output classes

        IMPORTANT: The interface Appendable requires that the check exception IOException must be caught when using its append(CharSequence) methods.
        Returns:
        Returns an instance of OSResponse. This response-Object (data-record) class holds three public, final fields:
        Process response-code
        Text sent to Standard-Output (as a java.lang.String)
        Text sent to Error-Output (also as a String)

        This OSResponse instance may be discarded without any effect on Process Execution. It is only provided as a convenience in case more information is required about the results of the O/S command invocation.

        Process Status: Upon completion of this method, the Operating-System java.lang.Process is guaranteed to have run to completion.
        Throws:
        java.io.IOException
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        38
        39
        40
        41
        42
        43
        44
        45
        46
        47
        48
        49
        50
        51
        52
        53
        54
        55
        56
        57
        58
         if (a == null) a = NOPRINT.np;
        
         // MORE INFORMATIVE Null Check...
         // It reads better than Runtime.exec(..)'s NullPointerException message
         for (int i=0; i < cmd.length; i++) if (cmd[i] == null) throw new NullPointerException(
             "The " + i + StringParse.ordinalIndicator(i) + " array element in the 'cmd' " +
             "(O/S Command) array-parameter that was passed to this method was 'null'.  " +
             "Java's method Runtime.getRuntime().exec(cmd) will not accept a 'cmd' array " +
             "that contains any nulls."
         );
        
         AppendableTap   stdOutTap   = new AppendableTap(a);
         AppendableTap   stdErrTap   = new AppendableTap(a); 
        
         try
         {
             // Starts the OS Command
             Process     pro         = Runtime.getRuntime().exec(cmd);
        
             // These 3 lines create a "Completion Monitor" instance, and then register the
             // "Reader Threads" for reading from Standard-Out and Standard-Error from the Process.
        
             Completed   completed   = new Completed();
        
             ISPT        stdOut      = new ISPT(pro.getInputStream(), stdOutTap, completed,
                                         "Thread for Reading from Standard Out"
                                       );
        
             ISPT        stdErr      = new ISPT(pro.getErrorStream(), stdErrTap, completed,
                                         "Thread for Reading from Standard Error"
                                       );
        
             // NOTE: The process, once it is instantiated, is already running.  There is no
             // need to "start" the process, the call to Runtime.exec (above does that).  Here
             // we can just wait for the reader threads to receive the EOF messages, which  is
             // how they terminate.
             completed.waitForCompletionOfAllThreads();
        
             // It is unlikely this would cause the current thread to wait, because the previous
             // line will wait until both Standard-Out and Standard-Err have received EOF...
             // Perhaps the process COULD delay the return response-code here.  The reality is that
             // method 'waitFor' is the PREFERRED way to retrieve the exit-value from this process...
             // although method 'Process.exitValue()' would also probably work.
             int response = pro.waitFor();
        
             // This prints a friendly little message at the end stating what the response-code was
             a.append("Command exit with return value " + response + '\n');
        
             completed.ifExceptionThrowException();
                    
             return new OSResponse
                 (Integer.valueOf(response), stdOutTap.getString(), stdErrTap.getString());
         }
         catch (InterruptedException e)
         {
             return new OSResponse
                 (INTERRUPTED, stdOutTap.getString(), stdErrTap.getString());
         }