/instrumentation/akka-http-10.0/javaagent/src/test/scala/AkkaHttpTestSyncWebServer.scala

https://github.com/open-telemetry/opentelemetry-auto-instr-java · Scala · 73 lines · 62 code · 6 blank · 5 comment · 4 complexity · 11f13b495022d7fbda323f0558db1423 MD5 · raw file

  1. /*
  2. * Copyright The OpenTelemetry Authors
  3. * SPDX-License-Identifier: Apache-2.0
  4. */
  5. import akka.actor.ActorSystem
  6. import akka.http.scaladsl.Http
  7. import akka.http.scaladsl.Http.ServerBinding
  8. import akka.http.scaladsl.model.HttpMethods.GET
  9. import akka.http.scaladsl.model._
  10. import akka.stream.ActorMaterializer
  11. import groovy.lang.Closure
  12. import io.opentelemetry.instrumentation.test.base.HttpServerTest
  13. import io.opentelemetry.instrumentation.test.base.HttpServerTest.ServerEndpoint._
  14. import scala.concurrent.Await
  15. object AkkaHttpTestSyncWebServer {
  16. implicit val system = ActorSystem("my-system")
  17. implicit val materializer = ActorMaterializer()
  18. // needed for the future flatMap/onComplete in the end
  19. implicit val executionContext = system.dispatcher
  20. val syncHandler: HttpRequest => HttpResponse = {
  21. case HttpRequest(GET, uri: Uri, _, _, _) => {
  22. val endpoint = HttpServerTest.ServerEndpoint.forPath(uri.path.toString())
  23. HttpServerTest.controller(
  24. endpoint,
  25. new Closure[HttpResponse](()) {
  26. def doCall(): HttpResponse = {
  27. val resp = HttpResponse(status = endpoint.getStatus)
  28. endpoint match {
  29. case SUCCESS => resp.withEntity(endpoint.getBody)
  30. case INDEXED_CHILD =>
  31. INDEXED_CHILD.collectSpanAttributes(new UrlParameterProvider {
  32. override def getParameter(name: String): String =
  33. uri.query().get(name).orNull
  34. })
  35. resp.withEntity("")
  36. case QUERY_PARAM => resp.withEntity(uri.queryString().orNull)
  37. case REDIRECT =>
  38. resp.withHeaders(headers.Location(endpoint.getBody))
  39. case ERROR => resp.withEntity(endpoint.getBody)
  40. case EXCEPTION => throw new Exception(endpoint.getBody)
  41. case _ =>
  42. HttpResponse(status = NOT_FOUND.getStatus)
  43. .withEntity(NOT_FOUND.getBody)
  44. }
  45. }
  46. }
  47. )
  48. }
  49. }
  50. private var binding: ServerBinding = null
  51. def start(port: Int): Unit = synchronized {
  52. if (null == binding) {
  53. import scala.concurrent.duration._
  54. binding = Await.result(
  55. Http().bindAndHandleSync(syncHandler, "localhost", port),
  56. 10 seconds
  57. )
  58. }
  59. }
  60. def stop(): Unit = synchronized {
  61. if (null != binding) {
  62. binding.unbind()
  63. system.terminate()
  64. binding = null
  65. }
  66. }
  67. }