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

The following examples show how to use akka.http.scaladsl.model.StatusCodes.BadRequest. 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: 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 2
Source File: PostActionActivation.scala    From openwhisk   with Apache License 2.0 5 votes vote down vote up
package org.apache.openwhisk.core.controller.actions

import scala.concurrent.Future
import scala.concurrent.duration.FiniteDuration

import akka.http.scaladsl.model.StatusCodes.BadRequest

import spray.json._

import org.apache.openwhisk.common.TransactionId
import org.apache.openwhisk.core.controller.RejectRequest
import org.apache.openwhisk.core.controller.WhiskServices
import org.apache.openwhisk.core.entity._
import org.apache.openwhisk.http.Messages

protected[core] trait PostActionActivation extends PrimitiveActions with SequenceActions {
  
  protected[controller] def invokeAction(
    user: Identity,
    action: WhiskActionMetaData,
    payload: Option[JsObject],
    waitForResponse: Option[FiniteDuration],
    cause: Option[ActivationId])(implicit transid: TransactionId): Future[Either[ActivationId, WhiskActivation]] = {
    action.toExecutableWhiskAction match {
      // this is a topmost sequence
      case None =>
        val SequenceExecMetaData(components) = action.exec
        invokeSequence(user, action, components, payload, waitForResponse, cause, topmost = true, 0).map(r => r._1)
      // a non-deprecated ExecutableWhiskAction
      case Some(executable) if !executable.exec.deprecated =>
        invokeSingleAction(user, executable, payload, waitForResponse, cause)
      // a deprecated exec
      case _ =>
        Future.failed(RejectRequest(BadRequest, Messages.runtimeDeprecated(action.exec)))
    }
  }
} 
Example 3
Source File: ProjectRejection.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.admin.projects

import java.util.UUID

import akka.http.scaladsl.model.StatusCodes.{BadRequest, Conflict, NotFound}
import ch.epfl.bluebrain.nexus.commons.http.directives.StatusFrom
import ch.epfl.bluebrain.nexus.rdf.implicits._
import ch.epfl.bluebrain.nexus.service.config.Contexts._
import ch.epfl.bluebrain.nexus.service.routes.ResourceRejection
import io.circe.generic.extras.Configuration
import io.circe.generic.extras.semiauto.deriveConfiguredEncoder
import io.circe.{Encoder, Json}

import scala.annotation.nowarn

sealed abstract class ProjectRejection(val msg: String) extends ResourceRejection

object ProjectRejection {

  
  final case class IncorrectRev(expected: Long, provided: Long)
      extends ProjectRejection(
        s"Incorrect revision '$provided' provided, expected '$expected', the project may have been updated since last seen."
      )

  @nowarn("cat=unused")
  implicit val projectRejectionEncoder: Encoder[ProjectRejection] = {
    implicit val rejectionConfig: Configuration = Configuration.default.withDiscriminator("@type")
    val enc                                     = deriveConfiguredEncoder[ProjectRejection].mapJson(_ addContext errorCtxUri)
    Encoder.instance(r => enc(r) deepMerge Json.obj("reason" -> Json.fromString(r.msg)))
  }

  implicit val projectStatusFrom: StatusFrom[ProjectRejection] = StatusFrom {
    case _: IncorrectRev             => Conflict
    case _: ProjectAlreadyExists     => Conflict
    case _: ProjectNotFound          => NotFound
    case _: OrganizationNotFound     => NotFound
    case _: ProjectIsDeprecated      => BadRequest
    case _: OrganizationIsDeprecated => BadRequest
    case _: InvalidProjectFormat     => BadRequest
  }

} 
Example 4
Source File: OrganizationRejection.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.admin.organizations

import java.util.UUID

import akka.http.scaladsl.model.StatusCodes.{BadRequest, Conflict, NotFound}
import ch.epfl.bluebrain.nexus.commons.http.directives.StatusFrom
import ch.epfl.bluebrain.nexus.rdf.implicits._
import ch.epfl.bluebrain.nexus.service.config.Contexts._
import ch.epfl.bluebrain.nexus.service.routes.ResourceRejection
import io.circe.generic.extras.Configuration
import io.circe.generic.extras.semiauto.deriveConfiguredEncoder
import io.circe.{Encoder, Json}

import scala.annotation.nowarn

sealed abstract class OrganizationRejection(val msg: String) extends ResourceRejection

object OrganizationRejection {

  
  final case class IncorrectRev(expected: Long, provided: Long)
      extends OrganizationRejection(
        s"Incorrect revision '$provided' provided, expected '$expected', the organization may have been updated since last seen."
      )

