I'm working in Scala and need to distinguish between XML messages that represent either success or failure. The information I've found provides lots of insight into pulling apart a known XML fragment but not where you're unsure of which fragment you have.
Here are the two possible messages:
val success = XML.loadString("""<cas:serviceResponse xmlns:cas='http://ift.tt/1jNd6ZE'>
<cas:authenticationSuccess>
<cas:user>bwbecker</cas:user>
</cas:authenticationSuccess>
</cas:serviceResponse>""")
val failure = XML.loadString("""<cas:serviceResponse xmlns:cas='http://ift.tt/1jNd6ZE'>
<cas:authenticationFailure code='INVALID_REQUEST'>
'service' and 'ticket' parameters are both required
</cas:authenticationFailure>
</cas:serviceResponse>""")
The following code does what I want (I'll eventually return an Either of case classes, but this is fine for playing...):
def parse(response: NodeSeq):Either[String, String] = {
(response \ "authenticationSuccess").headOption
.flatMap(succ => (succ \ "user").headOption)
.map(usr => Right(usr.text))
.getOrElse((response \ "authenticationFailure").headOption
.map{fail =>
val code = fail \ "@code"
val msg = fail.text
Left(s"Failure: ${code} ${msg}")
}
.getOrElse(Left("Really Botched"))
)
}
However, I find this really hard to code and read. Is there a better way? What if I had five different messages to distinguish?
I tried matchers, but got discouraged with the arcane syntax for XML (the cas: namespace seems to complicate things).
Any guidance for improving my code?
No comments:
Post a Comment