Groovy slurping of yr.no

It’s about time for a new geek post!

I’ve been playing around a bit with Groovy lately, and it’s really neat, especially for processing XML stuff. It has a bunch of ways of reading it, from the more normal Java-like ways of DomBuilder to the Groovy way of XmlSlurper. And then it has it’s really cool builder syntax for constructing XML, or pretty much whatever else you can represent as a tree (Swing GUIs, JSON and so on).

Now I’d like to combine some slurping and building to show some custom formatted weather data for the city of Oslo, consumed from the Norwegian online weather portal yr.no‘s API!

  1. def weather = new XmlSlurper().parse(yrUrl + "/varsel.xml")
  2. new MarkupBuilder(writer).div {
  3.     h2("Vær for " + weather.location.name)
  4.     p {
  5.         def w = weather.forecast.tabular.time[0]
  6.             String.format("%02d", w.symbol.@number.toInteger()) +
  7.             (w.symbol.@number.toInteger()<9 && w.@period == "0"?"n":"") + ".png")
  8.         span("class":w.temperature.@value.toInteger()<0?"minus":"plus" + " temperature",
  9.             w.temperature.@value.text() + "°")
  10.         br()
  11.         span("class":"wind", w.windSpeed.@name.text() + ", " +
  12.             w.windSpeed.@mps.text() + " m/s fra " + w.windDirection.@name.text())
  13.     }
  14.     p("class":"nag", "Varsel fra ") {
  15.         a("href":yrUrl,"yr.no")
  16.     }
  17. }
  18.  
  19. println writer.toString()

That’s it. About 20 lines for reading and parsing a URL and building a HTML fragment, now let’s see you do that with plain Java and the DomBuilder… 😉

There is some added ugliness in there that probably deserves an explanation. For one, since I wanted to display temperatures below/above zero with a custom CSS class I’m checking the value of the temperature. Secondly, I wanted to use the weather images directly off NRK’s server. Symbols 1-9 starts with a leading zero and symbol 1-8 are different during nighttime..

Reklamer

3 thoughts on “Groovy slurping of yr.no

Legg igjen en kommentar

Fyll inn i feltene under, eller klikk på et ikon for å logge inn:

WordPress.com-logo

Du kommenterer med bruk av din WordPress.com konto. Logg ut / Endre )

Twitter-bilde

Du kommenterer med bruk av din Twitter konto. Logg ut / Endre )

Facebookbilde

Du kommenterer med bruk av din Facebook konto. Logg ut / Endre )

Google+-bilde

Du kommenterer med bruk av din Google+ konto. Logg ut / Endre )

Kobler til %s