Tuesday, April 26, 2022

Using apache commons exec from Clojure

One of the strong points of Clojure is its ability to handle markup languages like HTML, so I figure why not demonstrate the apache commons exec library by opening up a browser window to display hiccup generated HTML.
(ns executor.core
  (:use (hiccup core))
  (:import [org.apache.commons.io FileUtils]
           [org.apache.commons.exec CommandLine DefaultExecutor]
           (java.io File)
           (java.nio.charset StandardCharsets)))

; hiccup generated html
(def page-data
  [:html
   [:head
    [:title "Group rings"]]
   [:body
    "Let G be a group and R a ring then R[G] is its group ring."]])

; store the html on the file system first
(defn ^File create-temp-file
  [html-data]

  (let [tmp (FileUtils/getTempDirectory)
        out-file (new File (str (.getPath tmp) "/out.html"))]
    (FileUtils/write out-file (html html-data) StandardCharsets/UTF_8)
    out-file))

; display the temp file in the browser
(defn display-temp-file
  [file]

  (let [cmdLine (new CommandLine "firefox")]
    (.addArgument cmdLine (.getPath file))
    (let [executor (new DefaultExecutor)]
      (.execute executor cmdLine))))

; Create a file and display it at the same time
(defn display-html
  [data]

  (display-temp-file (create-temp-file data)))

Another possibility is that you can display generated HTML using Swing. In either case, it is relatively easy to open up some kind of window to display an HTML document. Apache commons exec can be used to open up all kinds of processes from Clojure.

External links:
Apache commons exec

No comments:

Post a Comment