Skip to content

Instantly share code, notes, and snippets.

@karthik20522
Created May 25, 2019 03:45
Show Gist options
  • Save karthik20522/efed2e48b3a69132f7e76b7824112730 to your computer and use it in GitHub Desktop.
Save karthik20522/efed2e48b3a69132f7e76b7824112730 to your computer and use it in GitHub Desktop.
Calling SOAP Service in Scala
import spray.client.pipelining._
import akka.actor.{ ActorRefFactory }
import spray.http._
import spray.httpx._
import scala.concurrent.Future
import scala.xml._
class KeywordService(keywordServiceURL: String, implicit val actorRefFactory: ActorRefFactory) {
import actorRefFactory.dispatcher
def sendAndReceive = sendReceive
def fetchKeywords(keywordIds: List[Int], language: String = "en-us"): Future[Elem] = {
if (keywordIds.isEmpty) {
Future { <xml/> }
} else {
val requestDetail = new GetKeywordDetailsRequest("test", 0, Terms(termIds = keywordIds), DesiredDetails(languageCodes = language))
doRequest(keywordServiceURL, wrap(requestDetail.toXML), Some(keywordLookupMetric))
}
}
private val mapErrors = (response: HttpResponse) => {
response.status.isSuccess match {
case true => response
case false => throw new Exception(response.entity.asString)
}
}
private def doRequest(uri: String, data: Elem, timer: Option[Timer] = None): Future[Elem] = {
val kwdServiceURI = Uri(uri)
val pipeline = addHeader("SOAPAction", "http://xxx.com/GetKeywordDetails") ~> sendAndReceive ~> mapErrors ~> unmarshal[HttpResponse]
val kwdServiceResponse: Future[HttpResponse] = pipeline(Post(kwdServiceURI, data))
kwdServiceResponse map {
r => XML.loadString(r.entity.asString(spray.http.HttpCharsets.`UTF-8`).replaceAll("[^\\x20-\\x7e]", ""))
} recover {
case any: UnsuccessfulResponseException => throw any;
}
}
def wrap(xml: Elem): Elem = {
val buf = new StringBuilder
buf.append("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">")
buf.append("<s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">")
buf.append(xml.toString.split('\n').map(_.trim.filter(_ >= ' ')).mkString)
buf.append("</s:Body>")
buf.append("</s:Envelope>")
XML.loadString(buf.toString)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment