akka.http.scaladsl.model.StatusCodes.OK Scala Examples

The following examples show how to use akka.http.scaladsl.model.StatusCodes.OK. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: FailoverTestGateway.scala    From affinity   with Apache License 2.0 5 votes vote down vote up
package io.amient.affinity.core.cluster

import akka.http.scaladsl.model.HttpMethods.{GET, POST}
import akka.http.scaladsl.model.StatusCodes.{NotFound, OK, SeeOther}
import akka.http.scaladsl.model.{HttpResponse, Uri, headers}
import akka.util.Timeout
import com.typesafe.config.ConfigFactory
import io.amient.affinity.core.actor.GatewayHttp
import io.amient.affinity.core.cluster.FailoverTestPartition.{GetValue, PutValue}
import io.amient.affinity.core.http.RequestMatchers.{HTTP, PATH}
import io.amient.affinity.core.http.{Encoder, HttpInterfaceConf}

import scala.collection.JavaConverters._
import scala.concurrent.duration._
import io.amient.affinity.core.ack
import scala.language.postfixOps

class FailoverTestGateway extends GatewayHttp {

  override val rejectSuspendedHttpRequests = false

  override def listenerConfigs: Seq[HttpInterfaceConf] = List(HttpInterfaceConf(
    ConfigFactory.parseMap(Map("host" -> "127.0.0.1", "port" -> "0").asJava)))

  implicit val executor = scala.concurrent.ExecutionContext.Implicits.global

  implicit val scheduler = context.system.scheduler

  val keyspace1 = keyspace("keyspace1")

  override def handle: Receive = {
    case HTTP(GET, PATH(key), _, response) => handleWith(response) {
      implicit val timeout = Timeout(1 seconds)
      keyspace1 ?! GetValue(key) map {
        _ match {
          case None => HttpResponse(NotFound)
          case Some(value) => Encoder.json(OK, value, gzip = false)
        }
      }
    }

    case HTTP(POST, PATH(key, value), _, response) => handleWith(response) {
      implicit val timeout = Timeout(1 seconds)
      keyspace1 ?! PutValue(key, value) map {
        case _ => HttpResponse(SeeOther, headers = List(headers.Location(Uri(s"/$key"))))
      }
    }
  }
} 
Example 2
Source File: ArchiveRoutes.scala    From nexus-kg   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.kg.routes

import akka.http.scaladsl.model.StatusCodes.{Created, OK}
import akka.http.scaladsl.model.headers.Accept
import akka.http.scaladsl.model.{HttpEntity, MediaTypes}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import ch.epfl.bluebrain.nexus.admin.client.types.Project
import ch.epfl.bluebrain.nexus.iam.client.types._
import ch.epfl.bluebrain.nexus.kg.KgError.{InvalidOutputFormat, UnacceptedResponseContentType}
import ch.epfl.bluebrain.nexus.kg.archives.Archive._
import ch.epfl.bluebrain.nexus.kg.config.AppConfig
import ch.epfl.bluebrain.nexus.kg.directives.AuthDirectives.hasPermission
import ch.epfl.bluebrain.nexus.kg.directives.PathDirectives._
import ch.epfl.bluebrain.nexus.kg.directives.ProjectDirectives._
import ch.epfl.bluebrain.nexus.kg.directives.QueryDirectives.outputFormat
import ch.epfl.bluebrain.nexus.kg.marshallers.instances._
import ch.epfl.bluebrain.nexus.kg.resources._
import ch.epfl.bluebrain.nexus.kg.resources.syntax._
import ch.epfl.bluebrain.nexus.kg.routes.OutputFormat.Tar
import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri
import io.circe.Json
import kamon.instrumentation.akka.http.TracingDirectives.operationName
import monix.eval.Task
import monix.execution.Scheduler.Implicits.global

class ArchiveRoutes private[routes] (archives: Archives[Task])(
    implicit acls: AccessControlLists,
    project: Project,
    caller: Caller,
    config: AppConfig
) {

  private val responseType = MediaTypes.`application/x-tar`

  
  def routes(id: AbsoluteIri): Route = {
    val resId = Id(project.ref, id)
    concat(
      // Create archive
      (put & pathEndOrSingleSlash) {
        operationName(s"/${config.http.prefix}/archives/{org}/{project}/{id}") {
          (hasPermission(write) & projectNotDeprecated) {
            entity(as[Json]) { source =>
              complete(archives.create(resId, source).value.runWithStatus(Created))
            }
          }
        }
      },
      // Fetch archive
      (get & outputFormat(strict = true, Tar) & pathEndOrSingleSlash) {
        case Tar                           => getArchive(resId)
        case format: NonBinaryOutputFormat => getResource(resId)(format)
        case other                         => failWith(InvalidOutputFormat(other.toString))

      }
    )
  }

  private def getResource(resId: ResId)(implicit format: NonBinaryOutputFormat): Route =
    completeWithFormat(archives.fetch(resId).value.runWithStatus(OK))

  private def getArchive(resId: ResId): Route = {
    parameter("ignoreNotFound".as[Boolean] ? false) { ignoreNotFound =>
      onSuccess(archives.fetchArchive(resId, ignoreNotFound).value.runToFuture) {
        case Right(source) =>
          headerValueByType[Accept](()) { accept =>
            if (accept.mediaRanges.exists(_.matches(responseType)))
              complete(HttpEntity(responseType, source))
            else
              failWith(
                UnacceptedResponseContentType(
                  s"File Media Type '$responseType' does not match the Accept header value '${accept.mediaRanges.mkString(", ")}'"
                )
              )
          }
        case Left(err) => complete(err)
      }
    }
  }
}

object ArchiveRoutes {
  final def apply(archives: Archives[Task])(
      implicit acls: AccessControlLists,
      caller: Caller,
      project: Project,
      config: AppConfig
  ): ArchiveRoutes = new ArchiveRoutes(archives)
} 
Example 3
Source File: TagRoutes.scala    From nexus-kg   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.kg.routes

import akka.http.scaladsl.model.StatusCodes.{Created, OK}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import ch.epfl.bluebrain.nexus.admin.client.types.Project
import ch.epfl.bluebrain.nexus.iam.client.types._
import ch.epfl.bluebrain.nexus.kg.config.AppConfig
import ch.epfl.bluebrain.nexus.kg.config.Contexts.tagCtxUri
import ch.epfl.bluebrain.nexus.kg.config.Vocabulary.nxv
import ch.epfl.bluebrain.nexus.kg.directives.AuthDirectives._
import ch.epfl.bluebrain.nexus.kg.directives.ProjectDirectives._
import ch.epfl.bluebrain.nexus.kg.marshallers.instances._
import ch.epfl.bluebrain.nexus.kg.resources._
import ch.epfl.bluebrain.nexus.kg.resources.syntax._
import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri
import ch.epfl.bluebrain.nexus.rdf.implicits._
import io.circe.syntax._
import io.circe.{Encoder, Json}
import kamon.Kamon
import kamon.instrumentation.akka.http.TracingDirectives.operationName
import monix.eval.Task
import monix.execution.Scheduler.Implicits.global

class TagRoutes private[routes] (resourceType: String, tags: Tags[Task], schema: Ref, write: Permission)(
    implicit acls: AccessControlLists,
    caller: Caller,
    project: Project,
    config: AppConfig
) {

  
  def routes(id: AbsoluteIri): Route =
    // Consume the tag segment
    pathPrefix("tags") {
      concat(
        // Create tag
        (post & parameter("rev".as[Long]) & pathEndOrSingleSlash) { rev =>
          operationName(opName) {
            (hasPermission(write) & projectNotDeprecated) {
              entity(as[Json]) { source =>
                Kamon.currentSpan().tag("resource.operation", "create")
                complete(tags.create(Id(project.ref, id), rev, source, schema).value.runWithStatus(Created))
              }
            }
          }
        },
        // Fetch a tag
        (get & projectNotDeprecated & pathEndOrSingleSlash) {
          operationName(opName) {
            hasPermission(read).apply {
              parameter("rev".as[Long].?) {
                case Some(rev) => complete(tags.fetch(Id(project.ref, id), rev, schema).value.runWithStatus(OK))
                case _         => complete(tags.fetch(Id(project.ref, id), schema).value.runWithStatus(OK))
              }
            }
          }
        }
      )
    }

  private implicit def tagsEncoder: Encoder[TagSet] =
    Encoder.instance(tags => Json.obj(nxv.tags.prefix -> Json.arr(tags.map(_.asJson).toSeq: _*)).addContext(tagCtxUri))

  private def opName: String = resourceType match {
    case "resources" => s"/${config.http.prefix}/resources/{org}/{project}/{schemaId}/{id}/tags"
    case _           => s"/${config.http.prefix}/$resourceType/{org}/{project}/{id}/tags"
  }
} 
Example 4
Source File: Api.scala    From streamee   with Apache License 2.0 5 votes vote down vote up
package io.moia.streamee.demo

import akka.Done
import akka.actor.{ CoordinatedShutdown, ActorSystem => ClassicSystem }
import akka.actor.CoordinatedShutdown.{ PhaseServiceUnbind, Reason }
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.StatusCodes.{ BadRequest, InternalServerError, OK }
import akka.http.scaladsl.server.Route
import io.moia.streamee.FrontProcessor
import org.slf4j.LoggerFactory
import scala.concurrent.duration.FiniteDuration
import scala.util.{ Failure, Success }

object Api {

  type TextShufflerProcessor =
    FrontProcessor[TextShuffler.ShuffleText, Either[TextShuffler.Error, TextShuffler.TextShuffled]]

  final case class Config(interface: String, port: Int, terminationDeadline: FiniteDuration)

  private final object BindFailure extends Reason

  private val logger = LoggerFactory.getLogger(getClass)

