Asymmetrical View

Creating Standalone Java Applications with Leiningen

Leiningen is a simpler build tool for Clojure. Previously I covered a few basic aspects including how to run the HEAD version of Leiningen. Leiningen can also build a standalone jars in the same way the maven assembly plug-in does. There are a few steps you need to follow, I’ll walk you through them here. This example is available in my sandbox.

project.clj

For the example, I started by creating a new project (for testing a csv parsing library) by running lein new cljcsv. I added clojure-csv as a dependency, set cljcsv.core to be compiled, by specifying the name-space with the :aot parameter and specified cljcsv.core to be the main class invoked for the jar file by specifying it with :main.

(defproject cljcsv "1.0.0-SNAPSHOT"
  :description "CSV Example."
  :dependencies
    [[org.clojure/clojure "1.1.0"]
     [org.clojure/clojure-contrib "1.1.0"]
     [clojure-csv/clojure-csv "1.0.0"]]
  :aot  [cljcsv.core]
  :main cljcsv.core)

src/cljcsv/core.clj

To have a Clojure program produce a class file with a main function, you need to ensure you have :gen-class specified in the name-space for your program and that you define a -main function to act as the main.

(ns cljcsv.core
  (:require [com.davidsantiago.csv :as cdc]
            [clojure.contrib.pprint :as pp])
  (:gen-class))

(defn parse-cdc [file]
 (let [rs (cdc/parse-csv (slurp file))]
  (prn (str "rs=" rs))
  (prn (pp/cl-format nil "cdc: rows: ~a~&" (count rs)))
  (prn (pp/cl-format nil "cdc: ~a~&" rs))))

(defn -main [& args]
  (prn (format "args=%s" args))
  (if (not (empty? args))
    (do
      (parse-cdc (first args)))))

Then to build and run the jar:

$ lein compile
$ lein uberjar
$ java -jar cljcsv-standalone.jar input.csv

Leiningen makes creating and building Clojure projects quick and easy. It makes creating an executable jar for your project, which may have many dependencies, about as easy as you can get.

Kyle Burton, 08 Jun 2010 – Philadelphia PA

Special Thanks

Special thanks to technomancy, for creating Leiningen.


Tags: clojure,leiningen,build-tools