  @nowarn("cat=unused")
  implicit val organizationRejectionEncoder: Encoder[OrganizationRejection] = {
    implicit val rejectionConfig: Configuration = Configuration.default.withDiscriminator("@type")
    val enc                                     = deriveConfiguredEncoder[OrganizationRejection].mapJson(_ addContext errorCtxUri)
    Encoder.instance(r => enc(r) deepMerge Json.obj("reason" -> Json.fromString(r.msg)))
  }

  implicit val organizationStatusFrom: StatusFrom[OrganizationRejection] = StatusFrom {
    case _: IncorrectRev              => Conflict
    case _: OrganizationAlreadyExists => Conflict
    case _: OrganizationNotFound      => NotFound
    case _: InvalidOrganizationFormat => BadRequest
  }
} 
Example 5
Source File: AclRejection.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.iam.acls

import akka.http.scaladsl.model.StatusCodes.{BadRequest, Conflict, NotFound}
import ch.epfl.bluebrain.nexus.commons.http.directives.StatusFrom
import ch.epfl.bluebrain.nexus.iam.types.Permission
import ch.epfl.bluebrain.nexus.rdf.Iri.Path
import ch.epfl.bluebrain.nexus.rdf.implicits._
import ch.epfl.bluebrain.nexus.service.config.Contexts.errorCtxUri
import ch.epfl.bluebrain.nexus.service.routes.ResourceRejection
import io.circe.generic.extras.Configuration
import io.circe.generic.extras.semiauto.deriveConfiguredEncoder
import io.circe.{Encoder, Json}

import scala.annotation.nowarn

sealed abstract class AclRejection(val msg: String) extends ResourceRejection

object AclRejection {

  
  final case class UnknownPermissions(permissions: Set[Permission])
      extends AclRejection(
        s"Some of the permissions specified are not known: '${permissions.mkString("\"", ", ", "\"")}'"
      )

  @nowarn("cat=unused")
  implicit val aclRejectionEncoder: Encoder[AclRejection] = {
    implicit val rejectionConfig: Configuration = Configuration.default.withDiscriminator("@type")
    val enc                                     = deriveConfiguredEncoder[AclRejection].mapJson(_ addContext errorCtxUri)
    Encoder.instance(r => enc(r) deepMerge Json.obj("reason" -> Json.fromString(r.msg)))
  }

  implicit val aclRejectionStatusFrom: StatusFrom[AclRejection] =
    StatusFrom {
      case _: NothingToBeUpdated                        => BadRequest
      case _: AclIsEmpty                                => BadRequest
      case _: AclCannotContainEmptyPermissionCollection => BadRequest
      case _: AclNotFound                               => NotFound
      case _: IncorrectRev                              => Conflict
      case _: UnknownPermissions                        => BadRequest
    }
} 
Example 6
Source File: AclRejection.scala    From nexus-iam   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.iam.acls

import akka.http.scaladsl.model.StatusCodes.{BadRequest, Conflict, NotFound}
import ch.epfl.bluebrain.nexus.commons.http.directives.StatusFrom
import ch.epfl.bluebrain.nexus.iam.config.Contexts.errorCtxUri
import ch.epfl.bluebrain.nexus.iam.types.{Permission, ResourceRejection}
import ch.epfl.bluebrain.nexus.rdf.Iri.Path
import ch.epfl.bluebrain.nexus.rdf.implicits._
import com.github.ghik.silencer.silent
import io.circe.generic.extras.Configuration
import io.circe.generic.extras.semiauto.deriveConfiguredEncoder
import io.circe.{Encoder, Json}

sealed abstract class AclRejection(val msg: String) extends ResourceRejection

object AclRejection {

  
  final case class UnknownPermissions(permissions: Set[Permission])
      extends AclRejection(
        s"Some of the permissions specified are not known: '${permissions.mkString("\"", ", ", "\"")}'"
      )

  @silent // rejectionConfig is not recognized as being used
  implicit val aclRejectionEncoder: Encoder[AclRejection] = {
    implicit val rejectionConfig: Configuration = Configuration.default.withDiscriminator("@type")
    val enc                                     = deriveConfiguredEncoder[AclRejection].mapJson(_ addContext errorCtxUri)
    Encoder.instance(r => enc(r) deepMerge Json.obj("reason" -> Json.fromString(r.msg)))
  }

  implicit val aclRejectionStatusFrom: StatusFrom[AclRejection] =
    StatusFrom {
      case _: NothingToBeUpdated                        => BadRequest
      case _: AclIsEmpty                                => BadRequest
      case _: AclCannotContainEmptyPermissionCollection => BadRequest
      case _: AclNotFound                               => NotFound
      case _: IncorrectRev                              => Conflict
      case _: UnknownPermissions                        => BadRequest
    }
} 
Example 7
Source File: DataApi.scala    From NSDb   with Apache License 2.0 5 votes vote down vote up
package io.radicalbit.nsdb.web.routes