  def apply(config: Config, textShufflerProcessor: TextShufflerProcessor)(implicit
      classicSystem: ClassicSystem
  ): Unit = {
    import FrontProcessor.processorUnavailableHandler
    import classicSystem.dispatcher
    import config._

    val shutdown = CoordinatedShutdown(classicSystem)

    Http()
      .bindAndHandle(route(textShufflerProcessor), interface, port)
      .onComplete {
        case Failure(cause) =>
          if (logger.isErrorEnabled)
            logger.error(s"Shutting down, because cannot bind to $interface:$port!", cause)
          shutdown.run(BindFailure)

        case Success(binding) =>
          if (logger.isInfoEnabled)
            logger.info(s"Listening for HTTP connections on ${binding.localAddress}")
          shutdown.addTask(PhaseServiceUnbind, "api.unbind") { () =>
            binding.terminate(terminationDeadline).map(_ => Done)
          }
      }
  }

  def route(textShufflerProcessor: TextShufflerProcessor): Route = {
    import akka.http.scaladsl.server.Directives._
    import de.heikoseeberger.akkahttpcirce.ErrorAccumulatingCirceSupport._
    import io.circe.generic.auto._

    pathSingleSlash {
      get {
        complete {
          OK
        }
      }
    } ~
    path("shuffle") {
      import TextShuffler._
      post {
        entity(as[ShuffleText]) { shuffleText =>
          onSuccess(textShufflerProcessor.offer(shuffleText)) {
            case Left(Error.EmptyText)                 => complete(BadRequest -> "Empty text!")
            case Left(Error.InvalidText)               => complete(BadRequest -> "Invalid text!")
            case Left(Error.RandomError)               => complete(InternalServerError -> "Random error!")
            case Left(Error.EmptyWordSeq)              => complete(InternalServerError -> "Words empty!")
            case Right(TextShuffled(original, result)) => complete(s"$original -> $result")
          }
        }
      }
    }
  }
} 
Example 5
Source File: MetricsRoute.scala    From vamp   with Apache License 2.0 5 votes vote down vote up
package io.vamp.http_api

import akka.http.scaladsl.model.StatusCodes.{ NotFound, OK }
import akka.http.scaladsl.server.Route
import akka.util.Timeout
import io.vamp.common.Namespace
import io.vamp.common.http.HttpApiDirectives
import io.vamp.operation.controller.MetricsController

import io.vamp.model.artifact.{ Gateway, Deployment }

object MetricsRoute {
  val path = "metrics"
}

trait MetricsRoute extends AbstractRoute with MetricsController {
  this: HttpApiDirectives ⇒

  def metricsRoutes(implicit namespace: Namespace, timeout: Timeout): Route = pathPrefix(MetricsRoute.path) {
    get {
      parameters("window".?) { window ⇒
        path(Gateway.kind / Segment / Segment) { (gateway, metrics) ⇒
          pathEndOrSingleSlash {
            onSuccess(gatewayMetrics(gateway, metrics)(window)) {
              case Some(result) ⇒ respondWith(OK, result)
              case _            ⇒ respondWith(NotFound, None)
            }
          }
        } ~ path(Gateway.kind / Segment / "routes" / Segment / Segment) { (gateway, route, metrics) ⇒
          pathEndOrSingleSlash {
            onSuccess(routeMetrics(gateway, route, metrics)(window)) {
              case Some(result) ⇒ respondWith(OK, result)
              case _            ⇒ respondWith(NotFound, None)
            }
          }
        } ~ path(Deployment.kind / Segment / "clusters" / Segment / "ports" / Segment / Segment) { (deployment, cluster, port, metrics) ⇒
          pathEndOrSingleSlash {
            onSuccess(clusterMetrics(deployment, cluster, port, metrics)(window)) {
              case Some(result) ⇒ respondWith(OK, result)
              case _            ⇒ respondWith(NotFound, None)
            }
          }
        } ~ path(Deployment.kind / Segment / "clusters" / Segment / "services" / Segment / "ports" / Segment / Segment) { (deployment, cluster, service, port, metrics) ⇒
          pathEndOrSingleSlash {
            onSuccess(serviceMetrics(deployment, cluster, service, port, metrics)(window)) {
              case Some(result) ⇒ respondWith(OK, result)
              case _            ⇒ respondWith(NotFound, None)
            }
          }
        } ~ path(Deployment.kind / Segment / "clusters" / Segment / "services" / Segment / "instances" / Segment / "ports" / Segment / Segment) { (deployment, cluster, service, instance, port, metrics) ⇒
          pathEndOrSingleSlash {
            onSuccess(instanceMetrics(deployment, cluster, service, instance, port, metrics)(window)) {
              case Some(result) ⇒ respondWith(OK, result)
              case _            ⇒ respondWith(NotFound, None)
            }
          }
        }
      }
    }
  }
} 
Example 6
Source File: HealthRoute.scala    From vamp   with Apache License 2.0 5 votes vote down vote up
package io.vamp.http_api

import akka.http.scaladsl.model.StatusCodes.{ NotFound, OK }
import akka.http.scaladsl.server.Route
import akka.util.Timeout
import io.vamp.common.Namespace
import io.vamp.common.http.HttpApiDirectives
import io.vamp.operation.controller.HealthController

