Code Monkeyism

Programming is hard by Stephan Schmidt

scala.xml.Node, text/xml and Jersey: How to do REST with Scala

Scala has native support for xml in the language via scala.xml.Node

val message = <message>Hello world</message>

There is an excellent book called scala.xml on XML and Scala so this post won’t go into more detail.

Using the XML support in Scala makes it easy to write REST applications with Jersey. I’ve shown how to create JSON with a JsonBuilder in Scala before.

We need a Resource to handle our REST requests. As a response to a GET request on /helloWorld/xml we create a Scala XML node:

@Path("/helloWorld")
class HelloWorld {
  @Path("/xml")
  @GET
  @Produces(Array("text/xml"))
  def helloWorld() = {
    Hello World
  }
}

Jersey needs to know how to translate an object of scala.xml.Node to a HTTP response. This is usually done by implementing a MessageBodyWriter that maps an object and a mime type - scala.xml.Node and text/xml in this case - to a response.

@Provider
@Produces(Array("text/xml"))
class ScalaNodeAdapter extends MessageBodyWriter[scala.xml.Node] {

  def isWriteable(dataType:java.lang.Class[_],
                       typ:Type,
                       annotations:Array[Annotation]) = {
    classOf[scala.xml.Node].isAssignableFrom(dataType);
  }

  def writeTo(node:scala.xml.Node, writer:Writer) {
    writer.write(node.toString)
  }

  def getSize(node:scala.xml.Node) = -1L

  def writeTo(node:scala.xml.Node, aClass:java.lang.Class[_],
                  typ:Type,
                  annotations:Array[Annotation],
                  mediaType:MediaType,
                  stringObjectMultivaluedMap:MultivaluedMap[String,Object],
                  outputStream:OutputStream) {
    val writer = new OutputStreamWriter(outputStream);
    writeTo(node, writer)
    writer.close()
  }
}

Voila, we now get <message>Hello world</message> when calling /helloWorld/xml.

Thanks for listening.

About the author: Stephan Schmidt is currently a team manager at ImmobilienScout24 in Berlin. Stephan has been working as a head of development and CTO. He has used a lot of different technologies in the last 20 years including Java, Rails and Python. Stephans main field of interest is maintainablity and productivity in software development. Want to know more? All views are only his own.

If you did like this article but you don't want to subscribe to new articles with your reader, you can follow me on Twitter or subscribe to new posts with your email:

Leave a Reply