Embedding Clojure/swank into existing Java system

67 views
Skip to first unread message

Anton Vodonosov

unread,
Nov 28, 2008, 9:37:52 PM11/28/08
to Clojure
Hello.

I want to embed Clojure into a Java system we are creating at work to
have interactive control on it (via SLIME) during development. The
system is running in Tomcat.

I did not find a conventional to do this. Therefore I copy/pasted
peace of clojure.lang.Repl class and created a JSP page, that starts
Clojure and swank when executed. The JSP may be found here:
http://paste.lisp.org/display/71206.

It is quite simple and works OK, but I dislike the copy/pasting of
clojure.lang.Repl code. Is there a better way to embed swank into a
Java system?

Best regards,
- Anton

Craig McDaniel

unread,
Dec 1, 2008, 11:46:49 AM12/1/08
to Clojure
Since release 1127, you can now do this instead:

$ cat src/mypkg/HelloServlet.clj
(ns myapp.HelloServlet
(:gen-class
:extends javax.servlet.http.HttpServlet)
(:import (java.io PrintWriter)
(java.util.logging Logger Level))
(:require swank clojure.main))

(defn- -init [this config]
(clojure.main/with-bindings
(swank/ignore-protocol-version "2008-11-23")
(swank/start-server "/dev/null" :port 4006 :encoding "iso-latin-1-
unix")))

(defn- -doGet [this request response]
(.severe (Logger/getLogger "hello") "logging this thang")
(.setContentType response "text/html")
(let [out (PrintWriter. (.getWriter response))]
(doto out
(.println "<html>")
(.println "<head>")
(.println "<title>Hello World!</title>")
(.println "</head>")
(.println "<body>")
(.println "<h1>Hello Bizarro World...from Clojure!</h1>")
(.println (str "17 + 33 = " (+ 17 33)))
(.println "</body>")
(.println "</html>"))))

It doesn't handle the unloading/reloading of servlets well, so it
could be improved by:

1. Letting swank pick which port to listen on, and writing the port
number to a temporary file.
2. On unload, closing the swank socket and deleting the temporary
file.

I posted the whole project (build.xml, etc...) here: http://paste.lisp.org/display/71326

I'm also going to try installing a Compojure-built servlet into
Tomcat. I'll post that later if I can make that work.

Craig McDaniel

unread,
Dec 1, 2008, 2:09:47 PM12/1/08
to Clojure
Never mind about my unloaded/reloading servlets comment. Checking for
a swank exception as in the original example would work fine.

-Craig

Anton Vodonosov

unread,
Dec 3, 2008, 5:17:29 PM12/3/08
to Clojure
Hi Craig,

clojure.main/with-bindings was exactly what I needed.
With it my JSP became trivial few liner: http://paste.lisp.org/display/71541

Thank you.

- Anton
Reply all
Reply to author
Forward
0 new messages