Showing posts with label lisp. Show all posts
Showing posts with label lisp. Show all posts

Thursday, August 27, 2009

Writing a Clojure DSL for SQLUnit

Last week, at our monthly eBig Java SIG meeting, Anne Ogborne spoke to us about her experiences using Clojure as a Second Life programmer. In the course of the talk, some one asked her why and when a typical Java programmer would use Clojure - unfortunately, as expected, her answer and the ensuing discussion eventually devolved into a bit of a language flame fest.

As it turns out, I have been debating this question myself to decide whether learning Clojure was worth spending time on. Clojure is a dialect of Lisp, a general purpose programming language that runs on the JVM, and can access Java classes loaded in the JVM, so it can do whatever I can do with Java and/or Lisp. However, as someone who mainly does Java and is fairly happy with it, I do not see myself doing in Clojure things I can already do easily in Java (or Jython/Python).

However, I think there is (at least) one area that Clojure is fantastic for - as a language for writing DSLs. Pragmatic Java programmers typically write their DSLs as a XML or JSON dialect, using one of the many XML/JSON parsers available in the Java world. Some examples that come to mind are Ant's build.xml and Spring's applicationContext.xml. More adventurous ones (or those working in situations where XML/JSON is not an option) would use something like JavaCC or AntLR to build a language and its parser from scratch, for example the Lucene query language.

With Clojure, you can write your DSL as as extension of Clojure. So all you do is implement (in Clojure or Clojure/Java) the bits that are specific to your DSL - things like control flow and variable declaration, assignments, etc. can be left to Clojure. Because of Clojure's (and Lisp's) homoiconic nature, functions that you provide are represented the same as functions provided by Clojure. The DSL user would basically write the DSLs in a "dialect" of Clojure that includes these extra functions.

SQLUnit in Clojure

A few years ago, I built a little tool that allowed developers to unit test stored procedures. Tests were specified as a stored procedure call and expected results in an XML dialect (see here for an example), and the tool would execute the procedure, and match the result with the one provided. Different styles of matching were provided, such as exact equality, row count equality, failure, etc. However, because it grew organically as a result of user feedback, and because of my own lack of design foresight, it eventually became really complex, and began to suck up almost all my free time, so I handed the project off to someone else and moved on to more interesting things.

The first draft of my Clojure version of the XML example is shown below. If you compare the XML with this version, you will see that there is a 1:1 correspondence between the two files. However, this is written in a real programming language, meaning that the DSL user has much more flexibility. For example, if you now wanted to compare the results from the same stored procedures from two different databases (an actual request which required a change to SQLUnit), then you could simply define another Connection object and replace the fourth argument to run-test with another run-select instead of from-string.

  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
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
; Source: src/sqlunit/pgsql-test.clj
(ns sqlunit.pgsql-test
  (:import
    (java.sql Types)
  )
  (:use [sqlunit.core])
)