import javax.ws.rs.Path
import akka.actor.ActorRef
import akka.pattern.ask
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.StatusCodes.{BadRequest, InternalServerError}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import akka.util.Timeout
import io.radicalbit.nsdb.common.protocol.Bit
import io.radicalbit.nsdb.protocol.MessageProtocol.Commands.MapInput
import io.radicalbit.nsdb.protocol.MessageProtocol.Events.{InputMapped, RecordRejected}
import io.radicalbit.nsdb.security.http.NSDBAuthProvider
import io.radicalbit.nsdb.security.model.Metric
import io.swagger.annotations._
import org.json4s.Formats

import scala.annotation.meta.field
import scala.util.{Failure, Success}

@ApiModel(description = "Data insertion body")
case class InsertBody(@(ApiModelProperty @field)(value = "database name") db: String,
                      @(ApiModelProperty @field)(value = "namespace name") namespace: String,
                      @(ApiModelProperty @field)(value = "metric name") metric: String,
                      @(ApiModelProperty @field)(
                        value = "bit representing a single row"
                      ) bit: Bit)
    extends Metric

@Api(value = "/data", produces = "application/json")
@Path("/data")
trait DataApi {

  import io.radicalbit.nsdb.web.NSDbJson._
  import io.radicalbit.nsdb.web.validation.ValidationDirective._
  import io.radicalbit.nsdb.web.validation.Validators._

  def writeCoordinator: ActorRef
  def authenticationProvider: NSDBAuthProvider

  implicit val timeout: Timeout
  implicit val formats: Formats

  @ApiOperation(value = "Insert Bit", nickname = "insert", httpMethod = "POST", response = classOf[String])
  @ApiImplicitParams(
    Array(
      new ApiImplicitParam(name = "body",
                           value = "bit definition",
                           required = true,
                           dataTypeClass = classOf[InsertBody],
                           paramType = "body")
    ))
  @ApiResponses(
    Array(
      new ApiResponse(code = 500, message = "Internal server error"),
      new ApiResponse(code = 400, message = "insert statement is invalid")
    ))
  def dataApi: Route =
    pathPrefix("data") {
      post {
        entity(as[InsertBody]) { insertBody =>
          optionalHeaderValueByName(authenticationProvider.headerName) { header =>
            validateModel(insertBody).apply { validatedInsertBody =>
              authenticationProvider.authorizeMetric(ent = validatedInsertBody, header = header, writePermission = true) {
                onComplete(
                  writeCoordinator ? MapInput(validatedInsertBody.bit.timestamp,
                                              validatedInsertBody.db,
                                              validatedInsertBody.namespace,
                                              validatedInsertBody.metric,
                                              validatedInsertBody.bit)) {
                  case Success(_: InputMapped) =>
                    complete("OK")
                  case Success(RecordRejected(_, _, _, _, _, reasons, _)) =>
                    complete(HttpResponse(BadRequest, entity = reasons.mkString(",")))
                  case Success(_) =>
                    complete(HttpResponse(InternalServerError, entity = "unknown response"))
                  case Failure(ex) => complete(HttpResponse(InternalServerError, entity = ex.getMessage))
                }
              }
            }
          }
        }
      }
    }

} 
Example 8
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 9
Source File: package.scala    From typed-schema   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.tschema
import akka.http.scaladsl.model.StatusCodes.BadRequest
import akka.http.scaladsl.server.{Directives, Rejection, Route}

package object akkaHttp {
  def rejectionHandler: PartialFunction[Rejection, Route] = {
    case NotFoundPathRejection(name)               =>
      Directives.complete(BadRequest, s"could not find path parameter $name")
    case MalformedPathRejection(name, formatError) =>
      Directives.complete(BadRequest, s"could not parse path parameter $name : $formatError")
  }
}

package akkaHttp {
  final case class NotFoundPathRejection(name: String) extends Rejection
  final case class MalformedPathRejection(name: String, formatError: String) extends Rejection
}