Package Torello.Java
Class OSCommands
- java.lang.Object
-
- Torello.Java.OSCommands
-
- All Implemented Interfaces:
java.lang.Cloneable
public abstract class OSCommands extends java.lang.Object implements java.lang.Cloneable
Root Ancestor / Parent Class for all Operating-System Execution Classes - including:MSDOS
,Shell
,GSUTIL
etc... This class serves as the root or parent class of all classes in this package which have been designed to start Operating System Calls. This class is generally a wrapper around several basic but important classes from thejava.lang
Package. These are listed below, and the functionality and features they provided are greatly expanded by this classOSCommands
, and all the descendant clases that extend it.class java.lang.Runtime
class java.lang.Process
class java.lang.ProcessBuilder
class java.lang.ProcessBuilder.Redirect
Do note that one of the motivating forces for writing these classes is merely to serve as explanation and example of using Java's classjava.lang.Process
. Quite a bit of work was done writing the reader and monitor threads to ensure that the output of executing a UNIX command is collected and returned properly. This class generates a simple instance ofOSResponse
whenever a command is invoked. This returned class contains several fields that have all the information produced by executing an O/S command.
Wildcard Issue:
On most UNIX platforms, whenever a command is issued to the O/S (by typing it, for example, inside a terminal or terminal-window) there is an execution-stage before the process is spawned where file-name and / or directory-name wildcards (usually:'*'
and'?'
) are expanded.
When a UNIX command receives a parameter list, if the file and/or directories specified by the user contains wild-cards, those wild-cards shall have already been eliminated and replaced by the O/S when the that command receives its actual parameter list. The arguments that the terminal-command actually "sees" are the actual files and/or directories from which the wild-card expression expanded. A wild-card expression (like a "reg-ex expression") is replaced by the complete list of files before the command ever begins (usually!)
Because of this situation, if a user would like, for instance, tocopy
ormove
a group of files - and use Java to do it, then a native Java A.P.I. such as thepackage java.nio.*
(or the class class FileNode API) is really the only way to ensure that wild-card expressions actually work. It is usually easiest to request an array (or ajava.util.Stream
) of files using theFileNode.flatten(...)
routines, and then pass that list to the UNIX command.
WORA:
In its inception, Java made the "Write Once, Run Anywhere" (WORA) pledge. The methods in this class are not in any way "Java-ized" versions of the Operating System Calls. Rather, they are just wrappers aroundjava.lang.Process
allowing a user to BOTH make Operating System calls easily AND to efficiently retrieve the generated text-output produced by the calls.
The bulk-work of the classes in this JAR Library were written and tested in a UNIX environment. While everything in the HTML Package ofJava HTML JAR
is indeed, O/S Independent (adhering to 'WORA'), this class and all classes which extendOSCommands
are highly O/S dependent. The methods in these classes are (for all intents and purposes) a set of hooks into native Operating System calls.
This means that an invocation of these methods while running in the wrong Operating System will just return a bunch of error-output results and thrown exceptions.
Hi-Lited Source-Code:- View Here: Torello/Java/OSCommands.java
- Open New Browser-Tab: Torello/Java/OSCommands.java
-
-
Field Summary
Fields Modifier and Type Field protected Appendable
appendable
protected boolean
cmdOrCmdAndOutput
protected Appendable
errorOutput
protected OSExtras
osExtras
protected Appendable
printCmdAppendable
protected Appendable
standardOutput
-
Constructor Summary
Constructors Constructor OSCommands()
OSCommands(Appendable appendable, boolean cmdOrCmdAndOutput, Appendable printCmdAppendable)
OSCommands(Appendable appendable, boolean cmdOrCmdAndOutput, Appendable printCmdAppendable, Appendable standardOutput, Appendable errorOutput)
OSCommands(Appendable standardOutput, Appendable errorOutput)
-
Method Summary
Synchronized Setter Methods Modifier and Type Method void
setAll(Appendable appendable, boolean cmdOrCmdAndOutput, Appendable printCmdAppendable, Appendable standardOutput, Appendable errorOutput)
void
setAppendable(Appendable appendable, boolean cmdOrCmdAndOutput, Appendable printCmdAppendable)
void
setOSExtras(OSExtras osExtras)
void
setStandardAndErrorOutput(Appendable standardOutput, Appendable errorOutput)
Synchronized Getter Methods Modifier and Type Method Appendable
appendable()
Appendable
errorOutput()
Appendable
printCmdAppendable()
Appendable
standardOutput()
Methods used by Shell
,GSUTIL
andMSDOS
Modifier and Type Method OSResponse
printAndRun(String[] command)
static OSResponse
run(String[] command, String commandStr, OSCommands osc)
static OSResponse
run(OSExtras ose, String[] command, String commandStr, OSCommands osc)
Utility Modifier and Type Method static String
commandToString(String[] command)
Methods: interface java.lang.Cloneable Modifier and Type Method abstract OSCommands
clone()
Methods: class java.lang.Object Modifier and Type Method boolean
equals(Object other)
String
toString()
-
-
-
Field Detail
-
appendable
protected java.lang.Appendable appendable
This is an instance ofjava.lang.Appendable
that will accept log text generated from the methods in this class. Since this class has the ability to send text to a terminal (likeSystem.out
, for instance); this field has been created to make it easy for the output from these Operating System commands to printed to the screen, or just about anywhere (using thisAppendable
).
This global 'log' is automatically used for printing by the methods in this class, and it may be configured using anyObject
that implements thejava.lang.Appendable
interface.
This parameter expects an implementation of Java'sinterface java.lang.Appendable
which allows for a wide range of options when logging intermediate messages.Class or Interface Instance Use & Purpose 'System.out'
Sends text to the standard-out terminal Torello.Java.StorageWriter
Sends text to System.out
, and saves it, internally.FileWriter, PrintWriter, StringWriter
General purpose java text-output classes FileOutputStream, PrintStream
More general-purpose java text-output classes
IMPORTANT: Theinterface Appendable
requires that the check exceptionIOException
must be caught when using itsappend(CharSequence)
methods.- See Also:
StorageWriter
- Code:
- Exact Field Declaration Expression:
protected Appendable appendable = System.out;
-
cmdOrCmdAndOutput
protected boolean cmdOrCmdAndOutput
Allows the user to decide between printing the command, or the command and the output of that command to the configured appendable field.
When this field is set toTRUE
, only the command will be printed to the output appendable field. When this is set toFALSE
, BOTH the command AND the output from that command are printed to appendable.
NOTE: If you would like the methods in this class to run fully silent, set the appendable field to NOPRINT.np, and nothing will be printed.
IMPORTANT: Regardless of the log-printing settings applied to the fields appendable and this field, the output generated by these commands in this class shall still be available in the OSResponse fields OSResponse.stdOut & OSResponse.stdErr.
DEFAULT: The initialized-setting for this field isFALSE
, again, meaning both the command itself, and its output, will be printed to theappendable
log (whose value is initialized to'System.out'
).
IMPORTANT:
Occasionally, as projects grow in size, the logging features of a project become ever more important. In such cases, one choice / "avenue" for output printing & logging has been to allow printing all output to a single outputAppendable
and simultaneously printing just the command text to a secondjava.lang.Appendable
.
This boolean is solely used for deciding whether to print the command text to the field appendable. This boolean field operates comletely independent from the other printing field, namely printCmdAppendable.- Code:
- Exact Field Declaration Expression:
protected boolean cmdOrCmdAndOutput = false;
-
printCmdAppendable
protected java.lang.Appendable printCmdAppendable
If a user wishes to print just the command being issues as text to some Java appendable, then a reference should be assigned to thispublic static
field. This will guarantee that any time any command from this class is issued, the text of that command will be printed to this outputjava.lang.Appendable
As should be noted, by defualt, this feild has been set to null. When this field is null, it will be ignored completely.
IMPORTANT:
Occasionally, as projects grow in size, the logging features of a project become ever more important. In such cases, one choice / "avenue" for output printing & logging has been to allow printing all output to a single outputAppendable
and simultaneously printing just the command text to a secondjava.lang.Appendable
.
Thisjava.lang.Appendable
field is solely used for printing the command text itself. It operates comletely independent from the fields appendable and cmdOrCmdAndOutput.- Code:
- Exact Field Declaration Expression:
protected Appendable printCmdAppendable = null;
-
standardOutput
protected java.lang.Appendable standardOutput
When this field is non-null, it shall receive all text that the underlying process sends toStandard Output
. When this field is null, it is ignored.
The default constructor for this class assigns 'null' to this field. Bear in mind that even when thisAppendable
is null, the underlying process being executed will continue to have itsStandard Output
text saved to an internal,private
, buffer. This buffer's contents will stil be available inside the returned instance field:OSResponse.standardOutput
The motivating force for the decision to provide anotherAppendable
for loggingStandard Output
was so that a user may receive this pipe's text output in real time, as the process executes, without having to wait for the process to run to completion.
There are numerous networked file-system operations (for instance) that may require several minutes to finish, and setting thisAppendable
allows a user to receive error notices as they happen, rather than waiting for the operation to complete.- Code:
- Exact Field Declaration Expression:
protected Appendable standardOutput = null;
-
errorOutput
protected java.lang.Appendable errorOutput
When this field is non-null, it shall receive all text that the underlying process sends toError Output
. When this field is null, it is ignored.
The default constructor for this class assigns 'null' to this field. Bear in mind that even when thisAppendable
is null, the underlying process being executed will continue to have itsError Output
text saved to an internal,private
, buffer. This buffer's contents will stil be available inside the returned instance field:OSResponse.errorOutput
The motivating force for the decision to provide anotherAppendable
for loggingError Output
was so that a user may receive this pipe's text output in real time, as the process executes, without having to wait for the process to run to completion.
There are numerous networked file-system operations (for instance) that may require several minutes to finish, and setting thisAppendable
allows a user to receive error notices as they happen, rather than waiting for the operation to complete.- Code:
- Exact Field Declaration Expression:
protected Appendable errorOutput = null;
-
-
Constructor Detail
-
OSCommands
public OSCommands()
Default constructor for instances inheriting this class. This constructor assigns the default values to all of the output loggingAppendable's
. This constructor's "See Also" section has a link to each of the loggingAppendable's
provided by this class.
Note that all of them are assigned 'null' - meaing their output will not be logged - except for the primary fieldthis.appendable
. This field is assignedSystem.out
, meaning that all text output by a process will be sent to the terminal window.- Code:
- Exact Constructor Body:
-
OSCommands
public OSCommands(java.lang.Appendable appendable, boolean cmdOrCmdAndOutput, java.lang.Appendable printCmdAppendable)
This constructor allows a user to assign theAppendable's
:appendable
&printCmdAppendable
.
The first collects all text-output generated by the processes and prints it using theAppendable's
printing methods. This includes text generated for BOTHStandard-Output
ANDError-Output
. This text is collected in real time as it is output by the underlying process.
The secondAppendable
merely accepts the requested command, itself, as an outputString
. ThisString
is printed using theAppendable's
append(...)
methods.
NOTE: Either of theseAppendable's
may be assigned null, and if they are, they are simply ignored.NullPointerException
won't throw, and the output text will simply not be printed.- Parameters:
appendable
- This parameter's reference is assigned directly to theOSCommands
field:appendable
. To clearly understand the use of this field, please review the documentation linked for that field. To summarize, thejava.lang.Appendable
that is synonymously namedappendable
simply collects all output text generated by a processes as it executes, and sends it to the reference'sappend(...)
method. This text will include that sent to BOTHStandard-Output
AND text sent toError-Output
. The text that is printed is transmitted in the order it is received from the reader-threads that read the underlying process' text-pipes.
By default this parameter is assignedSystem.out
. When this default value is used, it means that as the process executes, any and all text it prints is sent to the UNIX or MS-DOS Operating System Terminal Window.
This field may be assigned null, and when so it is just ignored. Assigning null toappendable
. will not produce aNullPointerException
.cmdOrCmdAndOutput
- Thisboolean
is assigned to theOSCommands
field namedcmdOrCmdAndOutput
.
Please review the documentation for that field to understand clearly the use of this parameter.printCmdAppendable
- Thisjava.lang.Appendable
allows for yet another output mechanism when executing operating system commands. The sole purpose of thisAppendable
is to print the process command, itself, as a JavaString
- exactly as it was issued to the operating system.
This allows a type of "Monitor Log" to store all commands being issued to the Operating-System, without having to include the full-text output that those process calls have produced. The value passed to this parameter is assigned to theOSCommands
field namedprintCmdAppendable
.
This parameter may be null, and if it is, no such output will be generated.- See Also:
appendable
,cmdOrCmdAndOutput
,printCmdAppendable
- Code:
- Exact Constructor Body:
this.appendable = appendable; this.cmdOrCmdAndOutput = cmdOrCmdAndOutput; this.printCmdAppendable = printCmdAppendable;
-
OSCommands
public OSCommands(java.lang.Appendable appendable, boolean cmdOrCmdAndOutput, java.lang.Appendable printCmdAppendable, java.lang.Appendable standardOutput, java.lang.Appendable errorOutput)
Constructor that allows for assigning all four text-collectingAppendable's
. Please review the documentation for each of these fields to understand better how theseAppendable's
may be used.
NOTE: Any of theseAppendable's
may be assigned null, and if they are, they are simply ignored.NullPointerException
won't throw, and the relevant output text that would normally be appended to it, will simply not be appended.- Parameters:
appendable
- This parameter's reference is assigned directly to theOSCommands
field:appendable
. To clearly understand the use of this field, please review the documentation linked for that field. To summarize, thejava.lang.Appendable
that is synonymously namedappendable
simply collects all output text generated by a processes as it executes, and sends it to the reference'sappend(...)
method. This text will include that sent to BOTHStandard-Output
AND text sent toError-Output
. The text that is printed is transmitted in the order it is received from the reader-threads that read the underlying process' text-pipes.
By default this parameter is assignedSystem.out
. When this default value is used, it means that as the process executes, any and all text it prints is sent to the UNIX or MS-DOS Operating System Terminal Window.
This field may be assigned null, and when so it is just ignored. Assigning null toappendable
. will not produce aNullPointerException
.cmdOrCmdAndOutput
- Thisboolean
is assigned to theOSCommands
field namedcmdOrCmdAndOutput
.
Please review the documentation for that field to understand clearly the use of this parameter.printCmdAppendable
- Thisjava.lang.Appendable
allows for yet another output mechanism when executing operating system commands. The sole purpose of thisAppendable
is to print the process command, itself, as a JavaString
- exactly as it was issued to the operating system.
This allows a type of "Monitor Log" to store all commands being issued to the Operating-System, without having to include the full-text output that those process calls have produced. The value passed to this parameter is assigned to theOSCommands
field namedprintCmdAppendable
.
This parameter may be null, and if it is, no such output will be generated.standardOutput
- ThisAppendable
is assigned to the internalOSCommands
field:standardOutput
. ThisAppendabe
, as the name hopefully implies, allows a user to collect any / all text sent by the process toStandard-Output
.
Please review the documentation for that field to better understand it's use. Also, keep in mind that null may be passed to this parameter, and if / when it is the correspondingAppendable
field will simply be ignored during the process execution.errorOutput
- ThisAppendable
is assigned to the internalOSCommands
field:errorOutput
. ThisAppendabe
, as the name hopefully implies, allows a user to collect any / all text sent by the process toError-Output
.
Please review the documentation for that field to better understand it's use. Also, keep in mind that null may be passed to this parameter, and if / when it is the correspondingAppendable
field will simply be ignored during the process execution.- See Also:
appendable
,cmdOrCmdAndOutput
,printCmdAppendable
,standardOutput
,errorOutput
- Code:
- Exact Constructor Body:
this.appendable = appendable; this.cmdOrCmdAndOutput = cmdOrCmdAndOutput; this.printCmdAppendable = printCmdAppendable; this.standardOutput = standardOutput; this.errorOutput = errorOutput;
-
OSCommands
public OSCommands(java.lang.Appendable standardOutput, java.lang.Appendable errorOutput)
This constructor retains all default values for the internal fields of this class, except for the twoOSCommands
Appendable
fields listed, namely:standardOutput
anderrorOutput
- Parameters:
standardOutput
- ThisAppendable
is assigned to the internalOSCommands
field:standardOutput
. ThisAppendabe
, as the name hopefully implies, allows a user to collect any / all text sent by the process toStandard-Output
.
Please review the documentation for that field to better understand it's use. Also, keep in mind that null may be passed to this parameter, and if / when it is the correspondingAppendable
field will simply be ignored during the process execution.errorOutput
- ThisAppendable
is assigned to the internalOSCommands
field:errorOutput
. ThisAppendabe
, as the name hopefully implies, allows a user to collect any / all text sent by the process toError-Output
.
Please review the documentation for that field to better understand it's use. Also, keep in mind that null may be passed to this parameter, and if / when it is the correspondingAppendable
field will simply be ignored during the process execution.- See Also:
standardOutput
,errorOutput
- Code:
- Exact Constructor Body:
this.appendable = null; this.standardOutput = standardOutput; this.errorOutput = errorOutput;
-
-
Method Detail
-
setAppendable
public void setAppendable(java.lang.Appendable appendable, boolean cmdOrCmdAndOutput, java.lang.Appendable printCmdAppendable)
This method is nearly identical to the constructor that assigns the fields and has the exact same parameter names & types as this one.
This method's one minor difference is that it doesn't actually build a new instance ofOSCommands
, but rather resets the internal log-fields instead.- Parameters:
appendable
- This parameter's reference is assigned directly to theOSCommands
field:appendable
. To clearly understand the use of this field, please review the documentation linked for that field. To summarize, thejava.lang.Appendable
that is synonymously namedappendable
simply collects all output text generated by a processes as it executes, and sends it to the reference'sappend(...)
method. This text will include that sent to BOTHStandard-Output
AND text sent toError-Output
. The text that is printed is transmitted in the order it is received from the reader-threads that read the underlying process' text-pipes.
By default this parameter is assignedSystem.out
. When this default value is used, it means that as the process executes, any and all text it prints is sent to the UNIX or MS-DOS Operating System Terminal Window.
This field may be assigned null, and when so it is just ignored. Assigning null toappendable
. will not produce aNullPointerException
.cmdOrCmdAndOutput
- Thisboolean
is assigned to theOSCommands
field namedcmdOrCmdAndOutput
.
Please review the documentation for that field to understand clearly the use of this parameter.printCmdAppendable
- Thisjava.lang.Appendable
allows for yet another output mechanism when executing operating system commands. The sole purpose of thisAppendable
is to print the process command, itself, as a JavaString
- exactly as it was issued to the operating system.
This allows a type of "Monitor Log" to store all commands being issued to the Operating-System, without having to include the full-text output that those process calls have produced. The value passed to this parameter is assigned to theOSCommands
field namedprintCmdAppendable
.
This parameter may be null, and if it is, no such output will be generated.- See Also:
appendable
,cmdOrCmdAndOutput
,printCmdAppendable
- Code:
- Exact Method Body:
this.appendable = appendable; this.cmdOrCmdAndOutput = cmdOrCmdAndOutput; this.printCmdAppendable = printCmdAppendable;
-
setStandardAndErrorOutput
public void setStandardAndErrorOutput(java.lang.Appendable standardOutput, java.lang.Appendable errorOutput)
This method is nearly identical to the constructor that assigns the fields and has the exact same parameter names & types as this one.
This method's one minor difference is that it doesn't actually build a new instance ofOSCommands
, but rather resets the internal log-fields instead.- Parameters:
standardOutput
- ThisAppendable
is assigned to the internalOSCommands
field:standardOutput
. ThisAppendabe
, as the name hopefully implies, allows a user to collect any / all text sent by the process toStandard-Output
.
Please review the documentation for that field to better understand it's use. Also, keep in mind that null may be passed to this parameter, and if / when it is the correspondingAppendable
field will simply be ignored during the process execution.errorOutput
- ThisAppendable
is assigned to the internalOSCommands
field:errorOutput
. ThisAppendabe
, as the name hopefully implies, allows a user to collect any / all text sent by the process toError-Output
.
Please review the documentation for that field to better understand it's use. Also, keep in mind that null may be passed to this parameter, and if / when it is the correspondingAppendable
field will simply be ignored during the process execution.- See Also:
standardOutput
,errorOutput
- Code:
- Exact Method Body:
this.standardOutput = standardOutput; this.errorOutput = errorOutput;
-
setAll
public void setAll(java.lang.Appendable appendable, boolean cmdOrCmdAndOutput, java.lang.Appendable printCmdAppendable, java.lang.Appendable standardOutput, java.lang.Appendable errorOutput)
This method is nearly identical to the constructor that assigns the fields and has the exact same parameter names & types as this one.
This method's one minor difference is that it doesn't actually build a new instance ofOSCommands
, but rather resets the internal log-fields instead.- Parameters:
appendable
- This parameter's reference is assigned directly to theOSCommands
field:appendable
. To clearly understand the use of this field, please review the documentation linked for that field. To summarize, thejava.lang.Appendable
that is synonymously namedappendable
simply collects all output text generated by a processes as it executes, and sends it to the reference'sappend(...)
method. This text will include that sent to BOTHStandard-Output
AND text sent toError-Output
. The text that is printed is transmitted in the order it is received from the reader-threads that read the underlying process' text-pipes.
By default this parameter is assignedSystem.out
. When this default value is used, it means that as the process executes, any and all text it prints is sent to the UNIX or MS-DOS Operating System Terminal Window.
This field may be assigned null, and when so it is just ignored. Assigning null toappendable
. will not produce aNullPointerException
.cmdOrCmdAndOutput
- Thisboolean
is assigned to theOSCommands
field namedcmdOrCmdAndOutput
.
Please review the documentation for that field to understand clearly the use of this parameter.printCmdAppendable
- Thisjava.lang.Appendable
allows for yet another output mechanism when executing operating system commands. The sole purpose of thisAppendable
is to print the process command, itself, as a JavaString
- exactly as it was issued to the operating system.
This allows a type of "Monitor Log" to store all commands being issued to the Operating-System, without having to include the full-text output that those process calls have produced. The value passed to this parameter is assigned to theOSCommands
field namedprintCmdAppendable
.
This parameter may be null, and if it is, no such output will be generated.standardOutput
- ThisAppendable
is assigned to the internalOSCommands
field:standardOutput
. ThisAppendabe
, as the name hopefully implies, allows a user to collect any / all text sent by the process toStandard-Output
.
Please review the documentation for that field to better understand it's use. Also, keep in mind that null may be passed to this parameter, and if / when it is the correspondingAppendable
field will simply be ignored during the process execution.errorOutput
- ThisAppendable
is assigned to the internalOSCommands
field:errorOutput
. ThisAppendabe
, as the name hopefully implies, allows a user to collect any / all text sent by the process toError-Output
.
Please review the documentation for that field to better understand it's use. Also, keep in mind that null may be passed to this parameter, and if / when it is the correspondingAppendable
field will simply be ignored during the process execution.- See Also:
appendable
,cmdOrCmdAndOutput
,printCmdAppendable
,standardOutput
,errorOutput
- Code:
- Exact Method Body:
this.appendable = appendable; this.cmdOrCmdAndOutput = cmdOrCmdAndOutput; this.printCmdAppendable = printCmdAppendable; this.standardOutput = standardOutput; this.errorOutput = errorOutput;
-
setOSExtras
public void setOSExtras(OSExtras osExtras)
Sets the Extras / Features Record. This will be applied to the very next command execution made by this class. Note that immediately afterwards, the fieldosExtras
will be reset to 'null'. This field must be explicity set each and every time you would like it applied to a command execution request.- Parameters:
osExtras
- An instance of classOSExtras
- Code:
- Exact Method Body:
this.osExtras = osExtras;
-
appendable
public java.lang.Appendable appendable()
Simple getter method forappendable
- Returns:
- The current reference to
appendable
- Code:
- Exact Method Body:
return appendable;
-
printCmdAppendable
public java.lang.Appendable printCmdAppendable()
Simple getter method forprintCmdAppendable
- Returns:
- The current reference to
printCmdAppendable
- Code:
- Exact Method Body:
return printCmdAppendable;
-
standardOutput
public java.lang.Appendable standardOutput()
Simple getter method forstandardOutput
- Returns:
- The current reference to
standardOutput
- Code:
- Exact Method Body:
return standardOutput;
-
errorOutput
public java.lang.Appendable errorOutput()
Simple getter method forerrorOutput
- Returns:
- The current reference to
errorOutput
- Code:
- Exact Method Body:
return errorOutput;
-
commandToString
public static java.lang.String commandToString(java.lang.String[] command)
Extremely simple method that collates theString
-arguments in a command into a single, returned,String
- Parameters:
command
- The input command, as an array ofString
-arguments.- Returns:
- A complete
String
comprised of nothing more than the individual arguments appended to each-other, separated by a space-character. - Code:
- Exact Method Body:
StringBuilder sb = new StringBuilder(); for (int i=0; i < command.length; i++) sb.append(command[i] + " "); return sb.toString();
-
printAndRun
public OSResponse printAndRun(java.lang.String[] command) throws java.io.IOException
Executes a command by spawning an operating-system process.- Returns:
- An instance of
OSResponse
, containing all generated output produced, and a response code. - Throws:
java.io.IOException
- See Also:
run(String[], String, OSCommands)
,run(OSExtras, String[], String, OSCommands)
- Code:
- Exact Method Body:
String cmdStr = commandToString(command); if (this.printCmdAppendable != null) { this.printCmdAppendable.append(cmdStr); this.printCmdAppendable.append('\n'); } if (this.appendable != null) { this.appendable.append(cmdStr); this.appendable.append('\n'); } // this.cmdOrCmdAndOutput ? null : this.appendable, if (osExtras == null) return run(command, cmdStr, this); OSExtras ose = osExtras.clone(); this.osExtras = null; return run(ose, command, cmdStr, this);
-
run
public static OSResponse run(java.lang.String[] command, java.lang.String commandStr, OSCommands osc) throws java.io.IOException
This will run the command that may be specified by theString-Array
parameter'command'
.- Parameters:
command
- Is an array ofString's
that form the Operating-System or Cloud Command.commandStr
- For efficiency, this parameter is merely the concatenation of theString's
inside of the previous /'command'
parameter. Since this class output-print's the commands more than once, it is faster to save the entireString
after a single-printing.
This parameter may be null, and if it is'commandStr'
will be re-computed by concatenating all of theString's
inside'command'
.osc
- An instance of this class, replete with allAppendable
logs.- Returns:
- Returns an instance of
OSResponse
. This response-Object
(data-record) class holds threepublic, final
fields:
① Processresponse-code
② Text sent toStandard-Output
(as ajava.lang.String
)
③ Text sent toError-Output
(also as aString
)
ThisOSResponse
instance may be discarded without any effect onProcess
Execution. It is only provided as a convenience in case more information is required about the results of theO/S
command invocation.
Process Status: Upon completion of this method, theOperating-System java.lang.Process
is guaranteed to have run to completion. - Throws:
java.io.IOException
- Code:
- Exact Method Body:
// MORE INFORMATIVE Null Check... // It reads better than Runtime.exec(..)'s NullPointerException message for (int i=0; i < command.length; i++) if (command[i] == null) throw new NullPointerException( "The " + i + StringParse.ordinalIndicator(i) + " array element in the 'command' " + "(O/S Command) array-parameter that was passed to this method was 'null'. " + "Java's method Runtime.getRuntime().exec(command) will not accept a 'command' " + "array that contains any nulls." ); // Used to build the String's for this class standardOutput and errorOutput fields! StringBuilder standardOutputSB = new StringBuilder(); StringBuilder errorOutputSB = new StringBuilder(); // The user should not pass null to this parameter in this method. However, this method is // is most often invoked internally, above. If the user makes a direct call to this, and // passes null, then it is smarter to just computer/generate the 'commandStr' if (commandStr == null) commandStr = commandToString(command); try { // Starts the OS Command Process pro = Runtime.getRuntime().exec(command); // 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. // These create two "Daemon Threads" that read process-output and error-output using // Java Thread's. These will not hang **UNLESS** one of the InputStream read method's // hang/lock. Completed completed = new Completed(); // Note that the constructor's below start the printer/reader/monitors - there is no // need to actually keep a reference/pointer to these classes once they are // constructed. Passing 'completed' to these constructors is enough! // // ALSO: It is completely immaterial whether/if any of the three appendable's passed to // the TriAppendable-Constructor are actually null. Note that only the one whose // name ends with "SB" is guaranteed not to be null. The other two // (user-provided) Appendable's can easily be null! /* ISPT standardOutISPT = */ new ISPT( pro.getInputStream(), new TriAppendable(osc.appendable, standardOutputSB, osc.standardOutput), completed, "Thread for Reading from Standard Output" ); /* ISPT errorOutISPT = */ new ISPT( pro.getErrorStream(), new TriAppendable(osc.appendable, errorOutputSB, osc.errorOutput), completed, "Thread for Reading from Error Output" ); // 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 Error-Out 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 if (osc.appendable != null) osc.appendable.append("Command exit with return value " + response + '\n'); completed.ifExceptionThrowException(); // Note that a '0' response-code usually means 'succesfully terminated' return new OSResponse (commandStr, response, standardOutputSB.toString(), errorOutputSB.toString()); } catch (InterruptedException e) { return new OSResponse( commandStr, OSResponse.INTERRUPTED, standardOutputSB.toString(), errorOutputSB.toString() ); }
-
run
public static OSResponse run(OSExtras ose, java.lang.String[] command, java.lang.String commandStr, OSCommands osc) throws java.io.IOException
This will run the command named byString-Array
parameter'cmd'
, using the specified adjustment-parameters.- Parameters:
ose
- The list of additional processor directives.command
- Is an array ofString's
that form the Operating-System or Cloud Command.commandStr
- For efficiency, this parameter is merely the concatenation of theString's
inside of the previous /'command'
parameter. Since this class output-print's the commands more than once, it is faster to save the entireString
after a single-printing.
This parameter may be null, and if it is'commandStr'
will be re-computed by concatenating all of theString's
inside'command'
.osc
- An instance of this class, replete with allAppendable
logs.- Returns:
- Returns an instance of
OSResponse
. This response-Object
(data-record) class holds threepublic, final
fields:
① Processresponse-code
② Text sent toStandard-Output
(as ajava.lang.String
)
③ Text sent toError-Output
(also as aString
)
ThisOSResponse
instance may be discarded without any effect onProcess
Execution. It is only provided as a convenience in case more information is required about the results of theO/S
command invocation.
Process Status: Upon completion of this method, theOperating-System java.lang.Process
is guaranteed to have run to completion. - Throws:
java.io.IOException
- Code:
- Exact Method Body:
// MORE INFORMATIVE Null Check... // It reads better than Runtime.exec(..)'s NullPointerException message for (int i=0; i < command.length; i++) if (command[i] == null) throw new NullPointerException( "The " + i + StringParse.ordinalIndicator(i) + " array element in the 'command' " + "(O/S Command) array-parameter that was passed to this method was 'null'. " + "Java's method Runtime.getRuntime().exec(command) will not accept a 'command' " + "array that contains any nulls." ); if (ose.currentWorkingDirectory != null) if (! ose.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: " + '[' + ose.currentWorkingDirectory.getAbsolutePath() + ']' ); // Used to build the String's for this class standardOutput and errorOutput fields! StringBuilder standardOutputSB = new StringBuilder(); StringBuilder errorOutputSB = new StringBuilder(); if (commandStr == null) commandStr = commandToString(command); try { // This will create a process with specified modifications ProcessBuilder b = new ProcessBuilder(command); // NOTE: These "extra" configurations aren't so useful. HOWEVER, this is the only // reason this method is provided. Normally, you would use the other method // with the exact same name (Which leaves out all of these re-directs). If you // have opted to use this method, instead of the one that leaves these things // out, the redirects are set here! All they do is ask the OS Process to do that // "Operating System Thing" were input and/or output are retrieved/sent to a file if (ose.currentWorkingDirectory != null) b.directory(ose.currentWorkingDirectory); if (ose.mergeStdErrorAndStdOut) b.redirectErrorStream(true); if (ose.outputRedirect != null) b.redirectOutput(ose.outputRedirect); if (ose.inputRedirect != null) b.redirectInput(ose.inputRedirect); if (ose.errorRedirect != null) b.redirectError(ose.errorRedirect); if (ose.environmentVariableUpdater != null) ose.environmentVariableUpdater.accept(b.environment()); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // CODE BELOW IS IDENTICAL TO THAT IN PREVIOUS / ABOVE METHOD! NO COMMENTS INCLUDED! // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** Process pro = b.start(); Completed completed = new Completed(); new ISPT( pro.getInputStream(), new TriAppendable(osc.appendable, standardOutputSB, osc.standardOutput), completed, "Thread for Reading from Standard Output" ); new ISPT( pro.getErrorStream(), new TriAppendable(osc.appendable, errorOutputSB, osc.errorOutput), completed, "Thread for Reading from Error Output" ); completed.waitForCompletionOfAllThreads(); int response = pro.waitFor(); if (osc.appendable != null) osc.appendable.append("Command exit with return value " + response + '\n'); completed.ifExceptionThrowException(); return new OSResponse (commandStr, response, standardOutputSB.toString(), errorOutputSB.toString()); } catch (InterruptedException e) { return new OSResponse( commandStr, OSResponse.INTERRUPTED, standardOutputSB.toString(), errorOutputSB.toString() ); }
-
toString
public java.lang.String toString()
Generates aString
this class. The returnedString
merely encodes the class-names of the non-nullAppendable's
.- Overrides:
toString
in classjava.lang.Object
- Returns:
- A simple representation of this class, as a
java.lang.String
- Code:
- Exact Method Body:
// private static String toStrApp(Appendable a) // { return (a == null) ? "null\n" : (a.getClass().getName() + '\n'); } return "appendable: " + toStrApp(this.appendable) + "cmdOrCmdAndOutput: " + this.cmdOrCmdAndOutput + '\n' + "printCmdAppendable: " + toStrApp(this.printCmdAppendable) + "standardOutput: " + toStrApp(this.standardOutput) + "errorOutput: " + toStrApp(this.errorOutput);
-
equals
public boolean equals(java.lang.Object other)
Checks for equality based on whether two instances have identical outputAppendable
references.- Overrides:
equals
in classjava.lang.Object
- Parameters:
other
- Any Java Object. Only a valid sub-class ofOSCommands
could possibly produce aTRUE
return value- Returns:
TRUE
if and only if each of theOSCommands
fields are identical references in both'this'
and'other'
.- Code:
- Exact Method Body:
if (other == null) return false; if (! OSCommands.class.isAssignableFrom(other.getClass())) return false; OSCommands o = (OSCommands) other; return (this.appendable == o.appendable) && (this.cmdOrCmdAndOutput == o.cmdOrCmdAndOutput) && (this.printCmdAppendable == o.printCmdAppendable) && (this.standardOutput == o.standardOutput) && (this.errorOutput == o.errorOutput);
-
clone
public abstract OSCommands clone()
Creates a clone of'this'
instance. Though unlikely of much use, this could conceivably have some function if similar, but non-identical, output mechanisms were being used.- Overrides:
clone
in classjava.lang.Object
- Returns:
- An exact copy of
'this'
instance - one in which all outputAppendable's
have had their references copied into the new instance.
-
-