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

https://github.com/open-telemetry/opentelemetry-auto-instr-java · Scala · 65 lines · 51 code · 8 blank · 6 comment · 4 complexity · b1436f63b1806bdabb8cd51312aa6885 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._
  9. import akka.http.scaladsl.server.Directives._
  10. import akka.http.scaladsl.server.ExceptionHandler
  11. import akka.stream.ActorMaterializer
  12. import io.opentelemetry.instrumentation.test.base.HttpServerTest.ServerEndpoint._
  13. import scala.concurrent.Await
  14. // FIXME: This doesn't work because we don't support bindAndHandle.
  15. object AkkaHttpTestWebServer {
  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 exceptionHandler = ExceptionHandler { case ex: Exception =>
  21. complete(
  22. HttpResponse(status = EXCEPTION.getStatus).withEntity(ex.getMessage)
  23. )
  24. }
  25. val route = { //handleExceptions(exceptionHandler) {
  26. path(SUCCESS.rawPath) {
  27. complete(
  28. HttpResponse(status = SUCCESS.getStatus).withEntity(SUCCESS.getBody)
  29. )
  30. } ~ path(QUERY_PARAM.rawPath) {
  31. complete(
  32. HttpResponse(status = QUERY_PARAM.getStatus).withEntity(SUCCESS.getBody)
  33. )
  34. } ~ path(REDIRECT.rawPath) {
  35. redirect(Uri(REDIRECT.getBody), StatusCodes.Found)
  36. } ~ path(ERROR.rawPath) {
  37. complete(HttpResponse(status = ERROR.getStatus).withEntity(ERROR.getBody))
  38. } ~ path(EXCEPTION.rawPath) {
  39. failWith(new Exception(EXCEPTION.getBody))
  40. }
  41. }
  42. private var binding: ServerBinding = null
  43. def start(port: Int): Unit = synchronized {
  44. if (null == binding) {
  45. import scala.concurrent.duration._
  46. binding =
  47. Await.result(Http().bindAndHandle(route, "localhost", port), 10 seconds)
  48. }
  49. }
  50. def stop(): Unit = synchronized {
  51. if (null != binding) {
  52. binding.unbind()
  53. system.terminate()
  54. binding = null
  55. }
  56. }
  57. }