How to Buildr showdown.js into JavaHow to Buildr showdown.js into Java

Do you want a Markdown translator to use in the JVM that gives exactly the same results as one in JavaScript? It wouldn’t hurt! Because you see, having the translator in JavaScript means you can do a sweet live preview in the browser. But all text processing thingies have quirks, or just very special features, so you should really use exactly the same one on the server as the client so your writers do not have unpleasant surprises.

Thanks to Rhino this is not hard to do. If you want a Buildr buildfile that downloads Rhino, downloads Showdown, and uses the former to compile the latter, then here it is:

repositories.remote << "http://www.ibiblio.org/maven2/"

rhino = artifact('rhino:js:jar:1.7R1')

define "showdown" do
  SD_V = '0.9'
  showdown_zip = artifact("net.attacklab:showdown:zip:#{SD_V}")
  download(showdown_zip.name => "http://attacklab.net/showdown/showdown-v#{SD_V}.zip")
  zip = unzip('target/zip' => showdown_zip)

  showdown_js = file('target/Showdown.js' => zip) do |t|
    cp(File.join(zip.target.name, 'src/showdown.js'), t.name)
    f = File.new(t.name, "a")
    f.write("\nfunction makeHtml(md) { return new Showdown.converter().makeHtml('' + md) }")
    f.close
  end

  task :build => file('target/classes/showdown.class' => [rhino, showdown_js])  do
    Java::Commands.java(
      :classpath => rhino, 
      :java_args => [
        'org.mozilla.javascript.tools.jsc.Main', 
        '-d', 'target/classes', 
        '-extends', 'java.lang.Object',
        showdown_js.name
      ]
    )
  end
end

task :run => project('showdown').task(:build) do
  system "scala -classpath target/classes:#{rhino}"
end

The run task is to try it in the Scala interpreter, like so:

$ buildr clean run
...
scala> (new Showdown).makeHtml("**what**")                
res0: java.lang.Object = <p><strong>what</strong></p>

Die, FCKeditor, die.

Add a comment