the blog for developers

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 Stephan Schmidt has been working with internet technologies for the last 20 years. He was head of development, consultant and CTO and is a speaker, author and blog writer. He specializes in organizing and optimizing software development helping companies by increasing productivity with lean software development and agile methodologies. Want to know more? All views are only his own. You can find him on Google +

You can leave a Reply here. Of course, you should follow me on twitter here.

You can share this post!
Do you want to tell others about this article? Use the social bookmark icons to submit this artice to the service of your choice. Thanks.

Leave a reply.

Comments

Mark

Thanks for this, very helpful.

Note that most people will want:

new OutputStreamWriter(outputStream, Charset.forName(“UTF-8″))

instead of:

new OutputStreamWriter(outputStream)

Leave a Reply

What people wrote somewhere else:

Additional comments powered by BackType

Guide to CodeMonkeyism

Over the last 4 years I wrote many articles on this blog. To make it easier for you to find the relevant ones, I've organized them into topics.

Top 10

6 reasons why my VC funded startup did fail

Go Ahead: Next Generation Java Programming Style

Java Interview questions: Write a String Reverser

The dark side of NoSQL

7 Bad Signs not to Work for a Software Company or Startup

Is Java dead?

Scala vs. Clojure

Never, never, never use String in Java

No future for functional programming in 2008 – Scala, F# and Nu

Clojure vs Scala, Part 2

Java Developer

Is Java Dead?

Go Ahead: Next Generation Java Programming Style

Be careful with magical code

All variables in Java must be final

Never, never, never use String in Java

Bending Java: More readable code with methods that do nothing?

NoSQL Guy

NoSQL: The Dawn of Polyglot Persistence

The dark side of NoSQL

Essential storage tradeoff: Simple Reads vs. Simple Writes

Sharding destroys the goals of your relational database

The unholy legacy of databases

Startup/CTO

Development Dream Teams

6 reasons why my VC funded startup did fail

American vs. European style of Software Development

12 Things to Reduce Your Lead Time and Time to Market

The high cost of overhead when working in parallel

Essential storage tradeoff: Simple Reads vs. Simple Writes

Job Seeker

Another Good (Java) Interview Question

7 Bad Signs not to Work for a Software Company or Startup

Java Interview questions: Write a String Reverser (and use Recursion!)

Java Interview questions: Multiple Inheritance

As a Manager: What I value in developers

Top 10 Tips (+1) to Get a Pay Raise

Agilist

What Developers Need to Know About Agile

5 Practices Better to Change in Your Scrum Implementation

Scrum is not about engineering practices

ScrumMaster and ZenMaster: The joke of certification

What is Trans-Scrum?