(defn main
  "This is the main test program that will be provided by the caller"
  []
  (def conn (
    connect-to-db "org.postgresql.Driver"
      "jdbc:postgresql://localhost:5432/sqlunitdb"
      "sujit" "")
  )
  (setup-suite conn (to-array [
    "delete from timecard where 1=1"
    "delete from employee where 1=1"
    "delete from department where 1=1"])
  )
  (run-test "Adding department HR"
    assert-results-equal?
    (run-select conn "select AddDept(?)"
      (struct sql-arg 1 "Human Resources" Types/VARCHAR :in))
    (from-string
      "[[{:idx 1 :name \"adddept\" :value \"$deptId_HR\"}]]")
  )
  (run-test "Adding department Infotech"
    assert-results-equal?
    (run-select conn "select AddDept(?)"
      (struct sql-arg 1 "Information Technology" Types/VARCHAR :in))
    (from-string
      "[[{:idx 1 :name \"adddept\" :value \"$deptId_IT\"}]]")
  )
  (run-test "Adding Employee John Doe to InfoTech"
    assert-results-equal?
    (run-select conn "select AddEmployee(?,?,?,?,?,?,?)"
      (struct sql-arg 1 "Information Technology" Types/VARCHAR :in)
      (struct sql-arg 2 "John Doe" Types/VARCHAR :in)
      (struct sql-arg 3 "1900-01-01" Types/DATE :in)
      (struct sql-arg 4 "123456789" Types/VARCHAR :in)
      (struct sql-arg 5 40.00 Types/NUMERIC :in)
      (struct sql-arg 6 10.00 Types/FLOAT :in)
      (struct sql-arg 7 20.00 Types/FLOAT :in))
    (from-string
      "[[{:idx 1 :name \"addemployee\" :value \"$empId_John\"}]]")
  )
  (run-test "Adding Employee John Doe again (expect exception)"
    assert-fail?
    (run-select conn "select AddEmployee(?,?,?,?,?,?,?)"
      (struct sql-arg 1 "Information Technology" Types/VARCHAR :in)
      (struct sql-arg 2 "John Doe" Types/VARCHAR :in)
      (struct sql-arg 3 "1900-01-01" Types/DATE :in)
      (struct sql-arg 4 "123456789" Types/VARCHAR :in)
      (struct sql-arg 5 40.00 Types/NUMERIC :in)
      (struct sql-arg 6 10.00 Types/FLOAT :in)
      (struct sql-arg 7 20.00 Types/FLOAT :in))
    (from-string "[[{}]]") ; we ignore this
  )
  (run-test "Adding Employee Jane Doe to HR"
    assert-results-equal?
    (run-select conn "select AddEmployee(?,?,?,?,?,?,?)"
      (struct sql-arg 1 "Human Resources" Types/VARCHAR :in)
      (struct sql-arg 2 "Jane Doe" Types/VARCHAR :in)
      (struct sql-arg 3 "1910-01-01" Types/DATE :in)
      (struct sql-arg 4 "143456789" Types/VARCHAR :in)
      (struct sql-arg 5 45.00 Types/NUMERIC :in)
      (struct sql-arg 6 10.0 Types/FLOAT :in)
      (struct sql-arg 7 20.0 Types/FLOAT :in))
    (from-string
      "[[{:idx 1 :name \"addemployee\" :value \"$empId_Jane\"}]]")
  )
  (run-test "Adding Employee Dick Tracy to InfoTech"
    assert-results-equal?
    (run-select conn "select AddEmployee(?,?,?,?,?,?,?)"
      (struct sql-arg 1 "Information Technology" Types/VARCHAR :in)
      (struct sql-arg 2 "Dick Tracy" Types/VARCHAR :in)
      (struct sql-arg 3 "1920-01-01" Types/DATE :in)
      (struct sql-arg 4 "144456789" Types/VARCHAR :in)
      (struct sql-arg 5 50.00 Types/NUMERIC :in)
      (struct sql-arg 6 10.0 Types/FLOAT :in)
      (struct sql-arg 7 20.0 Types/FLOAT :in))
    (from-string
      "[[{:idx 1 :name \"addemployee\" :value \"$empId_Dick\"}]]")
  )
  (run-test "Updating Hourly Rate for John"
    assert-results-equal?
    (run-select conn "select UpdateRate(?,?)"
      (struct sql-arg 1 "John Doe" Types/VARCHAR :in)
      (struct sql-arg 2 55.00 Types/NUMERIC :in))
    (from-string
      "[[{:idx 1 :name \"updaterate\" :value 40.00}]]")
  )
  (run-test "Looking up John Doe by name"
    assert-results-equal?
    (run-select conn "select * from GetEmployeeByName(?)"
      (struct sql-arg 1 "John Doe" Types/VARCHAR :in))
    (from-string
      "[[{:idx 1 :name \"emp_id\" :value \"$empId_John\"}
         {:idx 2 :name \"emp_name\" :value \"John Doe\"}
         {:idx 3 :name \"dept_name\" :value \"Information Technology\"}
         {:idx 4 :name \"emp_dob\" :value \"1900-01-01\"}
         {:idx 5 :name \"emp_ssn\" :value \"123456789\"}
         {:idx 6 :name \"rate_per_hour\" :value 55.00}]]")
  )
  (run-test "Looking up all employees in InfoTech"
    assert-results-equal?
    (run-select conn "select * from GetAllEmpForDept(?)"
      (struct sql-arg 1 "Information Technology" Types/VARCHAR :in))
    (from-string
      "[[{:idx 1 :name \"dept_id\" :value \"$deptId_IT\"}
         {:idx 2 :name \"emp_id\" :value \"$empId_John\"}
         {:idx 3 :name \"emp_name\" :value \"John Doe\"}
         {:idx 4 :name \"emp_dob\" :value \"1900-01-01\"}
         {:idx 5 :name \"emp_ssn\" :value \"123456789\"}
         {:idx 6 :name \"rate_per_hour\" :value 55.00}
         {:idx 7 :name \"location\" :value \"(10.0,20.0)\"}]
        [{:idx 1 :name \"dept_id\" :value \"$deptId_IT\"}
         {:idx 2 :name \"emp_id\" :value \"$empId_Dick\"}
         {:idx 3 :name \"emp_name\" :value \"Dick Tracy\"}
         {:idx 4 :name \"emp_dob\" :value \"1920-01-01\"}
         {:idx 5 :name \"emp_ssn\" :value \"144456789\"}
         {:idx 6 :name \"rate_per_hour\" :value 50.00}
         {:idx 7 :name \"location\" :value \"(10.0,20.0)\"}]]")
  )
  (run-test "Adding timecard for John"
    assert-results-equal?
    (run-select conn "select AddTimecard(?,?,?,?)"
      (struct sql-arg 1 "John Doe" Types/VARCHAR :in)
      (struct sql-arg 2 "2000-01-01" Types/DATE :in)
      (struct sql-arg 3 "09:00:00" Types/VARCHAR :in)
      (struct sql-arg 4 "17:00:00" Types/VARCHAR :in))
    (from-string
      "[[{:idx 1 :name \"addtimecard\" :value \"$empId_John\"}]]")
  )
  (run-test "Adding another timecard for John"
    assert-results-equal?
    (run-select conn "select AddTimecard(?,?,?,?)"
      (struct sql-arg 1 "John Doe" Types/VARCHAR :in)
      (struct sql-arg 2 "2000-01-02" Types/DATE :in)
      (struct sql-arg 3 "09:00:00" Types/VARCHAR :in)
      (struct sql-arg 4 "17:00:00" Types/VARCHAR :in))
    (from-string
      "[[{:idx 1 :name \"addtimecard\" :value \"$empId_John\"}]]")
  )
  (run-test "Adding timecard for Dick"
    assert-results-equal?
    (run-select conn "select AddTimecard(?,?,?,?)"
      (struct sql-arg 1 "Dick Tracy" Types/VARCHAR :in)
      (struct sql-arg 2 "2000-01-01" Types/DATE :in)
      (struct sql-arg 3 "10:00:00" Types/VARCHAR :in)
      (struct sql-arg 4 "23:00:00" Types/VARCHAR :in))
    (from-string
      "[[{:idx 1 :name \"addtimecard\" :value \"$empId_Dick\"}]]")
  )
  (run-test "Getting monthly report for InfoTech"
    assert-results-equal?
    (run-select conn "select * from GetMonthlyDeptReport(?,?,?)"
      (struct sql-arg 1 "Information Technology" Types/VARCHAR :in)
      (struct sql-arg 2 "2000-01-01" Types/DATE :in)
      (struct sql-arg 3 "2000-02-01" Types/DATE :in))
    (from-string
      "[[{:idx 1 :name \"dept_name\" :value \"Information Technology\"}
         {:idx 2 :name \"emp_name\" :value \"Dick Tracy\"}
         {:idx 3 :name \"hours_worked\" :value 13}
         {:idx 4 :name \"pay_rate\" :value 50.00}
         {:idx 5 :name \"total_pay\" :value 650.00}]
        [{:idx 1 :name \"dept_name\" :value \"Information Technology\"}
         {:idx 2 :name \"emp_name\" :value \"John Doe\"}
         {:idx 3 :name \"hours_worked\" :value 16}
         {:idx 4 :name \"pay_rate\" :value 55.00}
         {:idx 5 :name \"total_pay\" :value 880.00}]]")
  )
  (teardown-suite conn)
)

(main)

The core.clj file that is imported in the above code via the :use call is shown below. Ideally, this would be a small bit of Clojure glue code that would link up the test with some Java code, but I was trying to learn Clojure at this point, so I decided to do the whole thing in Clojure. I will try the Clojure/Java approach and write about at some point in the future. In any case, here is the Clojure code for a rudimentary version of SQLUnit.

  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
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
; Source: pgsql-test.clj
(ns sqlunit.core
  (:import
    (java.lang Class String)
    (java.sql DriverManager Connection Statement PreparedStatement
      ResultSet ResultSetMetaData Types SQLException)
  )
)

; Represents a stored procedure IN/OUT/INOUT parameter. The :idx
; is the (1-based) index, :value is the string or numeric value
; of the argument, :sqltype is the Types value and :paramtype is
; :in/:out/:inout.
(defstruct sql-arg :idx :value :sqltype :paramtype)
; Represents a single column in the database. The :idx is the
; (1-based) index, :name is the column name and :value is the
; value of the column. Note that only pure numeric values are
; left unquoted, all others are stringified and quoted.
(defstruct sql-col :idx :name :value)

; global variables
; symbol table
(def *syms* (ref {}))

(defn connect-to-db
  "Create and return a JDBC Connection using the DriverManager approach.
   Param: driver - the class name of the driver to use.
   Param: url - the JDBC url.
   Param: user - the user name.
   Param: password - the JDBC password.
   Return: a reference to a JDBC connection"
  [driver, url, user, password]
  (Class/forName driver)
  (def connection (DriverManager/getConnection url user password))
  connection
)

(defn get-metadata
  "Returns the metadata for the provided ResultSet object as a sequence
   of sql-arg data.
   Param: resultset - the resultset to examine.
   Return: the resultset metadata as a sequence of sql-args"
  [resultset]
  (def rsmd (.getMetaData resultset))
  (def colcount (.getColumnCount rsmd))
  (map #(struct sql-arg % (.getColumnName rsmd %) (.getColumnType rsmd %))
    (range 1 (inc colcount))
  )
)

(defn from-resultset
  "Converts a JDBC ResultSet object to the internal form, ie, a Sequence
   of Sequence of col structs.
   Param: resultset - the JDBC resultset.
   Return: A Seq of Seq of col structs."
  [resultset]
  (def resultmetas (get-metadata resultset))
  (def result [])
  (while (.next resultset)
    (def row [])
    (doseq [resultmeta resultmetas]
      (def col (struct sql-col
        (:idx resultmeta) (:value resultmeta)
        (String/valueOf (.getObject resultset (:idx resultmeta)))))
      (def row (conj row col))
    )
    (def result (conj result row))
  )
  result
)

(defn from-string
  "Converts a user-supplied raw result string to the internal form, ie,
   a Sequence of Sequence of col structs. Non-numeric values in
   the raw string should be quoted, otherwise this method will fail.
   Param: raw-string - the raw string.
   Return: the Seq of Seq of cols."
  [raw-string]
  (load-string raw-string)
)

(defn no-errors?
  "Return true if the current test already has an error, in which case
   calling code will typically short-circuit and return. The method just
   checks for the existence of the :message key in the global symbol table
   *syms*.
   Param: none
   Return: true or false"
  []
  (not (contains? (deref *syms*) :message))
)

(defn is-symbol?
  "Return true if the value is a symbol, ie, preceded by a $ sign.
   Param: value - the value to check.
   Return: true or false"
  [value]
  (.startsWith (str value) "$")
)

(defn assert-cols-equal?
  "Predicate that returns true if the string value of the columns are
   identical. Side effect is that if the LHS (col-1) value is a symbol,
   then the value is looked up from the symbol table. If the RHS (col-2)
   is a symbol, then the value is looked up from the LHS and the RHS
   and symbol table values updated with this value. Additionally, if
   the string values of the columns don't match after this, then an
   error message is written to the symbol table.
   Param: row-id - the row id of the column (0-based)
   Param: col-id - the column id of the column (0-based)
   Param: col-1 - the col struct representing the first column.
   Param: col-2 - the col struct representing the second column.
   Return: true or false"
  [row-id col-id col-1 col-2]
  (doseq [k (keys col-1)]
    ; if one of the values is a symbol, ie of the form $..., then we
    ; just replace one by the other
    (def col-value-1 (get col-1 k))
    (def col-value-2 (get col-2 k))
    (if (is-symbol? col-value-1)
      ; if the symbol is on the LHS, then check to see if it is defined
      ; in the symbol table
      (def col-value-1 (get *syms* col-value-1))
    )
    (if (is-symbol? col-value-2)
      ; if the symbol is on the RHS, then replace the symbol with the
      ; value on the LHS, and update the symbol table
      (do
        (dosync (alter *syms* assoc col-value-2 col-value-1))
        (def col-value-2 col-value-1)
      )
    )
    (def retval (and no-errors? (= (str col-value-1) (str col-value-2))))
    (if (not retval)
      (dosync (alter *syms* assoc :message (format
        "mismatch at (row,col):(%d,%d) for %s (%s != %s)"
        (inc row-id) (inc col-id) k col-value-1 col-value-2)))
    )
    retval
  )
)

(defn assert-rows-equal?
  "Predicate that compares two rows for equality. A row is a Seq of 
   col structs. The function iterates through the columns and
   delegates to the assert-cols-equal? predicate for each of
   them. If there is an error in the previous call, then the test is
   skipped. First checks for equality of number of rows, and if they
   are not equal, writes out the error message to the symbol table.
   Param: row-id - the row id (0-based).
   Param: row-1 - the LHS row Seq of cols.
   Param: row-2 - the RHS row Seq of cols.
   Return: true or false."
  [row-id row-1 row-2]
  (def count-1 (count row-1))
  (def count-2 (count row-2))
  (if (not (= count-1 count-2))
    (dosync (alter *syms* assoc :message (
      format "row count mismatch at row: %d (%d != %d)"
      (inc row-id) (count-1) (count-2)))
    )
  )
  (if no-errors?
    (dotimes [i count-1]
      ; although assert-cols-equal? produces a retval, there
      ; does not seem to be a way of breaking out on a condition, so we
      ; just let it do the full run, and then check for the no-error?
      ; side effect at the end.
      (assert-cols-equal? row-id i (get row-1 i) (get row-2 i))
    )
  )
  no-errors?
)

(defn assert-results-equal?
  "Predicate that compares two results for equality. A result is a Seq of
   rows. The function loops through the rows in the result and delegates
   to the assert-rows-equal? predicate. First checks for equality
   of results, if not equal, writes an error into the symbol table.
   Param: result-1 - the first result.
   Param: result-2 - the second result.
   Return: true or false."
  [result-1 result-2]
  (def count-1 (count result-1))
  (def count-2 (count result-2))
  (if (not (= count-1 count-2))
    (dosync (alter *syms* assoc :message (
      format "result count mismatch (%d != %d)"
      (count-1) (count-2))))
  )
  (if no-errors?
    (dotimes [i count-1]
      (assert-rows-equal? i (get result-1 i) (get result-2 i))
    )
  )
  no-errors?
)

(defn assert-fail?
  "Checks to see if a failure message was logged as a result of the
   run-select function going into the catch block because of an
   exception in running.
   Params: None
   Return: true or false"
  [& junk]
  (contains? (deref *syms*) :failure)
)

(defn run-select
  "Runs a SELECT SQL query. Returns the result, which is the JDBC
   resultset in internal form.
   Param: connection - the JDBC connection.
   Param: sql - the SQL to run.
   Param: & sql-arg - variable number of sql-arg structs.
   Return: result - the JDBC resultset converted to internal format."
  [connection sql & sql-args]
  (def ps (.prepareStatement connection sql))
  (doseq [sql-arg sql-args]
    (.setObject ps (:idx sql-arg) (:value sql-arg) (:sqltype sql-arg))
  )
  (try
    (do
      (def rs (.executeQuery ps))
      (def result (from-resultset rs))
      (.close rs)
      (.close ps)
      result
    )
    (catch SQLException e
      (dosync (alter *syms* assoc :failure (.getErrorCode e)))
    )
  )
)

(defn run-update
  "Runs a SQL INSERT/UPDATE query. This is used here when setting up
   the test, to remove artifacts of previous tests, for example.
   Param: connection - the JDBC connection.
   Param: sql - the INSERT/UPDATE SQL.
   Param: & sql-args - a variable number of sql-arg structs.
   Returns: none"
  [connection sql & sql-args]
  (def ps (.prepareStatement connection sql))
  (doseq [sql-arg sql-args]
    (.setObject ps (:idx sql-arg) (:value sql-arg) (:sqltype sql-arg))
  )
  (.executeUpdate ps)
  (.close ps)
)

(defn setup-suite
  "Run setup commands (SQL UPDATE/INSERT) commands in preparation
   for running a suite of tests.
   Param: connection - the JDBC connection
   Param: sqls a Seq of SQL UPDATE/INSERT calls.
   Return: None."
  [connection sqls]
  (doseq [sql sqls]
    (run-update connection sql)
  )
)

(defn teardown-suite
  "Run teardown commands (usually closing connection, etc) once the
   suite of tests are completed.
   Param: connection - the JDBC connection.
   Return: None."
  [connection]
  (.close connection)
)

(defn run-test
  "The test function is a super-function which the caller calls to
   run the test.
   Param: test-name - the name of the test.
   Param: assertion - the assertion to check.
   Param: result-1 - the LHS result.
   Param: result-2 - the RHS result.
   Return: None."
  [test-name assertion result-1 result-2]
  (print "Running Test:" test-name)
  (def retval (apply assertion [result-1 result-2]))
  (dosync
    (alter *syms* dissoc :message)
    (alter *syms* dissoc :failure)
  )
  (def test-result
    (if retval "Ok"
      (format "Failed\n..Message: %s" (*syms* :message))
  ))
  (println "..." test-result)
)

The indentation may look a bit funky to experienced Lisp/Clojure programmers, but I come from a Java/Python background, and it helps if I line up the parenthesis like I have above, as well as make the introduction and removal of debugging (println "foo") calls less invasive.

Running this test in the REPL produces the following output, which is similar to what SQLUnit returns as well:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
user=> 
Running Test: Adding department HR... Ok
Running Test: Adding department Infotech... Ok
Running Test: Adding Employee John Doe to InfoTech... Ok
Running Test: Adding Employee John Doe again (expect exception)... Ok
Running Test: Adding Employee Jane Doe to HR... Ok
Running Test: Adding Employee Dick Tracy to InfoTech... Ok
Running Test: Updating Hourly Rate for John... Ok
Running Test: Looking up John Doe by name... Ok
Running Test: Looking up all employees in InfoTech... Ok
Running Test: Adding timecard for John... Ok
Running Test: Adding another timecard for John... Ok
Running Test: Adding timecard for Dick... Ok
Running Test: Getting monthly report for InfoTech... Ok
nil
user=> 

Conclusions

People (including yours truly in the past) often complain about Lisp's prefix notation and all the parenthesis, but I think thats just a function of usage. It took me approximately 4 (4-6 hours per day) days to write the code in this post, and that was starting with zero knowledge of Clojure. Stuart Holloway's Programming Clojure book helped a lot, as did the four part Clojure tutorial (parts 1, 2, 3 and 4) by the author of the Occasionally sane blog. But as a result of this, I now find Clojure code almost as easy to read as Java or Python code.

The point I am trying to make is that you may get pushback along similar lines from the DSL user, but if you point out to him that (a) the problem is temporary and will go away in 3-4 days, (b) the Clojure code is not much different from the XML version, and (c) that he is programming in a real language, so he does not have to depend on you for every little change, he will probably buy into the idea as well. As a DSL writer, you can concentrate on coding only the actual behavior and thus be more productive. I believe that this alone may be a compelling reason for a Java programmer to learn Clojure.

Other information

I used the Netbeans IDE with the enclojure plugin to write the code. Along with the standard paren-matching and syntax highlighting, enclojure offers a built in REPL which is very convenient - I use the Emacs key-binding, so to run the code within the built-in REPL, the keystroke is ALT+L (not CTRL+L as advertised, perhaps for the default key-binding, on the enclojure docs).

I also had a bit of re-learning to do when setting up PostgreSQL for the test. Last I used it was over 3 years (and 1 machine) ago, so I had to install everything from scratch. Here is a quick cheat sheet if you want to do something similar.

  1. Install PostgreSQL: I used yum to install postgresql, postgresql-libs and postgresql-server. This automatically creates a Unix user called "postgres".
  2. Start the server: Run "sudo /etc/init.d/postgresql restart" from the unix prompt. The first time it will ask you to set up the cluster - do that and retry the command. On my machine, the cluster is created under /var/lib/pgsql/data. Note this directory, you will need it later.
  3. Create database: As postgres, run "createdb sqlunit" from the unix prompt. This will create your database.
  4. Create user: As postgres, run "createuser sujit" from the unix prompt. When prompted, give it PostgresSQL super-user privileges.
  5. Create language: Allow sqlunitdb to use plpgsql as a stored procedure language. As postgres, run "createlang plpgsql sqlunitdb" from the unix prompt.
  6. Load schema and procedures: There is a reload.sh that would do this for you. You will have to edit out the "drop table" calls the first time you use it.
  7. Enable JDBC access: You need to add the line in pg_hba.conf (in your /var/lib/pgsql/data directory) as described in the PostgreSQL JDBC FAQ here. The update to postgres.conf described here did not work and turned out to be unnecessary for me. Restart the server after updating pg_hba.conf.

Sunday, April 20, 2008

Learning to LISP

This is my third attempt at learning LISP. My first attempt was at college as part of my Artificial Intelligence elective course. While I gained enough competence in the language to pass the test, I did not particularly like it, and since I never had to use it after that, I soon forgot about it. My second attempt was a few years ago, fueled by comments on the blogosphere touting its advantages as a great tool for functional programming. Even though I did not have a good use case for it, I felt it was worth learning, if only to open my mind to think in terms of functional programming rather than in pure OO terms. I also came across the free e-book on Practical Common Lisp by Peter Siebel on the Internet, and I liked the book so much I bought myself a paper copy. I did attempt to make my way through the book, trying out the examples on a trial copy of Allegro-CL, but other things came up, so I gave up.

This time around, I did have something of a use-case for learning LISP. My plan was to have LISP scripts associated with workflow actions (see my last post), which would be sent over to the JMS server to be executed. In retrospect, though, I think I could probably have used Jython or Javascript to do the same thing more elegantly with less code. However, its here as a placeholder, in case I want to come back to it later.

I must admit that while I am in total awe of people who actually manage to write applications in LISP, I still don't like the LISP syntax that well. Or more likely I just don't get it, and the dislike could just be a function of unfamiliarity. However, what I do get is:

  • In LISP, code == data, much more so than in other languages.
  • LISP is probably the most parser-friendly language on the planet.
  • It is possible to extend LISP with custom functions and operations using defmacro, in ways not possible in C/C++ or Java.

Anyway, I started to look for a LISP interpreter that I could embed into my Java code and send it LISP scriptlets to execute. I chose JLisp initially, but soon realized I could not code LISP to save my life, so I had to stop and learn some LISP before I started up again.

To start off learning some basic LISP so you can start working with it, I strongly recommend the CUSP, a LISP plugin for Eclipse from Bitfauna. It comes integrated with SBCL, but I was not able to make SBCL work, so I downloaded clisp and used CUSP as a simple LISP editor, testing out my code on a terminal with clisp. I worked through about the first 10 chapters of Peter Siebel's book to get a basic understanding of LISP.

I also looked at Jatha while I was looking at JLisp, and while Jatha is probably the more mature of the two, JLisp seemed to be more suitable for what I was trying to do. For the example, I created a simple LISP "library" function closexec that will take a LISP program of this form:

1
2
(import com.mycompany.myapp.lisp.ext.closexec)
(closexec (setf x 1) (setf y 2) com.mycompany.myapp.lisp.Foo)

And then instantiate the Java class, set the variables, and call execute on it. Something like this:

1
2
3
4
5
Foo = new Foo();
foo.setX(1);
foo.setY(2);
foo.execute();
return foo.getResult();

To do this, I had to create a Library implementation called closexec (note the lowercase class name, this is a JLisp convention for Java based library extensions). Here is the code:

 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
72
73
// closexec.java
package com.mycompany.myapp.lisp.ext;

import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.Map;

import net.thinksquared.jlisp.Library;
import net.thinksquared.jlisp.Lisp;
import net.thinksquared.jlisp.Sexp;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.MethodUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class closexec implements Library {

  private final Log log = LogFactory.getLog(getClass());
  
  private Sexp CLOSEXEC;
  
  /**
   * @see net.thinksquared.jlisp.Library#apply(net.thinksquared.jlisp.Sexp, net.thinksquared.jlisp.Sexp)
   */
  public Sexp apply(Sexp function, Sexp args) {
    int result = 0;
    if (function.equals(CLOSEXEC)) {
      String className = null;
      Map<String,String> properties = new LinkedHashMap<String,String>(); 
      for (;;) {
        Sexp head = args.head;
        if (head.equals(args)) {
          // nothing more to extract from list
          break;
        }
        if (! head.at) {
          // not an atom, stack the setters
          Sexp name = head.head.tail.head;
          Sexp value = head.head.tail.tail.head;
          String nameVal = name.pname;
          String valueVal = (value.nmb ? value.pname : value.nval.toString());
          properties.put(nameVal, valueVal);
        } else {
          className = head.toS();
        }
        args = args.tail;
      }
      // now instantiate and run the class
      try {
        Object obj = Class.forName(className).newInstance();
        for (String var : properties.keySet()) {
          BeanUtils.setProperty(obj, var, (String) properties.get(var)); 
        }
        MethodUtils.invokeExactMethod(obj, "execute", null);
        result = Integer.valueOf(BeanUtils.getProperty(obj, "result"));
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
    Lisp lisp = new Lisp();
    return lisp.atom(new BigDecimal(result));
  }

  /**
   * @see net.thinksquared.jlisp.Library#register(java.util.Map, net.thinksquared.jlisp.Lisp)
   */
  @SuppressWarnings("unchecked")
  public void register(Map registry, Lisp lisp) {
    CLOSEXEC = lisp.atom("closexec");
    registry.put(CLOSEXEC, this);
  }
}

And here is the JUnit test to run this code:

 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
// LispRunnerTest.java
package com.mycompany.myapp.lisp;

import net.thinksquared.jlisp.Lisp;
import net.thinksquared.jlisp.LispThread;
import net.thinksquared.jlisp.Sexp;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;

public class LispRunnerTest {

  private final Log log = LogFactory.getLog(getClass());
  
  private final String prog = 
    "(import com.mycompany.myapp.lisp.ext.closexec) " +
    "(closexec (setf x 1) (setf y 2) com.mycompany.myapp.lisp.Foo)";
  
  @Test
  public void testRunning() throws Exception {
    Lisp lisp = new Lisp();
    Sexp progSexp = new Sexp(prog);
    if (progSexp.bad()) {
      log.error("Lisp code is not well-formed, please check");
    }
    Sexp[] sexps = lisp.execute(prog);
    // first sexp is the import
    log.debug("result=" + sexps[1].toS());
  }
}

And here is the class that is going to be manipulated. Its deliberately kept very simple, since this is just a test.

 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
// Foo.java
package com.mycompany.myapp.lisp;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Foo {

  private final Log log = LogFactory.getLog(getClass());
  
  private int x;
  private int y;

  private int result;
  
  public void setX(String x) {
    this.x = Integer.valueOf(x);
  }
  
  public void setY(String y) {
    this.y = Integer.valueOf(y);
  }
  
  public int getResult() {
    return result;
  }

  public void execute() {
    log.debug("Executing:" + getClass().getName());
    result = x + y;
  }
}

And the output of running the test looks like this:

1
2
Executing:com.healthline.gyncms.lisp.Foo
result=3

Anyway, as mentioned before, I don't plan on using this. All I need to do is pass in plain text scripts to a remote script runner, which I can do with less effort and with greater elegance with scripting languages that have a tighter integration with Java. With these languages, it is possible to instantiate, set and execute the object directly instead of passing it through the lisp interpreter and executing it with my own code. However, it's another way of doing it, even though it may not be the most optimal.

Saturday, March 17, 2007

Scriptable Java Closures

This mini-project was inspired by another recent project where we had to deliver a fairly complex data set as flat files. The specifications were quite simple to start with, so I started writing it as a single Java class, but then began to morph very rapidly, so before you knew it, the one class had begun to look pretty hairy. Another person joined me on the project, and both of us began to work on different sections of the same file, which brought up more complications with CVS merging and refactoring. He mentioned in passing that his preferred approach was the Unix utility approach, i.e. little Java classes that did specific things rather than the monolithic approach I had set up. This set me thinking, and since I didn't particularly like what I had set up myself, once the initial dataset was created, modifications to it were done with little one-off Java classes. While this approach worked well, the disadvantage was that you are soon inundated with little classes, and you need to remember what each class does and how and when to use it, and what classes to keep and what to throw away. To manage the complexity, I thought it may be good to take the Unix utility analogy one step further, and have some way to link these little classes using some sort of scripting language.

I looked around the internet for scripting languages that could link up one or more Java classes, but found none that fit my needs, so I rolled my own. This post describes a system to parse a LISP like scripting language that I call SCLOS, that can be used to set up and execute chains of Closure objects. SCLOS also provides control-flow using standard Predicate implementations in the Jakarta commons-collections package..

What I needed was a simple way to create a structure of Closure and Predicate implementation outside of Java code, and I needed a simple way of passing in data to this structure. Both Closure and Predicate take an Object argument in their execute() and evaluate() methods, and I usually pass in a DynaBean and let these methods extract what they need from it. Since we are now working with a chain of Closures and Predicates, I needed the parser to also be able to introspect these Closures and tell me what parameters are needed. A side effect of this approach is that now we need only a single shell script to run the Java class, not a script per class.

Providing Life cycle awareness

To allow the Closures and Predicates to report on what parameters they needed to function or what they would set as a result of execution, I set up two Strategy implementations of Predicate and Closure, the LifecycleAwarePredicate and LifecycleAwareClosure, which act as Decorators to our user-defined Predicate and Closure implementations. All these do is to enforce that the actual class of Object being passed in is a DynaBean, then execute all setPropXXX() methods on the target Closure or Predicate to populate it from the DynaBean, run the underlying method, then execute all the getPropXXX() methods on the target Predicate or Closure to populate the DynaBean. The code is shown below:

  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
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
// LifecycleAwareClosure.java
public class LifecycleAwareClosure implements Closure {

  private Closure closure;

  public LifecycleAwareClosure(Closure closure) {
    this.closure = closure;
  }

  public Closure getClosure() {
    return closure;
  }

  public void execute(Object obj) {
    if (!(obj instanceof DynaBean)) {
      throw new RuntimeException("Passed in object must be a DynaBean");
    }
    try {
      DynaBean dynaBean = (DynaBean) obj;
      LifecycleUtils.invokeAllSetters(closure, dynaBean);
      closure.execute(dynaBean);
      LifecycleUtils.invokeAllGetters(closure, dynaBean);
    } catch (Exception e) {
      throw new RuntimeException(e.getMessage(), e);
    }
  }
}

// LifecycleAwarePredicate.java
public class LifecycleAwarePredicate implements Predicate {

  private Predicate predicate;

  public LifecycleAwarePredicate(Predicate predicate) {
    this.predicate = predicate;
  }

  public Predicate getPredicate() {
    return this.predicate;
  }

  public boolean evaluate(Object obj) {
    if (!(obj instanceof DynaBean)) {
      throw new RuntimeException("Passed in object must be a DynaBean");
    }
    try {
      DynaBean dynaBean = (DynaBean) obj;
      LifecycleUtils.invokeAllSetters(predicate, dynaBean);
      boolean result = predicate.evaluate(dynaBean);
      LifecycleUtils.invokeAllGetters(predicate, dynaBean);
      return result;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}

// LifecycleUtils.java
public class LifecycleUtils {

  public static void invokeAllSetters(Object obj, DynaBean dynabean) throws Exception {
    List<Method> setters = LifecycleUtils.getAllSetters(obj);
    for (Method setter : setters) {
      setter.invoke(obj, new Object[] {dynabean.get(getVarName(setter))});
    }
  }

  public static void invokeAllGetters(Object obj, DynaBean dynabean) throws Exception {
    List<Method> getters = LifecycleUtils.getAllGetters(obj);
    for (Method getter : getters) {
      dynabean.set(getVarName(getter), getter.invoke(obj, new Object[0]));
    }
  }

  public static List<Method> getAllSetters(Object obj) {
    return LifecycleUtils.getAllMethodsStartingWith(obj, "setProp");
  }

  public static List<Method> getAllGetters(Object obj) {
    return LifecycleUtils.getAllMethodsStartingWith(obj, "getProp");
  }

  public static List<String> getAllSettableVars(Object obj) {
    List<Method> setters = LifecycleUtils.getAllSetters(obj);
    List<String> settableVars = new ArrayList<String>();
    for (Method setter : setters) {
      settableVars.add(LifecycleUtils.getVarName(setter));
    }
    return settableVars;
  }

  private static List<Method> getAllMethodsStartingWith(Object obj, String prefix) {
    List<Method> setters = new ArrayList<Method>();
    Class clazz = obj.getClass();
    Method[] methods = clazz.getDeclaredMethods();
    for (Method method : methods) {
      if (method.getName().startsWith(prefix)) {
        setters.add(method);
      }
    }
    return setters;
  }

  private static String getVarName(Method method) {
    return StringUtils.uncapitalize(method.getName().substring(7));
  }
}

A user-defined Predicate or Closure implementation just implements Predicate or Closure, provides a default constructor, a set of setPropXXX() methods that will set its member variables from the DynaBean, and a set of getPropXXX() methods that will populate the DynaBean from the member variables. The script parser will decorate these user-defined Predicates or Closures with their corresponding Lifecycle aware decorator.

The script parser

The script parser parses a LISP style script that defines a Closure chain (see the Usage example below) and converts it to a Java Closure chain, then runs it. It defines keywords based on a number of standard Predicate and Closure implementations available in commons-collections and builds them from the LISP forms in the script. One of the nicest things about LISP is how close its syntax is to the actual parse tree. In fact, this contributed significantly to the simplicity of the parser. Here are the keywords and their corresponding implementations, and links to their Javadocs.

Keyword Example Implementation
AND (AND Predicate1 Predicate2) AndPredicate
ANY (ANY Predicate1 ...) AnyPredicate
CHAIN (CHAIN Closure1 ...) ChainedClosure
FOR (FOR number Closure) ForClosure
IF (IF Predicate TrueClosure FalseClosure) IfClosure
NOT (NOT Predicate) NotPredicate
OR (OR Predicate1 Predicate2) OrPredicate
SWITCH (SWITCH Predicate... Closure... DefaultClosure) SwitchClosure
WHILE (WHILE Predicate Closure) WhileClosure
DO-WHILE (DO-WHILE Predicate Closure) WhileClosure
  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
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
// ScriptParser.java
public class ScriptParser {

  private Set<String> argumentSet = new HashSet<String>();

  private class OneOrMorePredicate implements Predicate {
    public boolean evaluate(Object object) {
      Integer argc = (Integer) object;
      return (argc > 0);
    }
  };

  private class OddPredicate implements Predicate {
    public boolean evaluate(Object object) {
      Integer argc = (Integer) object;
      return (argc %2 != 0);
    }
  }

  public ScriptParser() {
    super();
  }

  public Closure parse(String scriptFileName) throws Exception {
    argumentSet.clear();
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(scriptFileName)));
    StringBuilder scriptBuilder = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      if (line.startsWith(";")) {
        continue;
      }
      scriptBuilder.append(line).append(" ");
    }
    reader.close();
    StringTokenizer tokenizer = new StringTokenizer(scriptBuilder.toString(), "() ", true);
    Closure closure = (Closure) parseRecursive(tokenizer, 0);
    return closure;
  }

  /**
   * Populates a Set of settable variables for the user-defined Closures and
   * Predicates as a side effect of the parsing. A call to parse() will reset
   * this set, so it must be used immediately after the parse() is called.
   * @return a Set of settable variables for the pipeline.
   */
  public Set<String> getAllSettableVars() {
    return argumentSet;
  }

  private Object parseRecursive(StringTokenizer tokenizer, int depth) throws Exception {
    List<Object> list = new ArrayList<Object>();
    while (tokenizer.hasMoreTokens()) {
      String token = tokenizer.nextToken();
      if ("(".equals(token)) {
        // descend
        Object obj = parseRecursive(tokenizer, depth + 1);
        if (depth == 0) {
          return obj;
        }
        list.add(obj);
      } else if (")".equals(token)) {
        // return
        return buildClosureOrPredicate(list);
      } else if (StringUtils.isBlank(token)) {
        // skip whitespace
        continue;
      } else {
        // accumulate tokens into list
        list.add(token);
      }
    }
    if (depth != 0) {
      throw new Exception("Parsing error, possibly unbalanced parenthesis");
    }
    return buildClosureOrPredicate(list);
  }

  /**
   * Builds a specific Predicate or Closure implementation based on the command
   * and the arguments. Performs some amount of validation.
   * @param list the list representing the S-expression.
   * @return a Closure or Predicate implementation instance.
   * @throws Exception if there are problems with validation.
   */
  private Object buildClosureOrPredicate(List<Object> list) throws Exception {
    try {
      String command = (String) list.get(0);
      List<Object> args = list.subList(1, list.size());
      int argc = args.size();
      if ("CHAIN".equals(command)) {
        assertArgCount(argc, new OneOrMorePredicate(), "CHAIN needs one or more arguments");
        LifecycleAwareClosure[] closures = new LifecycleAwareClosure[argc];
        for (int i = 0; i < argc; i++) {
          closures[i] = getClosure(args.get(i), command, i);
        }
        return new ChainedClosure(closures);
      } else if ("FOR".equals(command)) {
        assertArgCount(args.size(), new EqualPredicate(2), "FOR must have exactly 2 arguments");
        int count = 0;
        if (args.get(0) instanceof String) {
          try {
            count = Integer.parseInt((String) args.get(0));
          } catch (NumberFormatException e) {
            throw new Exception("FOR argument[0] must be an Integer");
          }
        } else {
          throw new Exception("FOR argument[0] must be an Integer");
        }
        LifecycleAwareClosure closure = getClosure(args.get(1), command, 1);
        return new ForClosure(count, closure);
      } else if ("IF".equals(command)) {
        assertArgCount(args.size(), new EqualPredicate(3), "IF must have exactly 3 arguments");
        LifecycleAwarePredicate predicate = getPredicate(args.get(0), command, 0);
        LifecycleAwareClosure trueClosure = getClosure(args.get(1), command, 1);        LifecycleAwareClosure falseClosure = getClosure(args.get(2), command, 2);
        return new IfClosure(predicate, trueClosure, falseClosure);
      } else if ("WHILE".equals(command) || "DO-WHILE".equals(command)) {
        assertArgCount(args.size(), new EqualPredicate(2), command + " must have exactly 2 arguments");
        LifecycleAwarePredicate predicate = getPredicate(args.get(0), command, 0);
        LifecycleAwareClosure closure = getClosure(args.get(1), command, 1);
        boolean isDoWhile = "DO-WHILE".equals(command);
        return new WhileClosure(predicate, closure, isDoWhile);
      } else if ("SWITCH".equals(command)) {
        assertArgCount(args.size(), new OddPredicate(), "An n-way SWITCH must have exactly 2n+1 arguments");
        int n = (argc - 1) / 2;
        LifecycleAwarePredicate[] predicates = new LifecycleAwarePredicate[n];
        for (int i = 0; i < n; i++) {
          predicates[i] = getPredicate(args.get(i), command, i);
        }
        LifecycleAwareClosure[] closures = new LifecycleAwareClosure[n];
        for (int i = 0; i < n; i++) {
          closures[i] = getClosure(args.get(i + n), command, (i + n));
        }
        LifecycleAwareClosure defaultClosure = getClosure(args.get(argc - 1), command, (argc - 1));
        return new SwitchClosure(predicates, closures, defaultClosure);
      } else if ("AND".equals(command)) {
        assertArgCount(args.size(), new EqualPredicate(2), "AND must have exactly 2 arguments");
        LifecycleAwarePredicate[] predicates = new LifecycleAwarePredicate[2];
        for (int i = 0; i < 2; i++) {
          predicates[i] = getPredicate(args.get(i), command, i);
        }
        return new AndPredicate(predicates[0], predicates[1]);
      } else if ("OR".equals(command)) {
        assertArgCount(args.size(), new EqualPredicate(2), "OR must have exactly two arguments");
        LifecycleAwarePredicate[] predicates = new LifecycleAwarePredicate[2];
        for (int i = 0; i < 2; i++) {
          predicates[i] = getPredicate(args.get(i), command, i);
        }
        return new OrPredicate(predicates[0], predicates[1]);
      } else if ("NOT".equals(command)) {
        assertArgCount(args.size(), new EqualPredicate(1), "NOT must have exactly one argument");
        LifecycleAwarePredicate predicate = getPredicate(args.get(0), command, 0);
        return new NotPredicate(predicate);
      } else if ("ANY".equals(command)) {
        assertArgCount(args.size(), new OneOrMorePredicate(), "ANY must have one or more arguments");
        LifecycleAwarePredicate[] predicates = new LifecycleAwarePredicate[argc];
        for (int i = 0; i < argc; i++) {
          predicates[i] = getPredicate(args.get(i), command, i);
        }
        return new AnyPredicate(predicates);
      } else if ("ALL".equals(command)) {
        assertArgCount(args.size(), new OneOrMorePredicate(), "ALL must have one or more arguments");
        LifecycleAwarePredicate[] predicates = new LifecycleAwarePredicate[args.size()];
        for (int i = 0; i < predicates.length; i++) {
          predicates[i] = getPredicate(args.get(i), command, i);
        }
        return new AnyPredicate(predicates);
      } else {
        throw new Exception("Invalid keyword: " + command);
      }
    } catch (Exception e) {
      throw new Exception("Problem building closure from (" +
        StringUtils.join(list.iterator(), ' ') + ")", e);
    }
  }

  private Object resolveBeanName(String beanName) throws Exception {
    Object bean = null;
    if (beanName.indexOf(':') > -1) {
      String[] pair = StringUtils.split(beanName, ':');
      IBeanResolver beanResolver = BeanResolverFactory.getBeanResolver(pair[0]);      if (beanResolver == null) {
        throw new Exception("No resolver available for context:" + pair[0]);
      }
      bean = beanResolver.getBean(pair[1]);
    } else {
      IBeanResolver beanResolver = new DefaultBeanResolver(null);
      bean = beanResolver.getBean(beanName);
    }
    if (bean == null) {
      throw new Exception("Bean " + beanName + " not found");
    }
    return bean;
  }

  /**
   * Evaluate the actual size against the predicate and if the evaluation
   * returns false, throw an exception.
   * @param argc the number of arguments.
   * @param predicate the Predicate object to evaluate against.
   * @param message the Exception message to throw if evaluation fails.
   * @throws Exception if the evaluation fails.
   */
  private void assertArgCount(int argc, Predicate predicate, String message)
      throws Exception {
    if (! predicate.evaluate(new Integer(argc))) {
      throw new Exception(message);
    }
  }

  private LifecycleAwareClosure getClosure(Object obj, String command, int argPosition)
      throws Exception {
    Closure containedClosure = null;
    if (obj instanceof String) {
      containedClosure = (Closure) resolveBeanName((String) obj);
    } else if (obj instanceof Closure) {
      containedClosure = (Closure) obj;
    } else {
      throw new Exception(command + " argument[" + argPosition + "] must be a Closure");
    }
    argumentSet.addAll(LifecycleUtils.getAllSettableVars(containedClosure));
    LifecycleAwareClosure closure = new LifecycleAwareClosure(containedClosure);    return closure;
  }

  private LifecycleAwarePredicate getPredicate(Object obj, String command, int argPosition)
      throws Exception {
    Predicate containedPredicate = null;
    if (obj instanceof String) {
      containedPredicate = (Predicate) resolveBeanName((String) obj);
    } else if (obj instanceof Predicate) {
      containedPredicate = new LifecycleAwarePredicate((Predicate) obj);
    } else {
      throw new Exception(command + " argument[" + argPosition + "] must be a Predicate");
    }
    argumentSet.addAll(LifecycleUtils.getAllSettableVars(containedPredicate));
    LifecycleAwarePredicate predicate = new LifecycleAwarePredicate(containedPredicate);
    return predicate;
  }
}

Pluggable bean resolvers

As you will notice in the code for the Script Parser above, the resolveBeanName(String name) is responsible for instantiating the bean instance named in the script. The first implementation uses reflection to instantiate an instance of the named class. However, I use Spring in my command line code as well, so I thought it would be a good idea to allow a client to plug in the required bean factory implementation. Spring beans can be particularly useful if you wanted one of your Closures to be pre-instantiated with a connection to the database, for example. In order to signal to the parser that an bean resolver implementation other than the default is being used, the beans need to have a prefix (such as spring:myBean) which needs to be declared in the BeanResolverFactory. Multiple implementations can be used in the same script as long as they are suitably initialized from the CLI.

Here is the code for the IBeanResolver interface, the BeanResolverFactory, and the default (reflection based) and Spring based implementations of IBeanResolver.

 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
72
73
// IBeanResolver.java
public interface IBeanResolver {
  public Object getBean(String name) throws Exception;
}

// BeanResolverFactory.java
public class BeanResolverFactory {

  private final static String[][] RESOLVER_CLASSES_DATA = {
    {"spring", "com.healthline.sclos.SpringBeanResolver"},
  };

  private static Map<String,IBeanResolver> RESOLVERS = new HashMap<String,IBeanResolver>();

  static {
    RESOLVERS.put("default", new DefaultBeanResolver(null));
  }

  /**
   * Returns a bean resolver for the bean type, or null if there is none.
   * @param string the string to signal which resolver to use.
   * @return an instance of the Bean resolver.
   */
  public static IBeanResolver getBeanResolver(String string) throws Exception {
    return RESOLVERS.get(string);
  }

  /**
   * Should be called from the CLI handler module to initialize the bean
   * resolver factory from command line parameters.
   * @param contextMap the context map to use.
   * @throws Exception if one is thrown.
   */
  public static void initialize(Map<String,String[]> contextMap) throws Exception {
    for (String[] resolverClassData : RESOLVER_CLASSES_DATA) {
      String[] contexts = contextMap.get(resolverClassData[0]);
      if (contexts == null || contexts.length == 0) {
        continue;
      }
      RESOLVERS.put(resolverClassData[0],
        (IBeanResolver) Class.forName(resolverClassData[1]).
        getConstructor(new Class[] {Object[].class}).
        newInstance(new Object[] {contexts}));
    }
  }
}

// DefaultBeanResolver.java
public class DefaultBeanResolver implements IBeanResolver {

  private static final Logger LOGGER = Logger.getLogger(DefaultBeanResolver.class);

  public DefaultBeanResolver(Object[] obj) {;}

  public Object getBean(String name) throws Exception {
    return Class.forName(name).newInstance();
  }
}

// SpringBeanResolver.java
public class SpringBeanResolver implements IBeanResolver {

  private ApplicationContext context;

  public SpringBeanResolver(Object[] obj) {
    String[] applicationContextFiles = (String[]) obj;
    context = new ClassPathXmlApplicationContext(applicationContextFiles);
  }

  public Object getBean(String name) throws Exception {
    return context.getBean(name);
  }
}

Putting it all together - the CLI

Finally, we have a command line interface which is going to be called from our shell script. It provides command line help, a --list option which allows us to list the parameters that are used by the named SCLOS script, and an --execute option which will execute the SCLOS script with the named context and parameters. The code is shown below:

 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Main.java
public class Main {
  public void help() {
    System.out.println("Usage information:");
    System.out.println("Options:");
    System.out.println("--help|h    : print this message");
    System.out.println("--list|l    : list settable variables.");
    System.out.println("--context|c : specify context files. Not needed for\n" +                       "              fully qualified beans");
    System.out.println("--execute|c : Execute the script.");
    System.out.println("Examples:");
    System.out.println("java Main --help");
    System.out.println("java Main --list scriptfile");
    System.out.println("java Main [--context spring:classpath:applicationContext.xml,...]\n" +
                       "    varname1=value1 [varname2=value2 ...] scriptfile");
  }

  public void initializeContexts(String contextParam) throws Exception {
    // if multiple contexts, the variable is bounded by double quotes and
    // contexts are separated by space
    boolean hasMultipleContexts = contextParam.startsWith("\"") &&
      contextParam.endsWith("\"");
    String[] contextParamElements = null;
    if (hasMultipleContexts) {
      contextParamElements = StringUtils.split(
        contextParam.substring(1, contextParam.length() - 1), ' ');
    } else {
      contextParamElements = new String[] {contextParam};
    }
    Map<String,String[]> contextMap = new HashMap<String,String[]>();
    for (String contextParamElement : contextParamElements) {
      // each individual context looks like type:filename1,filename2,...
      int typeFileSepPos = contextParamElement.indexOf(':');
      String type = contextParamElement.substring(0, typeFileSepPos);
      String[] files = StringUtils.split(contextParamElement.substring(typeFileSepPos + 1), ',');
      contextMap.put(type, files);
    }
    BeanResolverFactory.initialize(contextMap);
  }

  public void reportVariables(String scriptFile) throws Exception {
    ScriptParser parser = new ScriptParser();
    parser.parse(scriptFile);
    Set<String> settableVars = parser.getAllSettableVars();
    System.out.println("List of settable variables");
    for (String settableVar : settableVars) {
      System.out.println("  " + settableVar);
    }
  }

  public void execute(List<String> arguments) throws Exception {
    // arguments ::= (name=value)* scriptfile
    List<String> nameValuePairs = arguments.subList(0, arguments.size() - 1);
    String scriptFile = arguments.get(arguments.size() - 1);
    ScriptParser parser = new ScriptParser();
    Closure closure = parser.parse(scriptFile);
    DynaBean input = new LazyDynaBean();
    for (String nameValuePair : nameValuePairs) {
      int eqSepPos = nameValuePair.indexOf('=');
      String key = nameValuePair.substring(0, eqSepPos);
      String value = nameValuePair.substring(eqSepPos + 1);
      input.set(key, value);
    }
    closure.execute(input);
  }

  @SuppressWarnings("unchecked")
  public static void main(String[] argv) {
    try {
      Main main = new Main();
      // parse the command line
      CommandLineParser parser = new BasicParser();
      Options options = new Options();
      options.addOption("h", "help", false, "Print usage information");
      options.addOption("l", "list", false, "List settable parameters");
      options.addOption("c", "context", false, "Specify available contexts");
      options.addOption("x", "execute", false, "Execute the script with required context and parameters");
      CommandLine commandLine = parser.parse(options, argv);
      List<String> args = commandLine.getArgList();
      if (commandLine.hasOption('h') || args.size() == 0) {
        main.help();
        System.exit(0);
      }
      if (commandLine.hasOption('l')) {
        if (args == null || args.size() == 0) {
          throw new Exception("Script file name should be set");
        }
        main.reportVariables(args.get(0));
        System.exit(0);
      }
      if (commandLine.hasOption('c')) {
        main.initializeContexts(commandLine.getOptionValue('c'));
      }
      main.execute(args);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

The shell script is a standard shell script that pulls in the required third party JAR files in its classpath and invokes java with the Main class. All command line processing is delegated off to the Main class. The last part of the classpath points to target/classes (for the SCLOS parsing code) and target/test-classes (for the user defined classes that the SCLOS script names). Both should probably be replaced with JAR files in a production environment.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#!/bin/bash
# sclos.sh
export M2_REPO=$HOME/.m2/repository

$JAVA_HOME/bin/java -classpath \
$M2_REPO/commons-beanutils/commons-beanutils/1.7.0/commons-beanutils-1.7.0.jar:\
$M2_REPO/commons-cli/commons-cli/1.0/commons-cli-1.0.jar:\
$M2_REPO/commons-collections/commons-collections/3.1/commons-collections-3.1.jar:\
$M2_REPO/commons-io/commons-io/1.2/commons-io-1.2.jar:\
$M2_REPO/commons-lang/commons-lang/2.1/commons-lang-2.1.jar:\
$M2_REPO/commons-logging/commons-logging/1.1/commons-logging-1.1.jar:\
$M2_REPO/log4j/log4j/1.2.8/log4j-1.2.8.jar:\
$M2_REPO/org/springframework/spring/2.0/spring-2.0.jar:\
$HOME/src/sclos/target/classes:\
$HOME/src/sclos/target/test-classes \
com.healthline.sclos.Main $*

Usage example

My test case was a Closure chain to read a file with words and numbers in them, discard the numbers and sort the words so they rhyme. The rhyming is done by first reversing each word, sorting them, and then reversing them back again. Here is the algorithm and the corresponding SCLOS script.

foreach line in inputfile:
  if alpha string:
    add to list1
  else:
    add to list2
reverse list 1
sort list1
reverse list 1
print list1
      
; example.sclos
(CHAIN
  com.mycompany.closures.ReadFileToListClosure
  (WHILE com.mycompany.predicates.ListNotReadPredicate
    (IF com.mycompany.predicates.AlphaPredicate
      com.mycompany.closures.AddToListClosure
      com.mycompany.closures.NOPClosure
    )
  )
  com.mycompany.closures.ReverseListContentsClosure
  com.mycompany.closures.SortListClosure
  com.mycompany.closures.ReverseListContentsClosure
  com.mycompany.closures.PrintListClosure
)
      

To see what parameters sclos.sh takes run the command:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
[sujit@cyclone sclos]$ src/main/shell/sclos.sh --help 
Usage information:
Options:
--help|h    : print this message
--list|l    : list settable variables.
--context|c : specify context files. Not needed for
              fully qualified beans
--execute|c : Execute the script.
Examples:
java Main --help
java Main --list scriptfile
java Main [--context spring:classpath:applicationContext.xml,...]
    varname1=value1 [varname2=value2 ...] scriptfile

To find the parameters that the script needs, we run the following command:

1
2
3
4
5
6
[sujit@cyclone sclos]$ src/main/shell/sclos.sh --list src/test/resources/example.sclos
List of settable variables
  listIterator
  currentLine
  filename
  strList

Out of these, the only one we can set from the command is the filename parameter. This is not obvious from the command line, but I could not find a way to distinguish the ones that are passed around versus the one that comes in from the user. Perhaps some naming convention can be set up for this. So finally, we want to run the script against an input file of words input.txt.

1
2
3
4
5
6
7
8
9
[sujit@cyclone sclos]$ src/main/shell/sclos.sh \
  --execute filename=src/test/resources/input.txt src/test/resources/example.sclos
1:place
2:something
3:nothing
4:everything
5:this
6:roddy
7:nobody

The user-defined Closure and Predicate implementations are shown below, to give you an idea of what is involved in setting up the closure chain for the script.

  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
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
// AddToListClosure.java
public class AddToListClosure implements Closure {
  private String currentLine;
  public void setPropCurrentLine(String currentLine) { this.currentLine = currentLine; }

  private List<String> strList;
  public void setPropStrList(List<String> strList) { this.strList = strList; }
  public List<String> getPropStrList() { return strList; }

  public void execute(Object input) {
    if (strList == null) {
      strList = new ArrayList<String>();
    }
    strList.add(currentLine);
  }
}

// NOPClosure.java
public class NOPClosure implements Closure {
  public void execute(Object input) { // NOOP }
}

// PrintListClosure.java
public class PrintListClosure implements Closure {
  private List<String> strList;
  public void setPropStrList(List<String> strList) { this.strList = strList; }

  public void execute(Object input) {
    int i = 0;
    for (String element : strList) {
      i++;
      System.out.println(i + ":" + element);
    }
  }
}

// ReadFileToListClosure.java
public class ReadFileToListClosure implements Closure {
  private List<String> list;

  private String filename;
  public void setPropFilename(String filename) { this.filename = filename; }

  private Iterator<String> listIterator;
  public Iterator<String> getPropListIterator() { return listIterator; }

  public void execute(Object input) {
    list = new ArrayList<String>();
    try {
      BufferedReader reader = new BufferedReader(
        new InputStreamReader(new FileInputStream(filename)));
      String line = null;
      while ((line = reader.readLine()) != null) {
        list.add(line);
      }
      listIterator = list.iterator();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

}

// ReverseListContentsClosure.java
public class ReverseListContentsClosure implements Closure {
  private List<String> strList;
  public List<String> getPropStrList() { return strList; }
  public void setPropStrList(List<String> list) { this.strList = list; }

  public void execute(Object input) {
    List<String> reversedList = new ArrayList<String>();
    for (String element : strList) {
      reversedList.add(StringUtils.reverse(element));
    }
    this.strList = reversedList;
  }
}

// SortListClosure.java
public class SortListClosure implements Closure {
  private List<String> strList;
  public void setPropStrList(List<String> strList) { this.strList = strList; }
  public List<String> getPropStrList() { return strList; }

  public void execute(Object input) {
    Collections.sort(strList);
  }
}

// AlphaPredicate.java
public class AlphaPredicate implements Predicate {
  private String currentLine;
  public String getPropCurrentLine() { return currentLine; }
  public void setPropCurrentLine(String currentLine) { this.currentLine = currentLine; }

  public boolean evaluate(Object object) {
    boolean isAlpha = true;
    char[] chars = currentLine.toCharArray();
    for (char ch : chars) {
      if (! Character.isLetter(ch)) {
        isAlpha = false;
        break;
      }
    }
    return isAlpha;
  }
}

// ListNotReadPredicate.java
public class ListNotReadPredicate implements Predicate {
  private Iterator<String> listIterator;
  public void setPropListIterator(Iterator<String> listIterator) { this.listIterator = listIterator; }

  private String currentLine;
  public String getPropCurrentLine() { return currentLine; }

  public boolean evaluate(Object object) {
    if (listIterator.hasNext()) {
      currentLine = listIterator.next();
      return true;
    } else {
      return false;
    }
  }
}

Conclusion

This has been a fairly long post, and if you had the patience to get here, I hope this post has been helpful. This style of scripting Java objects is probably not what my colleague had in mind when he mentioned Unix utilities, and this approach probably introduces more complexity on another plane. For example, now you are forced to think in terms of Predicates and Closures. Actually, while I agree that the Predicate style of coding where the evaluation happens in a separate class takes a little getting used to, implementing Closures to do some specific task is probably not that far out. Also, since this approach depends on naming conventions for data, its probably a little more inconvenient than simply throwing classes together.

However, I think there are advantages to this approach as well. It allows you to develop in small independent units, and allows you to loosely couple these units into a command line script, as long as you are prepared to deal with (fairly minor, in my opinion) name integration issues during integration.