import io.vamp.model.artifact.{ Gateway, Deployment }

object HealthRoute {
  val path = "health"
}

trait HealthRoute extends AbstractRoute with HealthController {
  this: HttpApiDirectives ⇒

  def healthRoutes(implicit namespace: Namespace, timeout: Timeout): Route = pathPrefix(HealthRoute.path) {
    get {
      parameters("window".?) { window ⇒
        path(Gateway.kind / Segment) { gateway ⇒
          pathEndOrSingleSlash {
            onSuccess(gatewayHealth(gateway)(window)) {
              case Some(result) ⇒ respondWith(OK, result)
              case _            ⇒ respondWith(NotFound, None)
            }
          }
        } ~ path(Gateway.kind / Segment / "routes" / Segment) { (gateway, route) ⇒
          pathEndOrSingleSlash {
            onSuccess(routeHealth(gateway, route)(window)) {
              case Some(result) ⇒ respondWith(OK, result)
              case _            ⇒ respondWith(NotFound, None)
            }
          }
        } ~ path(Deployment.kind / Segment) { deployment ⇒
          pathEndOrSingleSlash {
            onSuccess(deploymentHealth(deployment)(window)) {
              case Some(result) ⇒ respondWith(OK, result)
              case _            ⇒ respondWith(NotFound, None)
            }
          }
        } ~ path(Deployment.kind / Segment / "clusters" / Segment) { (deployment, cluster) ⇒
          pathEndOrSingleSlash {
            onSuccess(clusterHealth(deployment, cluster)(window)) {
              case Some(result) ⇒ respondWith(OK, result)
              case _            ⇒ respondWith(NotFound, None)
            }
          }
        } ~ path(Deployment.kind / Segment / "clusters" / Segment / "services" / Segment) { (deployment, cluster, service) ⇒
          pathEndOrSingleSlash {
            onSuccess(serviceHealth(deployment, cluster, service)(window)) {
              case Some(result) ⇒ respondWith(OK, result)
              case _            ⇒ respondWith(NotFound, None)
            }
          }
        } ~ path(Deployment.kind / Segment / "clusters" / Segment / "services" / Segment / "instances" / Segment) { (deployment, cluster, service, instance) ⇒
          pathEndOrSingleSlash {
            onSuccess(instanceHealth(deployment, cluster, service, instance)(window)) {
              case Some(result) ⇒ respondWith(OK, result)
              case _            ⇒ respondWith(NotFound, None)
            }
          }
        }
      }
    }
  }
} 
Example 7
Source File: InfoRoute.scala    From vamp   with Apache License 2.0 5 votes vote down vote up
package io.vamp.http_api

import akka.http.scaladsl.model.StatusCodes.{ InternalServerError, OK }
import akka.util.Timeout
import io.vamp.common.Namespace
import io.vamp.common.akka._
import io.vamp.common.http.HttpApiDirectives
import io.vamp.operation.controller.InfoController

trait InfoRoute extends AbstractRoute with InfoController with ExecutionContextProvider {
  this: HttpApiDirectives ⇒

  def infoRoute(implicit namespace: Namespace, timeout: Timeout) = pathPrefix("information" | "info") {
    pathEndOrSingleSlash {
      get {
        parameterMultiMap { parameters ⇒
          onSuccess(infoMessage(parameters.getOrElse("on", Nil).toSet)) {
            case (result, succeeded) ⇒ respondWith(if (succeeded) OK else InternalServerError, result)
          }
        }
      }
    }
  }
} 
Example 8
Source File: StatsRoute.scala    From vamp   with Apache License 2.0 5 votes vote down vote up
package io.vamp.http_api

import akka.http.scaladsl.model.StatusCodes.OK
import akka.util.Timeout
import io.vamp.common.Namespace
import io.vamp.common.http.HttpApiDirectives
import io.vamp.operation.controller.StatsController

trait StatsRoute extends AbstractRoute with StatsController {
  this: HttpApiDirectives ⇒

  def statsRoute(implicit namespace: Namespace, timeout: Timeout) = pathPrefix("stats" | "statistics") {
    pathEndOrSingleSlash {
      get {
        onSuccess(stats()) { result ⇒
          respondWith(OK, result)
        }
      }
    }
  }
} 
Example 9
Source File: SchedulerRoute.scala    From vamp   with Apache License 2.0 5 votes vote down vote up
package io.vamp.http_api

import akka.http.scaladsl.model.StatusCodes.OK
import akka.http.scaladsl.server.Route
import akka.util.Timeout
import io.vamp.common.Namespace
import io.vamp.common.akka._
import io.vamp.common.http.HttpApiDirectives
import io.vamp.operation.controller.SchedulerController

object SchedulerRoute {
  val path: String = "scheduler"
}

trait SchedulerRoute extends AbstractRoute with SchedulerController with ExecutionContextProvider {
  this: HttpApiDirectives ⇒

