Class JRT
- Direct Known Subclasses:
SandboxedJRT
Variable access is achieved through the VariableManager interface. The constructor requires a VariableManager instance (which, in this case, is the compiled Jawk class itself).
Main services include:
- File and command output redirection via print(f).
- File and command input redirection via getline.
- Most built-in AWK functions, such as system(), sprintf(), etc.
- Automatic AWK type conversion routines.
- IO management for input rule processing.
- Random number engine management.
- Input field ($0, $1, ...) management.
All static and non-static service methods should be package-private
to the resultant AWK script class rather than public. However,
the resultant script class is not in the io.jawk.jrt package
by default, and the user may reassign the resultant script class
to another package. Therefore, all accessed methods are public.
- Author:
- Danny Daglas
- See Also:
-
Constructor Summary
ConstructorsConstructorDescriptionJRT(VariableManager vm, Locale locale, AwkSink awkSink, PrintStream error) Create a JRT with explicit default output and error streams. -
Method Summary
Modifier and TypeMethodDescriptionvoidapplyRS.final voidapplySpecialVariables(Map<String, Object> variableMap) Applies only the JRT-managed special variable assignments from the supplied map (FS, RS, OFS, ORS, CONVFMT, OFMT, SUBSEP, FILENAME, NF, NR, FNR, ARGC).static voidCalled by AVM/compiled modules to assign local environment variables to an associative array (in this case, to ENVIRON).final voidassignInitialVariables(Map<String, Object> initialVarMap) Assign all -v variables.voidassignInputLineFromGetline(Object value) Assigns$0from a getline result and initializes$1..$NF.static booleanCompares two objects.booleanconsumeInput(InputSource source) Attempt to consume one record from a structured input source and expose it as the current input record.booleanconsumeInputForEval(InputSource source) Consume at most one record from a structured source for expression evaluation.consumeInputToTarget(InputSource source) Attempt to consume one record from a structured input source forgetline target, returning only the input text and leaving the current input record state untouched.static booleancontainsAwkKey(Map<Object, Object> map, Object key) Checks key existence using AWK semantics when the supplied map is backed by anAssocArray, otherwise falling back to regularMapsemantics.copySpecialVariables(Map<String, Object> variableMap) Copies only the JRT-managed special variables from the supplied map.createAwkMap(boolean sortedArrayKeys) Creates an AWK-managed associative array and exposes it as a plainMapfor callers that do not need the concrete runtime type.static ObjectReturn an object which is numerically equivalent to one minus a given object.Get ARGC from the VariableManager.Returns the default output sink used byprintandprintf.static ObjectgetAwkValue(Map<Object, Object> map, Object key) Reads a map element using AWK semantics when the supplied map is backed by anAssocArray.Returns the current CONVFMT value as a string.Get CONVFMT from the VariableManager.Get FILENAME as tracked by JRT.getFNR()Get the current FNR value as tracked by JRT.Returns the current FS value as a string.getFSVar()Get FS from the VariableManager.Getter for the fieldinputLine.Returns the locale used for number formatting in this runtime.getNF()Retrieve the current value of NF.getNR()Get the current NR value as tracked by JRT.Get OFMT from the VariableManager.Returns the current OFS value as a string.Get OFS from the VariableManager.Returns the current ORS value as a string.Get ORS from the VariableManager.Getter for the fieldoutputFiles.Returns the underlyingPartitioningReadercurrently in use by the activeInputSource, ornullif the source is not stream-based.Get RLENGTH tracked by JRT.Returns the current RS value as a string.Get RSTART tracked by JRT (1-based).getRSVar()Get RS from the VariableManager.Returns the current SUBSEP value as a string.Get SUBSEP from the VariableManager.booleanstatic ObjectReturn an object which is numerically equivalent to one plus a given object.static booleanisActuallyLong(double d) Determines whether a double value actually represents a long integer within the limits of floating point precision.static booleanReturns whether the supplied variable name is managed directly by JRT rather than through the AVM runtime stack.Attempt to close an open stream, whether it is an input file, output file, input process, or output process.voidjrtCloseAll.booleanjrtConsumeCommandInput.jrtConsumeCommandInputForGetline(String cmdString) Retrieve the next line of output from a command, executing the command if necessary and store it to $0.booleanjrtConsumeFileInput(String fileNameParam) jrtConsumeFileInput.jrtConsumeFileInputForGetline(String fileNameParam) jrtConsumeFileInputForGetline.jrtGetInputField(long fieldnum) jrtGetInputField.jrtGetInputField(Object fieldnumObj) Retrieve the contents of a particular input field.Retrieve $0.jrtGetPrintStream(String fileNameParam, boolean append) Retrieve the PrintStream which writes to a particular file, creating the PrintStream if necessary.voidSplits $0 into $1, $2, etc.jrtSetInputField(Object valueObj, long fieldNum) Stores value_obj into an input field.voidAdjust the current input field list and $0 when NF is updated by the AWK script.jrtSpawnForOutput(String cmd) Retrieve the PrintStream which shuttles data to stdin for a process, executing the process if necessary.Executes the command specified by cmd and waits for termination, returning an Integer object containing the return code.static BSDRandomnewRandom(int seed) newRandom.static longparseFieldNumber(Object obj) Convert a field designator to a non-negative long, raising an AWK runtime exception when the value is invalid.voidprepareForExecution(String defaultFs, String defaultRs) Resets per-execution JRT state and re-applies the default runtime special variables for a new script or expression execution.voidprintDefault(Object[] values) Writes a standard AWKprintoperation to the default output.voidprintfDefault(String format, Object[] values) Writes a formatted AWK output string to the specified sink.static voidprintfNoCatch(PrintStream ps, Locale locale, String fmtArg, Object... arr) printfFunctionNoCatch.static voidprintfNoCatch(Locale locale, String fmtArg, Object... arr) printfFunctionNoCatch.voidprintfToFile(String fileNameParam, boolean append, String format, Object[] values) Writes formatted AWK output to a redirected file.voidprintfToProcess(String cmd, String format, Object[] values) Writes formatted AWK output to a redirected process.voidprintToFile(String fileNameParam, boolean append, Object[] values) Writes a standard AWKprintoperation to a redirected file.voidprintToProcess(String cmd, Object[] values) Writes a standard AWKprintoperation to a redirected process.voidSet ARGC via the VariableManager.voidsetAwkSink(AwkSink sink) Sets the sink used by defaultprintandprintfoperations.voidsetCONVFMT(Object value) Set CONVFMT via the VariableManager.voidsetErrorStream(PrintStream errorStream) Sets the stream used for the stderr output of spawned processes (e.g.system("...")).voidsetFILENAMEViaJrt(String name) Set FILENAME through VariableManager and update JRT mirror.voidAssign FNR to a specific value; also updates the VariableManager copy.voidSet FS via the VariableManager.voidsetInputLine(String inputLine) Setter for the fieldinputLine.voidSet NF to the specified value and update $0 and fields accordingly.voidAssign NR to a specific value; also updates the VariableManager copy.voidSet OFMT via the VariableManager.voidSet OFS via the VariableManager.voidSet ORS via the VariableManager.voidsetRLENGTH(Object value) Set RLENGTH tracked by JRT and mirror to VariableManager.voidSet RS via the VariableManager and apply it to the current reader if any.voidSet RSTART tracked by JRT (1-based) and mirror to VariableManager.voidSet SUBSEP via the VariableManager.intSplits the string into parts separated by one or more spaces; blank first and last fields are eliminated.intSplits the string into parts separated the regular expression fs.static StringsprintfNoCatch(Locale locale, String fmtArg, Object... arr) sprintfFunctionNoCatch.static Stringsubstr.static Stringsubstr.static inttimeSeed()timeSeed.Convert Strings, Integers, and Doubles to Strings based on the CONVFMT variable contents and the stored Locale.final booleanConverts an Integer, Double, String, Pattern, or ConditionPair to a boolean.static doubleConvert a String, Integer, or Double to Double.static longConvert a String, Long, or Double to Long.
-
Constructor Details
-
JRT
Create a JRT with explicit default output and error streams.- Parameters:
vm- The VariableManager to use with this JRT.locale- The Locale to use for number formatting.awkSink- default output sink used by plain AWK print operationserror- default error stream used for process stderr
-
-
Method Details
-
setAwkSink
Sets the sink used by defaultprintandprintfoperations.- Parameters:
sink- output sink to use
-
setErrorStream
Sets the stream used for the stderr output of spawned processes (e.g.system("...")).- Parameters:
errorStream- stream to receive process stderr
-
getAwkSink
Returns the default output sink used byprintandprintf.- Returns:
- the current AWK sink
-
getLocale
Returns the locale used for number formatting in this runtime.- Returns:
- the runtime locale
-
isJrtManagedSpecialVariable
Returns whether the supplied variable name is managed directly by JRT rather than through the AVM runtime stack.- Parameters:
name- variable name to inspect- Returns:
truewhen the variable is a JRT-managed special variable
-
copySpecialVariables
Copies only the JRT-managed special variables from the supplied map.- Parameters:
variableMap- source variable map- Returns:
- a new map containing only JRT-managed special variables
-
prepareForExecution
Resets per-execution JRT state and re-applies the default runtime special variables for a new script or expression execution.The
defaultFsanddefaultRsparameters allow the caller to configure the initial field and record separators. Other special variables (OFS,ORS,CONVFMT,OFMT,SUBSEP) use their POSIX-mandated defaults (seeAwkconstants) which are platform-independent and therefore not parameterized. Platform-specific end-of-line handling is the responsibility of theAwkSink.- Parameters:
defaultFs- default field separator, ornullforAwk.DEFAULT_FSdefaultRs- default record separator
-
assignInitialVariables
Assign all -v variables.- Parameters:
initialVarMap- A map containing all initial variable names and their values.
-
applySpecialVariables
Applies only the JRT-managed special variable assignments from the supplied map (FS, RS, OFS, ORS, CONVFMT, OFMT, SUBSEP, FILENAME, NF, NR, FNR, ARGC). Non-special variables are silently skipped because they require the runtime stack to be fully initialized (which happens during tuple execution).- Parameters:
variableMap- a map of variable names to values
-
assignEnvironmentVariables
Called by AVM/compiled modules to assign local environment variables to an associative array (in this case, to ENVIRON).- Parameters:
aa- The associative array to populate with environment variables. The module asserts that the associative array is empty prior to population.
-
createAwkMap
Creates an AWK-managed associative array and exposes it as a plainMapfor callers that do not need the concrete runtime type.- Parameters:
sortedArrayKeys-trueto keep keys sorted- Returns:
- a new AWK associative array
-
containsAwkKey
Checks key existence using AWK semantics when the supplied map is backed by anAssocArray, otherwise falling back to regularMapsemantics.- Parameters:
map- map to inspectkey- key to look up- Returns:
truewhen the key exists
-
getAwkValue
Reads a map element using AWK semantics when the supplied map is backed by anAssocArray. For plainMapinstances, missing ornull-valued entries are exposed as the AWK blank value so later expression evaluation never receives a rawnull.- Parameters:
map- map to inspectkey- key to look up- Returns:
- the stored value, or the AWK blank value when no concrete value is present
-
toAwkString
Convert Strings, Integers, and Doubles to Strings based on the CONVFMT variable contents and the stored Locale.- Parameters:
o- Object to convert.- Returns:
- A String representation of o.
-
toDouble
Convert a String, Integer, or Double to Double.- Parameters:
o- Object to convert.- Returns:
- the "double" value of o, or 0 if invalid
-
isActuallyLong
public static boolean isActuallyLong(double d) Determines whether a double value actually represents a long integer within the limits of floating point precision.- Parameters:
d- the double value to examine- Returns:
trueifdis effectively an integer
-
toLong
Convert a String, Long, or Double to Long.- Parameters:
o- Object to convert.- Returns:
- the "long" value of o, or 0 if invalid
-
parseFieldNumber
Convert a field designator to a non-negative long, raising an AWK runtime exception when the value is invalid.- Parameters:
obj- the object identifying the field (for example, the result of a numeric expression)- Returns:
- the parsed field number as a long
-
compare2
Compares two objects. Whether to employ less-than, equals, or greater-than checks depends on the mode chosen by the callee. It handles Awk variable rules and type conversion semantics.- Parameters:
o1- The 1st object.o2- the 2nd object.mode-- < 0 - Return true if o1 < o2.
- 0 - Return true if o1 == o2.
- > 0 - Return true if o1 > o2.
- Returns:
- a boolean
-
inc
Return an object which is numerically equivalent to one plus a given object. For Integers and Doubles, this is similar to o+1. For Strings, attempts are made to convert it to a double first. If the String does not represent a valid Double, 1 is returned.- Parameters:
o- The object to increase.- Returns:
- o+1 if o is an Integer or Double object, or if o is a String object and represents a double. Otherwise, 1 is returned. If the return value is an integer, an Integer object is returned. Otherwise, a Double object is returned.
-
dec
Return an object which is numerically equivalent to one minus a given object. For Integers and Doubles, this is similar to o-1. For Strings, attempts are made to convert it to a double first. If the String does not represent a valid Double, -1 is returned.- Parameters:
o- The object to increase.- Returns:
- o-1 if o is an Integer or Double object, or if o is a String object and represents a double. Otherwise, -1 is returned. If the return value is an integer, an Integer object is returned. Otherwise, a Double object is returned.
-
toBoolean
Converts an Integer, Double, String, Pattern, or ConditionPair to a boolean.- Parameters:
o- The object to convert to a boolean.- Returns:
- For the following class types for o:
- Integer - o.intValue() != 0
- Long - o.longValue() != 0
- Double - o.doubleValue() != 0
- String - o.length() > 0
- UninitializedObject - false
- Pattern - $0 ~ o
-
split
Splits the string into parts separated by one or more spaces; blank first and last fields are eliminated. This conforms to the 2-argument version of AWK's split function.- Parameters:
array- The array to populate.string- The string to split.- Returns:
- The number of parts resulting from this split operation.
-
split
Splits the string into parts separated the regular expression fs. This conforms to the 3-argument version of AWK's split function.If fs is blank, it behaves similar to the 2-arg version of AWK's split function.
- Parameters:
fieldSeparator- Field separator regular expression.array- The array to populate.string- The string to split.- Returns:
- The number of parts resulting from this split operation.
-
getPartitioningReader
Returns the underlyingPartitioningReadercurrently in use by the activeInputSource, ornullif the source is not stream-based.- Returns:
- the active reader, or
null
-
getInputLine
Getter for the field
inputLine.- Returns:
- a
Stringobject
-
getNF
Retrieve the current value of NF. When fields are initialized this returns the number of fields in $0; otherwise 0.- Returns:
- current NF value
-
setNF
Set NF to the specified value and update $0 and fields accordingly.- Parameters:
nfObject- value to assign to NF
-
getNR
Get the current NR value as tracked by JRT.- Returns:
- current NR
-
setNR
Assign NR to a specific value; also updates the VariableManager copy.- Parameters:
value- value to assign
-
getFNR
Get the current FNR value as tracked by JRT.- Returns:
- current FNR
-
setFNR
Assign FNR to a specific value; also updates the VariableManager copy.- Parameters:
value- value to assign
-
getFSVar
Get FS from the VariableManager.- Returns:
- FS value
-
getFSString
Returns the current FS value as a string.- Returns:
- current field separator
-
setFS
Set FS via the VariableManager.- Parameters:
value- new FS value
-
getRSVar
Get RS from the VariableManager.- Returns:
- RS value
-
getRSString
Returns the current RS value as a string.- Returns:
- current record separator
-
setRS
Set RS via the VariableManager and apply it to the current reader if any.- Parameters:
value- new RS value
-
getOFSVar
Get OFS from the VariableManager.- Returns:
- OFS value
-
getOFSString
Returns the current OFS value as a string.- Returns:
- current output field separator
-
setOFS
Set OFS via the VariableManager.- Parameters:
value- new OFS value
-
getORSVar
Get ORS from the VariableManager.- Returns:
- ORS value
-
getORSString
Returns the current ORS value as a string.- Returns:
- current output record separator
-
setORS
Set ORS via the VariableManager.- Parameters:
value- new ORS value
-
getRSTART
Get RSTART tracked by JRT (1-based).- Returns:
- current RSTART
-
setRSTART
Set RSTART tracked by JRT (1-based) and mirror to VariableManager.- Parameters:
value- new RSTART
-
getRLENGTH
Get RLENGTH tracked by JRT.- Returns:
- current RLENGTH
-
setRLENGTH
Set RLENGTH tracked by JRT and mirror to VariableManager.- Parameters:
value- new RLENGTH
-
getFILENAME
Get FILENAME as tracked by JRT.- Returns:
- current FILENAME (empty string for stdin/pipe)
-
setFILENAMEViaJrt
Set FILENAME through VariableManager and update JRT mirror.- Parameters:
name- file name to set
-
getSUBSEPVar
Get SUBSEP from the VariableManager.- Returns:
- SUBSEP value
-
getSUBSEPString
Returns the current SUBSEP value as a string.- Returns:
- current multidimensional-array subscript separator
-
setSUBSEP
Set SUBSEP via the VariableManager.- Parameters:
value- new SUBSEP value
-
getCONVFMTVar
Get CONVFMT from the VariableManager.- Returns:
- CONVFMT value
-
getCONVFMTString
Returns the current CONVFMT value as a string.- Returns:
- current numeric conversion format
-
setCONVFMT
Set CONVFMT via the VariableManager.- Parameters:
value- new CONVFMT value
-
getOFMTString
Get OFMT from the VariableManager.- Returns:
- OFMT value
-
setOFMT
Set OFMT via the VariableManager.- Parameters:
value- new OFMT value
-
getARGCVar
Get ARGC from the VariableManager.- Returns:
- ARGC value
-
setARGC
Set ARGC via the VariableManager.- Parameters:
value- new ARGC value
-
setInputLine
Setter for the field
inputLine.- Parameters:
inputLine- aStringobject
-
assignInputLineFromGetline
Assigns$0from a getline result and initializes$1..$NF.- Parameters:
value- getline result assigned to$0
-
consumeInput
Attempt to consume one record from a structured input source and expose it as the current input record.- Parameters:
source- source strategy that provides records and optional pre-split fields- Returns:
trueif a record was consumed;falsewhen the source is exhausted- Throws:
IOException- if the source raises an I/O error
-
consumeInputToTarget
Attempt to consume one record from a structured input source forgetline target, returning only the input text and leaving the current input record state untouched.- Parameters:
source- source strategy that provides records and optional pre-split fields- Returns:
- the consumed input text, or
nullwhen the source is exhausted - Throws:
IOException- if the source raises an I/O error
-
consumeInputForEval
Consume at most one record from a structured source for expression evaluation.- Parameters:
source- source strategy that provides records and optional pre-split fields- Returns:
trueif a record was consumed,falseotherwise- Throws:
IOException- if the source raises an I/O error
-
jrtParseFields
public void jrtParseFields()Splits $0 into $1, $2, etc. Called when an update to $0 has occurred. -
hasInputFields
public boolean hasInputFields()- Returns:
- true if at least one input field has been initialized.
-
jrtSetNF
Adjust the current input field list and $0 when NF is updated by the AWK script. Fields are either truncated or extended with empty values so thatNFtruly reflects the number of fields.- Parameters:
nfObj- New value for NF
-
jrtGetInputField
Retrieve the contents of a particular input field.- Parameters:
fieldnumObj- Object referring to the field number.- Returns:
- Contents of the field.
-
jrtGetInputField
jrtGetInputField.
- Parameters:
fieldnum- a long- Returns:
- a
Objectobject
-
jrtSetInputField
Stores value_obj into an input field.- Parameters:
valueObj- The RHS of the assignment.fieldNum- field number to update.- Returns:
- A string representation of valueObj.
-
jrtConsumeFileInputForGetline
jrtConsumeFileInputForGetline.
-
jrtConsumeCommandInputForGetline
Retrieve the next line of output from a command, executing the command if necessary and store it to $0.- Parameters:
cmdString- The command to execute.- Returns:
- Integer(1) if successful, Integer(0) if no more input is available, Integer(-1) upon an IO error.
-
jrtGetInputString
Retrieve $0.- Returns:
- The contents of the $0 input field.
-
getOutputFiles
Getter for the field
outputFiles.- Returns:
- a
Mapobject
-
printDefault
Writes a standard AWKprintoperation to the default output.- Parameters:
values- values to print- Throws:
IOException- if the sink cannot be written to
-
printToFile
Writes a standard AWKprintoperation to a redirected file.- Parameters:
fileNameParam- target file nameappend- whether output should be appendedvalues- values to print; an empty array prints$0- Throws:
IOException- if the sink cannot be written to
-
printToProcess
Writes a standard AWKprintoperation to a redirected process.- Parameters:
cmd- command to executevalues- values to print; an empty array prints$0- Throws:
IOException- if the sink cannot be written to
-
printfDefault
Writes a formatted AWK output string to the specified sink.- Parameters:
format- format string passed toprintfvalues- values supplied after the format string- Throws:
IOException- if the sink cannot be written to
-
printfToFile
public void printfToFile(String fileNameParam, boolean append, String format, Object[] values) throws IOException Writes formatted AWK output to a redirected file.- Parameters:
fileNameParam- target file nameappend- whether output should be appendedformat- format string passed toprintfvalues- values supplied after the format string- Throws:
IOException- if the sink cannot be written to
-
printfToProcess
Writes formatted AWK output to a redirected process.- Parameters:
cmd- command to executeformat- format string passed toprintfvalues- values supplied after the format string- Throws:
IOException- if the sink cannot be written to
-
jrtGetPrintStream
Retrieve the PrintStream which writes to a particular file, creating the PrintStream if necessary.- Parameters:
fileNameParam- The file which to write the contents of the PrintStream.append- true to append to the file, false to overwrite the file.- Returns:
- a
PrintStreamobject
-
jrtConsumeFileInput
jrtConsumeFileInput.
- Parameters:
fileNameParam- aStringobject- Returns:
- a boolean
- Throws:
IOException- if any.
-
jrtConsumeCommandInput
jrtConsumeCommandInput.
- Parameters:
cmd- aStringobject- Returns:
- a boolean
- Throws:
IOException- if any.
-
jrtSpawnForOutput
Retrieve the PrintStream which shuttles data to stdin for a process, executing the process if necessary. Threads are created to shuttle the data to/from the process.- Parameters:
cmd- The command to execute.- Returns:
- The PrintStream which to write to provide input data to the process.
-
jrtClose
Attempt to close an open stream, whether it is an input file, output file, input process, or output process.The specification did not describe AWK behavior when attempting to close streams/processes with the same file/command name. In this case, all open streams with this name are closed.
- Parameters:
fileNameParam- The filename/command process to close.- Returns:
- Integer(0) upon a successful close, Integer(-1) otherwise.
-
jrtCloseAll
public void jrtCloseAll()jrtCloseAll.
-
jrtSystem
Executes the command specified by cmd and waits for termination, returning an Integer object containing the return code. stdin to this process is closed while threads are created to shuttle stdout and stderr of the command to stdout/stderr of the calling process.- Parameters:
cmd- The command to execute.- Returns:
- Integer(return_code) of the created process. Integer(-1) is returned on an IO error.
-
sprintfNoCatch
public static String sprintfNoCatch(Locale locale, String fmtArg, Object... arr) throws IllegalFormatException sprintfFunctionNoCatch.
- Parameters:
locale- aLocaleobjectfmtArg- aStringobjectarr- an array ofObjectobjects- Returns:
- a
Stringobject - Throws:
IllegalFormatException- if any.
-
printfNoCatch
printfFunctionNoCatch.
-
printfNoCatch
printfFunctionNoCatch.
- Parameters:
ps- aPrintStreamobjectlocale- aLocaleobjectfmtArg- aStringobjectarr- an array ofObjectobjects
-
substr
substr.
-
substr
substr.
-
timeSeed
public static int timeSeed()timeSeed.
- Returns:
- a int
-
newRandom
newRandom.
- Parameters:
seed- a int- Returns:
- a
Randomobject
-
applyRS
applyRS.
- Parameters:
rsObj- aObjectobject
-