Class JRT

java.lang.Object
org.metricshub.jawk.jrt.JRT
Direct Known Subclasses:
SandboxedJRT

public class JRT extends Object
The Jawk runtime coordinator. The JRT services interpreted and compiled Jawk scripts, mainly for IO and other non-CPU bound tasks. The goal is to house service functions into a Java-compiled class rather than to hand-craft service functions in byte-code, or cut-paste compiled JVM code into the compiled AWK script. Also, since these functions are non-CPU bound, the need for inlining is reduced.

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 org.metricshub.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 Details

    • JRT

      public JRT(VariableManager vm)
      Create a JRT with a VariableManager
      Parameters:
      vm - The VariableManager to use with this JRT.
  • Method Details

    • setStreams

      public void setStreams(PrintStream ps, PrintStream err)
      Sets the streams for spawned command output and error.
      Parameters:
      ps - PrintStream to send command output to
      err - PrintStream to send command error output to
    • assignInitialVariables

      public final void assignInitialVariables(Map<String,Object> initialVarMap)
      Assign all -v variables.
      Parameters:
      initialVarMap - A map containing all initial variable names and their values.
    • assignEnvironmentVariables

      public static void assignEnvironmentVariables(AssocArray aa)
      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.
    • toAwkString

      public static String toAwkString(Object o, String convfmt, Locale locale)
      Convert Strings, Integers, and Doubles to Strings based on the CONVFMT variable contents.
      Parameters:
      o - Object to convert.
      convfmt - The contents of the CONVFMT variable.
      locale - a Locale object
      Returns:
      A String representation of o.
    • toAwkStringForOutput

      public static String toAwkStringForOutput(Object o, String ofmt, Locale locale)
      Convert a String, Integer, or Double to String based on the OFMT variable contents. Jawk will subsequently use this String for output via print().
      Parameters:
      o - Object to convert.
      ofmt - The contents of the OFMT variable.
      locale - a Locale object
      Returns:
      A String representation of o.
    • toDouble

      public static double toDouble(Object o)
      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:
      true if d is effectively an integer
    • toLong

      public static long toLong(Object o)
      Convert a String, Long, or Double to Long.
      Parameters:
      o - Object to convert.
      Returns:
      the "long" value of o, or 0 if invalid
    • compare2

      public static boolean compare2(Object o1, Object o2, int mode)
      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

      public static Object inc(Object o)
      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

      public static Object dec(Object o)
      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

      public final boolean toBoolean(Object o)
      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
      If o is none of these types, an error is thrown.
    • split

      public static int split(Object array, Object string, String convfmt, Locale locale)
      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.
      convfmt - Contents of the CONVFMT variable.
      locale - a Locale object
      Returns:
      The number of parts resulting from this split operation.
    • split

      public static int split(Object fs, Object array, Object string, String convfmt, Locale locale)
      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:
      fs - Field separator regular expression.
      array - The array to populate.
      string - The string to split.
      convfmt - Contents of the CONVFMT variable.
      locale - a Locale object
      Returns:
      The number of parts resulting from this split operation.
    • getPartitioningReader

      public PartitioningReader getPartitioningReader()

      Getter for the field partitioningReader.

      Returns:
      a PartitioningReader object
    • getInputLine

      public String getInputLine()

      Getter for the field inputLine.

      Returns:
      a String object
    • setInputLine

      public void setInputLine(String inputLine)

      Setter for the field inputLine.

      Parameters:
      inputLine - a String object
    • consumeInput

      public boolean consumeInput(InputStream input, boolean forGetline, Locale locale) throws IOException
      Attempt to consume one line of input. Input may come from standard input or from files/variable assignments supplied on the command line via ARGV. Variable assignment arguments are evaluated lazily when encountered.
      Parameters:
      input - stream used when consuming from standard input
      forGetline - true if the call is for getline; when false the fields of $0 are parsed automatically
      locale - locale used for string conversion
      Returns:
      true if a line was consumed, false if no more input is available
      Throws:
      IOException - upon an IO error
    • setInputLineforEval

      public void setInputLineforEval(InputStream input) throws IOException
      Read input from stdin, only once, and just for simple AWK expression evaluation

      Parameters:
      input - Stdin
      Throws:
      IOException - if couldn't read stdin (should never happen, as it's based on a String)
    • 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

      public void jrtSetNF(Object nfObj)
      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 that NF truly reflects the number of fields.
      Parameters:
      nfObj - New value for NF
    • jrtGetInputField

      public Object jrtGetInputField(Object fieldnumObj)
      Retrieve the contents of a particular input field.
      Parameters:
      fieldnumObj - Object referring to the field number.
      Returns:
      Contents of the field.
    • jrtGetInputField

      public Object jrtGetInputField(int fieldnum)

      jrtGetInputField.

      Parameters:
      fieldnum - a int
      Returns:
      a Object object
    • jrtSetInputField

      public String jrtSetInputField(Object valueObj, int fieldNum)
      Stores value_obj into an input field.
      Parameters:
      valueObj - The RHS of the assignment.
      fieldNum - Object referring to the field number.
      Returns:
      A string representation of valueObj.
    • jrtConsumeFileInputForGetline

      public Integer jrtConsumeFileInputForGetline(String filename)

      jrtConsumeFileInputForGetline.

      Parameters:
      filename - a String object
      Returns:
      a Integer object
    • jrtConsumeCommandInputForGetline

      public Integer jrtConsumeCommandInputForGetline(String cmdString)
      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

      public String jrtGetInputString()
      Retrieve $0.
      Returns:
      The contents of the $0 input field.
    • getOutputFiles

      public Map<String,PrintStream> getOutputFiles()

      Getter for the field outputFiles.

      Returns:
      a Map object
    • jrtGetPrintStream

      public PrintStream jrtGetPrintStream(String filename, boolean append)
      Retrieve the PrintStream which writes to a particular file, creating the PrintStream if necessary.
      Parameters:
      filename - The file which to write the contents of the PrintStream.
      append - true to append to the file, false to overwrite the file.
      Returns:
      a PrintStream object
    • jrtConsumeFileInput

      public boolean jrtConsumeFileInput(String filename) throws IOException

      jrtConsumeFileInput.

      Parameters:
      filename - a String object
      Returns:
      a boolean
      Throws:
      IOException - if any.
    • jrtConsumeCommandInput

      public boolean jrtConsumeCommandInput(String cmd) throws IOException

      jrtConsumeCommandInput.

      Parameters:
      cmd - a String object
      Returns:
      a boolean
      Throws:
      IOException - if any.
    • jrtSpawnForOutput

      public PrintStream jrtSpawnForOutput(String cmd)
      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

      public Integer jrtClose(String filename)
      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:
      filename - The filename/command process to close.
      Returns:
      Integer(0) upon a successful close, Integer(-1) otherwise.
    • jrtCloseAll

      public void jrtCloseAll()

      jrtCloseAll.

    • jrtSystem

      public Integer jrtSystem(String cmd)
      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 - a Locale object
      fmtArg - a String object
      arr - an array of Object objects
      Returns:
      a String object
      Throws:
      IllegalFormatException - if any.
    • printfNoCatch

      public static void printfNoCatch(Locale locale, String fmtArg, Object... arr)

      printfFunctionNoCatch.

      Parameters:
      locale - a Locale object
      fmtArg - a String object
      arr - an array of Object objects
    • printfNoCatch

      public static void printfNoCatch(PrintStream ps, Locale locale, String fmtArg, Object... arr)

      printfFunctionNoCatch.

      Parameters:
      ps - a PrintStream object
      locale - a Locale object
      fmtArg - a String object
      arr - an array of Object objects
    • prepareReplacement

      public static String prepareReplacement(String awkRepl)
      Transform the sub/gsub replacement string from Awk syntax (with '&') to Java (with '$') so it can be used in Matcher.appendReplacement()

      Awk and Java don't use the same syntax for regex replace:

      • Awk uses & to refer to the matched string
      • Java uses $0, $g, or ${name} to refer to the corresponding match groups
      Parameters:
      awkRepl - the replace string passed in sub() and gsub()
      Returns:
      a string that can be used in Java's Matcher.appendReplacement()
    • replaceFirst

      public static Integer replaceFirst(String origValue, String repl, String ere, StringBuffer sb)

      replaceFirst.

      Parameters:
      origValue - a String object
      repl - a String object
      ere - a String object
      sb - a StringBuffer object
      Returns:
      a Integer object
    • replaceAll

      public static Integer replaceAll(String origValue, String repl, String ere, StringBuffer sb)
      Replace all occurrences of the regular expression with specified string
      Parameters:
      origValue - String where replace is done
      repl - Replacement string (with '&' for referring to matching string)
      ere - Regular expression
      sb - StringBuffer we will work on
      Returns:
      the number of replacements performed
    • substr

      public static String substr(Object startposObj, String str)

      substr.

      Parameters:
      startposObj - a Object object
      str - a String object
      Returns:
      a String object
    • substr

      public static String substr(Object sizeObj, Object startposObj, String str)

      substr.

      Parameters:
      sizeObj - a Object object
      startposObj - a Object object
      str - a String object
      Returns:
      a String object
    • timeSeed

      public static int timeSeed()

      timeSeed.

      Returns:
      a int
    • newRandom

      public static BSDRandom newRandom(int seed)

      newRandom.

      Parameters:
      seed - a int
      Returns:
      a Random object
    • applyRS

      public void applyRS(Object rsObj)

      applyRS.

      Parameters:
      rsObj - a Object object