  def schedulerRoutes(implicit namespace: Namespace, timeout: Timeout): Route = get {
    pathPrefix(SchedulerRoute.path) {
      path("nodes") {
        pageAndPerPage() { (page, perPage) ⇒
          onSuccess(nodes(page, perPage)) {
            result ⇒ respondWith(OK, result)
          }
        }
      } ~ path("routing") {
        pageAndPerPage() { (page, perPage) ⇒
          parameters('selector.?) { selector ⇒
            onSuccess(routing(selector)(page, perPage)) {
              result ⇒ respondWith(OK, result)
            }
          }
        }
      }
    }
  }
} 
Example 10
Source File: ApiGwRestEndToEndTests.scala    From openwhisk   with Apache License 2.0 5 votes vote down vote up
package apigw.healthtests

import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter

import akka.http.scaladsl.model.StatusCodes.OK

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

import common.TestUtils._
import common.rest.WskRestOperations
import common.rest.RestResult
import common.WskActorSystem

@RunWith(classOf[JUnitRunner])
class ApiGwRestEndToEndTests extends ApiGwEndToEndTests with WskActorSystem {

  override lazy val wsk = new WskRestOperations
  override val createCode = OK.intValue

  override def verifyAPICreated(rr: RunResult): Unit = {
    val apiResultRest = rr.asInstanceOf[RestResult]
    apiResultRest.statusCode shouldBe OK
    val apiurl = apiResultRest.getField("gwApiUrl") + "/path"
    println(s"apiurl: '$apiurl'")
  }

  override def verifyAPIList(rr: RunResult,
                             actionName: String,
                             testurlop: String,
                             testapiname: String,
                             testbasepath: String,
                             testrelpath: String): Unit = {
    val apiResultRest = rr.asInstanceOf[RestResult]
    val apiValue = RestResult.getFieldJsObject(apiResultRest.getFieldListJsObject("apis")(0), "value")
    val apidoc = RestResult.getFieldJsObject(apiValue, "apidoc")
    val basepath = RestResult.getField(apidoc, "basePath")
    basepath shouldBe testbasepath

    val paths = RestResult.getFieldJsObject(apidoc, "paths")
    paths.fields.contains(testrelpath) shouldBe true

    val info = RestResult.getFieldJsObject(apidoc, "info")
    val title = RestResult.getField(info, "title")
    title shouldBe testapiname

    val relpath = RestResult.getFieldJsObject(paths, testrelpath)
    val urlop = RestResult.getFieldJsObject(relpath, testurlop)
    val openwhisk = RestResult.getFieldJsObject(urlop, "x-openwhisk")
    val actionN = RestResult.getField(openwhisk, "action")
    actionN shouldBe actionName
  }

  override def verifyAPISwaggerCreated(rr: RunResult): Unit = {
    val apiResultRest = rr.asInstanceOf[RestResult]
    apiResultRest.statusCode shouldBe OK
  }

  override def writeSwaggerFile(rr: RunResult): File = {
    val swaggerfile = File.createTempFile("api", ".json")
    swaggerfile.deleteOnExit()
    val bw = new BufferedWriter(new FileWriter(swaggerfile))
    val apiResultRest = rr.asInstanceOf[RestResult]
    val apiValue = RestResult.getFieldJsObject(apiResultRest.getFieldListJsObject("apis")(0), "value")
    val apidoc = RestResult.getFieldJsObject(apiValue, "apidoc")
    bw.write(apidoc.toString())
    bw.close()
    swaggerfile
  }

  override def getSwaggerApiUrl(rr: RunResult): String = {
    val apiResultRest = rr.asInstanceOf[RestResult]
    apiResultRest.getField("gwApiUrl") + "/path"
  }
} 
Example 11
Source File: ArchiveRoutes.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.kg.routes

import akka.http.scaladsl.model.StatusCodes.{Created, OK}
import akka.http.scaladsl.model.headers.Accept
import akka.http.scaladsl.model.{HttpEntity, MediaTypes}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import ch.epfl.bluebrain.nexus.admin.client.types.Project
import ch.epfl.bluebrain.nexus.iam.acls.Acls
import ch.epfl.bluebrain.nexus.iam.realms.Realms
import ch.epfl.bluebrain.nexus.iam.types.Caller
import ch.epfl.bluebrain.nexus.iam.types.Identity.Subject
import ch.epfl.bluebrain.nexus.kg.KgError.{InvalidOutputFormat, UnacceptedResponseContentType}
import ch.epfl.bluebrain.nexus.kg.archives.Archive._
import ch.epfl.bluebrain.nexus.kg.directives.PathDirectives._
import ch.epfl.bluebrain.nexus.kg.directives.ProjectDirectives._
import ch.epfl.bluebrain.nexus.kg.directives.QueryDirectives.outputFormat
import ch.epfl.bluebrain.nexus.kg.marshallers.instances._
import ch.epfl.bluebrain.nexus.kg.resources._
import ch.epfl.bluebrain.nexus.kg.resources.syntax._
import ch.epfl.bluebrain.nexus.kg.routes.OutputFormat.Tar
import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri
import ch.epfl.bluebrain.nexus.rdf.Iri.Path._
import ch.epfl.bluebrain.nexus.service.config.ServiceConfig
import ch.epfl.bluebrain.nexus.service.directives.AuthDirectives
import io.circe.Json
import kamon.instrumentation.akka.http.TracingDirectives.operationName
import monix.eval.Task
import monix.execution.Scheduler.Implicits.global

class ArchiveRoutes private[routes] (archives: Archives[Task], acls: Acls[Task], realms: Realms[Task])(implicit
    project: Project,
    caller: Caller,
    config: ServiceConfig
) extends AuthDirectives(acls, realms) {

  private val responseType              = MediaTypes.`application/x-tar`
  private val projectPath               = project.organizationLabel / project.label
  implicit private val subject: Subject = caller.subject

  
  def routes(id: AbsoluteIri): Route = {
    val resId = Id(project.ref, id)
    concat(
      // Create archive
      (put & pathEndOrSingleSlash) {
        operationName(s"/${config.http.prefix}/archives/{org}/{project}/{id}") {
          (authorizeFor(projectPath, write) & projectNotDeprecated) {
            entity(as[Json]) { source =>
              complete(archives.create(resId, source).value.runWithStatus(Created))
            }
          }
        }
      },
      // Fetch archive
      (get & outputFormat(strict = true, Tar) & pathEndOrSingleSlash) {
        case Tar                           => getArchive(resId)
        case format: NonBinaryOutputFormat => getResource(resId)(format)
        case other                         => failWith(InvalidOutputFormat(other.toString))

      }
    )
  }

  private def getResource(resId: ResId)(implicit format: NonBinaryOutputFormat): Route =
    completeWithFormat(archives.fetch(resId).value.runWithStatus(OK))

  private def getArchive(resId: ResId): Route = {
    (parameter("ignoreNotFound".as[Boolean] ? false) & extractCallerAcls(anyProject)) { (ignoreNotFound, acls) =>
      onSuccess(archives.fetchArchive(resId, ignoreNotFound)(acls, caller).value.runToFuture) {
        case Right(source) =>
          headerValueByType[Accept](()) { accept =>
            if (accept.mediaRanges.exists(_.matches(responseType)))
              complete(HttpEntity(responseType, source))
            else
              failWith(
                UnacceptedResponseContentType(
                  s"File Media Type '$responseType' does not match the Accept header value '${accept.mediaRanges.mkString(", ")}'"
                )
              )
          }
        case Left(err)     => complete(err)
      }
    }
  }
} 
Example 12
Source File: TagRoutes.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.kg.routes

import akka.http.scaladsl.model.StatusCodes.{Created, OK}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import ch.epfl.bluebrain.nexus.admin.client.types.Project
import ch.epfl.bluebrain.nexus.iam.acls.Acls
import ch.epfl.bluebrain.nexus.iam.realms.Realms
import ch.epfl.bluebrain.nexus.iam.types.Identity.Subject
import ch.epfl.bluebrain.nexus.iam.types.{Caller, Permission}
import ch.epfl.bluebrain.nexus.kg.config.Contexts.tagCtxUri
import ch.epfl.bluebrain.nexus.kg.directives.ProjectDirectives._
import ch.epfl.bluebrain.nexus.kg.marshallers.instances._
import ch.epfl.bluebrain.nexus.kg.resources._
import ch.epfl.bluebrain.nexus.kg.resources.syntax._
import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri
import ch.epfl.bluebrain.nexus.rdf.Iri.Path._
import ch.epfl.bluebrain.nexus.rdf.implicits._
import ch.epfl.bluebrain.nexus.service.config.ServiceConfig
import ch.epfl.bluebrain.nexus.service.directives.AuthDirectives
import io.circe.syntax._
import io.circe.{Encoder, Json}
import kamon.Kamon
import kamon.instrumentation.akka.http.TracingDirectives.operationName
import monix.eval.Task
import monix.execution.Scheduler.Implicits.global

class TagRoutes private[routes] (
    resourceType: String,
    tags: Tags[Task],
    acls: Acls[Task],
    realms: Realms[Task],
    schema: Ref,
    write: Permission
)(implicit
    caller: Caller,
    project: Project,
    config: ServiceConfig
) extends AuthDirectives(acls, realms) {

  private val projectPath               = project.organizationLabel / project.label
  implicit private val subject: Subject = caller.subject

  
  def routes(id: AbsoluteIri): Route =
    // Consume the tag segment
    pathPrefix("tags") {
      concat(
        // Create tag
        (post & parameter("rev".as[Long]) & pathEndOrSingleSlash) { rev =>
          operationName(opName) {
            (authorizeFor(projectPath, write) & projectNotDeprecated) {
              entity(as[Json]) { source =>
                Kamon.currentSpan().tag("resource.operation", "create")
                complete(tags.create(Id(project.ref, id), rev, source, schema).value.runWithStatus(Created))
              }
            }
          }
        },
        // Fetch a tag
        (get & projectNotDeprecated & pathEndOrSingleSlash) {
          operationName(opName) {
            authorizeFor(projectPath, read)(caller) {
              parameter("rev".as[Long].?) {
                case Some(rev) => complete(tags.fetch(Id(project.ref, id), rev, schema).value.runWithStatus(OK))
                case _         => complete(tags.fetch(Id(project.ref, id), schema).value.runWithStatus(OK))
              }
            }
          }
        }
      )
    }

  implicit private def tagsEncoder: Encoder[TagSet] =
    Encoder.instance(tags => Json.obj("tags" -> Json.arr(tags.map(_.asJson).toSeq: _*)).addContext(tagCtxUri))

  private def opName: String                        =
    resourceType match {
      case "resources" => s"/${config.http.prefix}/resources/{org}/{project}/{schemaId}/{id}/tags"
      case _           => s"/${config.http.prefix}/$resourceType/{org}/{project}/{id}/tags"
    }
} 
Example 13
Source File: ExpiresDirectiveSpec.scala    From akka-http-extensions   with Apache License 2.0 5 votes vote down vote up
package com.lonelyplanet.akka.http.extensions.directives

import akka.http.scaladsl.model.DateTime
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.{FlatSpec, Matchers}
import akka.http.scaladsl.server.Directives._
import ExpiresDirective._
import akka.http.scaladsl.model.StatusCodes.OK

class ExpiresDirectiveSpec extends FlatSpec with Matchers with ScalatestRouteTest {
  private val expirationDate = DateTime.now

  private val route = path("test") {
    expires(expirationDate) {
      complete {
        "OK"
      }
    }
  }

  "ExpiresDirective" should "set `Expires` header correctly" in {
    Get("/test") ~> route ~> check {
      status shouldBe OK
      responseAs[String] shouldBe "OK"
      header("Expires").get.value shouldBe expirationDate.toRfc1123DateTimeString
    }
  }
} 
Example 14
Source File: TopicResponse.scala    From sns   with Apache License 2.0 5 votes vote down vote up
package me.snov.sns.response

import java.util.UUID

import akka.http.scaladsl.model.StatusCodes.OK
import akka.http.scaladsl.model.HttpResponse
import me.snov.sns.model.Topic

object TopicResponse extends XmlHttpResponse {
  def delete = {
    response(
      OK,
      <DeleteTopicResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">
        <ResponseMetadata>
          <RequestId>
            {UUID.randomUUID}
          </RequestId>
        </ResponseMetadata>
      </DeleteTopicResponse>
    )
  }

  def create(topic: Topic): HttpResponse = {
    response(
      OK,
      <CreateTopicResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">
        <CreateTopicResult>
          <TopicArn>
            {topic.arn}
          </TopicArn>
        </CreateTopicResult>
        <ResponseMetadata>
          <RequestId>
            {UUID.randomUUID}
          </RequestId>
        </ResponseMetadata>
      </CreateTopicResponse>
    )
  }

  def list(topics: Iterable[Topic]): HttpResponse = {
    response(
      OK,
      <ListTopicsResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">
        <ListTopicsResult>
          <Topics>
            {topics.map(topic =>
            <member>
              <TopicArn>
                {topic.arn}
              </TopicArn>
            </member>
          )}
          </Topics>
        </ListTopicsResult>
        <ResponseMetadata>
          <RequestId>
            {UUID.randomUUID}
          </RequestId>
        </ResponseMetadata>
      </ListTopicsResponse>
    )
  }
} 
Example 15
Source File: LimitsApiTests.scala    From openwhisk   with Apache License 2.0 5 votes vote down vote up
package org.apache.openwhisk.core.controller.test

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import akka.http.scaladsl.model.StatusCodes.{BadRequest, MethodNotAllowed, OK}
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport.sprayJsonUnmarshaller
import akka.http.scaladsl.server.Route
import org.apache.openwhisk.core.controller.WhiskLimitsApi
import org.apache.openwhisk.core.entity.{EntityPath, UserLimits}


  behavior of "Limits API"

  // test namespace limit configurations
  val testInvokesPerMinute = 100
  val testConcurrent = 200
  val testFiresPerMinute = 300
  val testAllowedKinds = Set("java:8")
  val testStoreActivations = false

  val creds = WhiskAuthHelpers.newIdentity()
  val credsWithSetLimits = WhiskAuthHelpers
    .newIdentity()
    .copy(
      limits = UserLimits(
        Some(testInvokesPerMinute),
        Some(testConcurrent),
        Some(testFiresPerMinute),
        Some(testAllowedKinds),
        Some(testStoreActivations)))
  val namespace = EntityPath(creds.subject.asString)
  val collectionPath = s"/${EntityPath.DEFAULT}/${collection.path}"

  //// GET /limits
  it should "list default system limits if no namespace limits are set" in {
    implicit val tid = transid()
    Seq("", "/").foreach { p =>
      Get(collectionPath + p) ~> Route.seal(routes(creds)) ~> check {
        status should be(OK)
        responseAs[UserLimits].invocationsPerMinute shouldBe Some(whiskConfig.actionInvokePerMinuteLimit.toInt)
        responseAs[UserLimits].concurrentInvocations shouldBe Some(whiskConfig.actionInvokeConcurrentLimit.toInt)
        responseAs[UserLimits].firesPerMinute shouldBe Some(whiskConfig.triggerFirePerMinuteLimit.toInt)
        responseAs[UserLimits].allowedKinds shouldBe None
        responseAs[UserLimits].storeActivations shouldBe None
      }
    }
  }

  it should "list set limits if limits have been set for the namespace" in {
    implicit val tid = transid()
    Seq("", "/").foreach { p =>
      Get(collectionPath + p) ~> Route.seal(routes(credsWithSetLimits)) ~> check {
        status should be(OK)
        responseAs[UserLimits].invocationsPerMinute shouldBe Some(testInvokesPerMinute)
        responseAs[UserLimits].concurrentInvocations shouldBe Some(testConcurrent)
        responseAs[UserLimits].firesPerMinute shouldBe Some(testFiresPerMinute)
        responseAs[UserLimits].allowedKinds shouldBe Some(testAllowedKinds)
        responseAs[UserLimits].storeActivations shouldBe Some(testStoreActivations)
      }
    }
  }

  it should "reject requests for unsupported methods" in {
    implicit val tid = transid()
    Seq(Put, Post, Delete).foreach { m =>
      m(collectionPath) ~> Route.seal(routes(creds)) ~> check {
        status should be(MethodNotAllowed)
      }
    }
  }

  it should "reject all methods for entity level request" in {
    implicit val tid = transid()
    Seq(Put, Post, Delete).foreach { m =>
      m(s"$collectionPath/limitsEntity") ~> Route.seal(routes(creds)) ~> check {
        status should be(MethodNotAllowed)
      }
    }

    Seq(Get).foreach { m =>
      m(s"$collectionPath/limitsEntity") ~> Route.seal(routes(creds)) ~> check {
        status should be(BadRequest)
      }
    }
  }
} 
Example 16
Source File: RespondWithHeadersTests.scala    From openwhisk   with Apache License 2.0 5 votes vote down vote up
package org.apache.openwhisk.core.controller.test

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

import akka.http.scaladsl.model.StatusCodes.NotFound
import akka.http.scaladsl.model.StatusCodes.OK
import akka.http.scaladsl.server.Route

import org.apache.openwhisk.core.controller.RespondWithHeaders


@RunWith(classOf[JUnitRunner])
class RespondWithHeadersTests extends ControllerTestCommon with RespondWithHeaders {

  behavior of "General API"

  val routes = {
    pathPrefix("api" / "v1") {
      sendCorsHeaders {
        path("one") {
          complete(OK)
        } ~ path("two") {
          complete(OK)
        } ~ options {
          complete(OK)
        } ~ reject
      }
    } ~ pathPrefix("other") {
      complete(OK)
    }
  }

  it should "respond to options" in {
    Options("/api/v1") ~> Route.seal(routes) ~> check {
      headers should contain allOf (allowOrigin, allowHeaders)
    }
  }

  it should "respond to options on every route under /api/v1" in {
    Options("/api/v1/one") ~> Route.seal(routes) ~> check {
      headers should contain allOf (allowOrigin, allowHeaders)
    }
    Options("/api/v1/two") ~> Route.seal(routes) ~> check {
      headers should contain allOf (allowOrigin, allowHeaders)
    }
  }

  it should "respond to options even on bogus routes under /api/v1" in {
    Options("/api/v1/bogus") ~> Route.seal(routes) ~> check {
      headers should contain allOf (allowOrigin, allowHeaders)
    }
  }

  it should "not respond to options on routes before /api/v1" in {
    Options("/api") ~> Route.seal(routes) ~> check {
      status shouldBe NotFound
    }
  }

} 
Example 17
Source File: NamespacesApiTests.scala    From openwhisk   with Apache License 2.0 5 votes vote down vote up
package org.apache.openwhisk.core.controller.test

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

import akka.http.scaladsl.model.StatusCodes.OK
import akka.http.scaladsl.model.StatusCodes.NotFound
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport.sprayJsonUnmarshaller
import akka.http.scaladsl.server.Route

import spray.json.DefaultJsonProtocol._

import org.apache.openwhisk.core.controller.WhiskNamespacesApi
import org.apache.openwhisk.core.entity.EntityPath


  behavior of "Namespaces API"

  val collectionPath = s"/${collection.path}"
  val creds = WhiskAuthHelpers.newIdentity()
  val namespace = EntityPath(creds.subject.asString)

  it should "list namespaces for subject" in {
    implicit val tid = transid()
    Seq("", "/").foreach { p =>
      Get(collectionPath + p) ~> Route.seal(routes(creds)) ~> check {
        status should be(OK)
        val ns = responseAs[List[EntityPath]]
        ns should be(List(EntityPath(creds.subject.asString)))
      }
    }
  }

  it should "reject request for unsupported method" in {
    implicit val tid = transid()
    Seq(Get, Put, Post, Delete).foreach { m =>
      m(s"$collectionPath/${creds.subject}") ~> Route.seal(routes(creds)) ~> check {
        status should be(NotFound)
      }
    }
  }
}