A few months ago I was chatting to Brad Clow about the new Ehcache Server. I asked him for an example with Scala. Anyway he just got back to me with what is the smallest program yet for accessing RESTful Ehcache Server.
In a file named ExampleScalaGet.scala:
import java.net.URL import scala.io.Source.fromInputStream object ExampleScalaGet extends Application { val url = new URL("http://localhost:8080/ehcache/rest/sampleCache2/2") fromInputStream(url.openStream).getLines.foreach(print) }
run it with:
scala -e ExampleScalaGet
The program outputs:
goodnight
,
Gracie.
Goodnight,
Gracie.
If you are on a Mac the easiest way to get scale installed is “sudo port install scala”.
The Scala program ways in at 6 lines. Now, let’s compare it’s tersity with the other languages, all doing a GET and printing the result (See http://ehcache.sourceforge.net/documentation/cache_server.html for the examples). Whitespace lines are not included.
Scala 6 lines, using java.net.URL
PHP 6 lines, using curl lib
Python 3 lines, using urllib2
Ruby 6 lines, using open-uri
Java 19 lines, using java.net.HttpUrlConnection, which does a few things before it gives the InputStream as used in the Scala example.
Thanks to Brad for rounding out the examples.
Scala looks very interesting.
Comparing it with the others:
Brad has also blogged about his Scala example here: http://bradclow.blogspot.com/2009/01/scala-example-for-accessing-ehcache.html
Probably should do try/finally/close on the stream in Scala, too. Or am I missing something?
If we’re counting lines then I get to play golf 🙂
//in a file named ExampleScalaGet2.scala
import java.net.URL
import scala.io.Source.fromInputStream
fromInputStream(new URL(“http://localhost:8080/ehcache/rest/sampleCache2/2”).openStream).getLines.foreach(print)
//run with “scala ExampleScalaGet2”
In Clojure that’s:
(ns example-ehcache (:use clojure.xml))
(parse “”)
Tom, I have written my rational about why the code sample is as it is here.
Since we’re golfing, the Ruby example listed has a bunch of requires that aren’t used (rubygems, rexml), plus some useless variable assignment. Two lines are all that you need:
Granted, it’s not statically typed, and it uses Ruby’s much-maligned Net::HTTP, and it makes open work on both files and URIs… but hey.
Been waiting for a real-life need to play around with Ehcache — might have to jump the gun a bit.
In Clojure:
If you just want lines:
(clojure.contrib.duck-streams/read-lines (java.net.URL. “http://your.address/here”))
or if you want a tree:
(clojure.xml/parse “http://your.address/here”)