Skip to content

Instantly share code, notes, and snippets.

@mattnworb
Created January 30, 2014 20:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattnworb/8717911 to your computer and use it in GitHub Desktop.
Save mattnworb/8717911 to your computer and use it in GitHub Desktop.
override def query(q: String) = {
val responses: Seq[Future[HttpResponse]] = clients.map {client => client.query(q)}
val allResponses: Future[Seq[HttpResponse]] = Future.collect(responses)
val successResponses: Future[Seq[HttpResponse]] = allResponses.map(responses => responses.filter(_.getStatus == HttpResponseStatus.OK))
successResponses.map { responses: Seq[HttpResponse] =>
if (responses.isEmpty) {
errorResponse(HttpResponseStatus.INTERNAL_SERVER_ERROR, "No successful responses")
}
else {
mergeResponses(responses)
}
}.rescue{
case ex: Exception => Future.value(
errorResponse(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Exception: " + ex)
)
}
}
def mergeResponses(responses: Seq[HttpResponse]): HttpResponse = {
val resultStrings: Seq[String] = responses.map(response => {
val content: String = response.getContent.toString(UTF_8)
val jsonNode = objectMapper.readTree(content)
val arrayString = jsonNode.get("results").toString()
//println("Seen shared result: " + arrayString)
val strings = arrayString.replaceAll("\\[|\\]", "").split(",")
strings.map( rs => {
rs.replaceAll("\"", "")
})
}).flatten
//TODO filter out an empty result string like []
val matches = resultStrings.toSet.map { str: String => {
val colon = str.indexOf(":")
if (colon > -1) {
Match(str.substring(0, colon), Integer.parseInt(str.substring(colon + 1)))
}
else {
println("parsing error! for: " + str)
Match("", 0)
}
}}
querySuccessResponse(matches.toSeq)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment