play.api.mvc.Controller Scala Examples

The following examples show how to use play.api.mvc.Controller. 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: VirtualSourceController.scala    From DataQuality   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package controllers.sources

import javax.inject.Inject
import com.codahale.jerkson.Json.generate
import controllers.ControllerUtils._
import controllers.utils.MyDBSession
import controllers.utils.ValidationConstraints._
import models.sources._
import org.squeryl.PrimitiveTypeMode.inTransaction
import play.api.Play.current
import play.api.data.Form
import play.api.data.Forms.{mapping, optional, seq, text}
import play.api.i18n.Messages.Implicits._
import play.api.mvc.{Action, Controller}

import scala.util.Try


class VirtualSourceController @Inject()(session: MyDBSession) extends Controller {

  private def getVSRCForm(currId: Option[String] = None): Form[(Source, VirtualSource)] = {
    def valFunc: (String) => Boolean = (t:String) => inTransaction(validateId(t, Source.getIdList(), currId))
    def valSrc: (String) => Boolean = (t:String) => inTransaction(validateRefList(t, Source.getIdList()))

    Form(
      mapping(
        "id" -> text.verifying(errorUsed, valFunc),
        "keyFields" -> seq(text),
        "tipo" -> text,
        "left" -> text.verifying(errorNotFound("Source"), valSrc),
        "right" -> optional(text),
        "query" -> text
      )(VirtualSource.applyWithSource)(VirtualSource.unapplyWithSource)
    )
  }

  def addVSRC() = Action { implicit request =>
    val form = getVSRCForm().bindFromRequest
    form.value map { file =>
      try {
        inTransaction{
          file._1.insert()
          file._2.insert()
          val json = generate(VirtualSource.fileToMap(file))
          Ok(json).as(JSON)
        }
      } catch {
        case e: Exception => InternalServerError(e.toString)
      }
    } getOrElse BadRequest(form.errorsAsJson).as(JSON)
  }

  def getVSRCDetails(id: String) = Action {
    inTransaction{ Try{
      val file: (Source, VirtualSource) = VirtualSource.getDetailed(id)
      generate(VirtualSource.fileToMap(file))
    }.toOption match {
      case Some(json) => Ok(json).as(JSON)
      case None =>
        val json = generate(Map("error" -> "Virtual source not found!"))
        BadRequest(json).as(JSON)
    }}
  }

  def updateVSRC(id: String) = Action { implicit request =>
    val form = getVSRCForm(Some(id)).bindFromRequest
    form.value map { file =>
      inTransaction(try {
        file._1.id match {
          case `id` =>
            file._1.update()
            file._2.update()
          case _ =>
            file._1.insert()
            file._2.rebase(id)
        }
        val json = generate(VirtualSource.fileToMap(file))
        Ok(json).as(JSON)
      } catch {
        case e: Exception => InternalServerError(e.toString)
      })
    } getOrElse BadRequest(form.errorsAsJson).as(JSON)
  }

} 
Example 2
Source File: AboutController.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.controllers

import javax.inject.Inject

import de.frosner.broccoli.auth.Account
import de.frosner.broccoli.services._
import de.frosner.broccoli.conf
import de.frosner.broccoli.models.AboutInfo.aboutInfoWrites
import jp.t2v.lab.play2.auth.BroccoliSimpleAuthorization
import play.api.Environment
import play.api.cache.CacheApi
import play.api.libs.json.{JsBoolean, JsObject, JsString, Json}
import play.api.mvc.{Action, AnyContent, Controller}

case class AboutController @Inject()(
    aboutInfoService: AboutInfoService,
    override val securityService: SecurityService,
    override val cacheApi: CacheApi,
    override val playEnv: Environment
) extends Controller
    with BroccoliSimpleAuthorization {

  def about = StackAction(parse.empty) { implicit request =>
    Ok(Json.toJson(AboutController.about(aboutInfoService, loggedIn)))
  }

}

object AboutController {

  def about(aboutInfoService: AboutInfoService, loggedIn: Account) =
    aboutInfoService.aboutInfo(loggedIn)

} 
Example 3
Source File: SecurityController.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.controllers

import javax.inject.Inject

import cats.data.{EitherT, OptionT}
import cats.instances.future._
import cats.syntax.either._
import com.mohiva.play.silhouette.api.util.Credentials
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import de.frosner.broccoli.services.{SecurityService, WebSocketService}
import jp.t2v.lab.play2.auth.{BroccoliSimpleAuthorization, LoginLogout}
import play.api.{Environment, Logger}
import play.api.cache.CacheApi
import play.api.data.Forms._
import play.api.data._
import play.api.libs.json.Json
import play.api.mvc.{Action, AnyContent, Controller, Results}

import scala.concurrent.Future

case class SecurityController @Inject()(
    override val securityService: SecurityService,
    override val cacheApi: CacheApi,
    override val playEnv: Environment,
    webSocketService: WebSocketService
) extends Controller
    with LoginLogout
    with BroccoliSimpleAuthorization {

  private val log = Logger(getClass)

  import scala.concurrent.ExecutionContext.Implicits.global

  // https://www.playframework.com/documentation/2.5.x/ScalaForms
  val loginForm = Form {
    mapping(
      SecurityController.UsernameFormKey -> text,
      SecurityController.PasswordFormKey -> text
    )(Credentials.apply)(Credentials.unapply)
  }

  def login: Action[AnyContent] = Action.async { implicit request =>
    getSessionId(request).map(id => (id, webSocketService.closeConnections(id))) match {
      case Some((id, true)) => log.info(s"Removing websocket connection of $id due to another login")
      case _                =>
    }
    (for {
      credentials <- EitherT.fromEither[Future](
        loginForm.bindFromRequest().fold(Function.const(Results.BadRequest.asLeft), _.asRight))
      login <- OptionT(securityService.authenticate(credentials)).toRight(Results.Unauthorized)
      result <- EitherT.right(gotoLoginSucceeded(login.providerKey))
      user <- OptionT(resolveUser(login.providerKey)).toRight(Results.Unauthorized)
    } yield {
      val userResult = Results.Ok(Json.toJson(user))
      result.copy(
        header = result.header.copy(
          headers = userResult.header.headers
            .get("Content-Type")
            .map { contentType =>
              result.header.headers.updated("Content-Type", contentType)
            }
            .getOrElse(result.header.headers)
        ),
        body = userResult.body
      )
    }).merge
  }

  def logout = Action.async(parse.empty) { implicit request =>
    gotoLogoutSucceeded.andThen {
      case tryResult =>
        getSessionId(request).map(id => (id, webSocketService.closeConnections(id))) match {
          case Some((id, true))  => log.info(s"Removing websocket connection of $id due to logout")
          case Some((id, false)) => log.info(s"There was no websocket connection for session $id")
          case None              => log.info(s"No session available to logout from")
        }
    }
  }

  def verify = StackAction(parse.empty) { implicit request =>
    Ok(loggedIn.name)
  }

}

object SecurityController {

  val UsernameFormKey = "username"
  val PasswordFormKey = "password"

} 
Example 4
Source File: BroccoliSimpleAuthorization.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package jp.t2v.lab.play2.auth

import de.frosner.broccoli.auth.{Account, AuthMode}
import de.frosner.broccoli.conf
import de.frosner.broccoli.controllers.AuthConfigImpl
import de.frosner.broccoli.services.SecurityService
import jp.t2v.lab.play2.stackc.{RequestAttributeKey, RequestWithAttributes, StackableController}
import play.api.mvc.{Controller, RequestHeader, Result}

import scala.concurrent.Future

trait BroccoliSimpleAuthorization extends StackableController with AsyncAuth with AuthConfigImpl {

  self: Controller with AuthConfig =>

  val securityService: SecurityService

  private[auth] case object AuthKey extends RequestAttributeKey[User]

  override def proceed[A](req: RequestWithAttributes[A])(
      f: RequestWithAttributes[A] => Future[Result]): Future[Result] = {
    implicit val (r, ctx) = (req, StackActionExecutionContext(req))
    securityService.authMode match {
      case AuthMode.Conf => {
        restoreUser recover {
          case _ => None -> identity[Result] _
        } flatMap {
          case (Some(u), cookieUpdater) => super.proceed(req.set(AuthKey, u))(f).map(cookieUpdater)
          case (None, _)                => authenticationFailed(req)
        }
      }
      case AuthMode.None => {
        super.proceed(req)(f)
      }
    }
  }

  implicit def loggedIn(implicit req: RequestWithAttributes[_]): User = securityService.authMode match {
    case AuthMode.Conf => req.get(AuthKey).get
    case AuthMode.None => Account.anonymous
  }

  def getSessionId(request: RequestHeader): Option[AuthenticityToken] = extractToken(request)

} 
Example 5
Source File: TrafficHandler.scala    From CM-Well   with Apache License 2.0 5 votes vote down vote up
package trafficshaping

import com.typesafe.scalalogging.LazyLogging
import k.grid.dmap.impl.persistent.PersistentDMap
import play.api.mvc.{Action, Controller, InjectedController}
import DMapKeys._
import k.grid.dmap.api.SettingsLong
import security.AuthUtils
import javax.inject._

import filters.Attrs

import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}


@Singleton
class TrafficHandler @Inject()(authUtils: AuthUtils)(implicit ec: ExecutionContext)
    extends InjectedController
    with LazyLogging {
  // todo: remove this.
  def handleTimeout = Action.async { implicit originalRequest =>
    cmwell.util.concurrent.delayedTask(5.seconds)(Future.successful(Ok)).flatMap(identity)
  }

  def handleThresholdFactor = Action { implicit req =>
    val tokenOpt = authUtils.extractTokenFrom(req)
    if (authUtils.isOperationAllowedForUser(security.Admin, tokenOpt)) {
      val thresholdFactor = req.getQueryString("tf").map(_.toLong)
      thresholdFactor match {
        case Some(l) =>
          PersistentDMap.set(THRESHOLD_FACTOR, SettingsLong(l))
          Ok(s"Changed Threshold factor to $l")
        case None =>
          val curValOpt = PersistentDMap.get(THRESHOLD_FACTOR).flatMap(_.as[Long])
          curValOpt match {
            case Some(curVal) if curVal > 0L =>
              Ok(s"""Please provide the parameter "tf". The current value is: $curVal""")
            case _ => Ok(s"""Traffic shaping is disabled. Please provide the parameter "tf" in order to activate it.""")
          }
      }
    } else Forbidden("not authorized")
  }
} 
Example 6
Source File: Callback.scala    From auth0-scala-samples   with MIT License 5 votes vote down vote up
package controllers

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import javax.inject.Inject
import play.api.cache._
import play.api.http.HeaderNames
import play.api.http.MimeTypes
import play.api.libs.json.JsValue
import play.api.libs.json.Json
import play.api.libs.json.Json.toJsFieldJsValueWrapper
import play.api.libs.ws._
import play.api.mvc.{Action, AnyContent, Controller}
import helpers.Auth0Config
import play.api.Configuration

class Callback @Inject() (cache: CacheApi, ws: WSClient, configuration: Configuration) extends Controller {

  private val config = Auth0Config.get(configuration)

  def callback(codeOpt: Option[String] = None, stateOpt: Option[String] = None): Action[AnyContent] = Action.async { request =>
    val sessionId = request.session.get("id").get
    if (stateOpt == cache.get(sessionId + "state")) {
      (for {
        code <- codeOpt
      } yield {
        getToken(code, sessionId).flatMap { case (idToken, accessToken) =>
          getUser(accessToken).map { user =>
            cache.set(request.session.get("id").get + "profile", user)
            Redirect(routes.User.index())
          }

        }.recover {
          case ex: IllegalStateException => Unauthorized(ex.getMessage)
        }
      }).getOrElse(Future.successful(BadRequest("No parameters supplied")))
    } else {
      Future.successful(BadRequest("Invalid state parameter"))
    }
  }

  def getToken(code: String, sessionId: String): Future[(String, String)] = {
    var audience = config.audience
    if (config.audience == ""){
      audience = String.format("https://%s/userinfo",config.domain)
    }
    val tokenResponse = ws.url(String.format("https://%s/oauth/token", config.domain)).
      withHeaders(HeaderNames.ACCEPT -> MimeTypes.JSON).
      post(
        Json.obj(
          "client_id" -> config.clientId,
          "client_secret" -> config.secret,
          "redirect_uri" -> config.callbackURL,
          "code" -> code,
          "grant_type"-> "authorization_code",
          "audience" -> audience
        )
      )

    tokenResponse.flatMap { response =>
      (for {
        idToken <- (response.json \ "id_token").asOpt[String]
        accessToken <- (response.json \ "access_token").asOpt[String]
      } yield {
        cache.set(sessionId + "id_token", idToken)
        cache.set(sessionId + "access_token", accessToken)
        Future.successful((idToken, accessToken))
      }).getOrElse(Future.failed[(String, String)](new IllegalStateException("Tokens not sent")))
    }

  }

  def getUser(accessToken: String): Future[JsValue] = {
    val userResponse = ws.url(String.format("https://%s/userinfo", config.domain))
      .withQueryString("access_token" -> accessToken)
      .get()

    userResponse.flatMap(response => Future.successful(response.json))
  }
} 
Example 7
Source File: User.scala    From auth0-scala-samples   with MIT License 5 votes vote down vote up
package controllers

import javax.inject.Inject
import play.api.mvc.{Action, AnyContent, Controller, Request, Result}
import play.api.libs.json._
import play.api.cache._


class User @Inject() (cache: CacheApi) extends Controller {
  def AuthenticatedAction(f: Request[AnyContent] => Result): Action[AnyContent] = {
    Action { request =>
      (request.session.get("id").flatMap { id =>
        cache.get[JsValue](id + "profile")
      } map { profile =>
        f(request)
      }).orElse {
        Some(Redirect(routes.Application.index()))
      }.get
    }
  }
  
  def index: Action[AnyContent] = AuthenticatedAction { request =>
    val id = request.session.get("id").get
    val profile = cache.get[JsValue](id + "profile").get
    Ok(views.html.user(profile))
  }
} 
Example 8
Source File: Application.scala    From auth0-scala-samples   with MIT License 5 votes vote down vote up
package controllers

import javax.inject.Inject
import play.api.cache._
import play.api.mvc.{Action, AnyContent, Controller}
import helpers.Auth0Config
import java.security.SecureRandom
import java.math.BigInteger
import java.util.UUID.randomUUID

import play.api.Configuration


class Application @Inject() (cache: CacheApi, configuration: Configuration) extends Controller {

  private val config = Auth0Config.get(configuration)

  def index: Action[AnyContent] = Action {
    Ok(views.html.index())
  }

  def login: Action[AnyContent] = Action {
    // Generate random state parameter
    object RandomUtil {
      private val random = new SecureRandom()

      def alphanumeric(nrChars: Int = 24): String = {
        new BigInteger(nrChars * 5, random).toString(32)
      }
    }
    val state = RandomUtil.alphanumeric()

    var audience = config.audience
    if (config.audience == ""){
      audience = String.format("https://%s/userinfo", config.domain)
    }

    val id = randomUUID().toString
    cache.set(id + "state", state)
    val query = String.format(
      "authorize?client_id=%s&redirect_uri=%s&response_type=code&scope=openid profile&audience=%s&state=%s",
      config.clientId,
      config.callbackURL,
      audience,
      state
    )
    Redirect(String.format("https://%s/%s", config.domain, query)).withSession("id" -> id)
  }

  def logout: Action[AnyContent] = Action { request =>
    val host = request.host
    var scheme = "http"
    if (request.secure) {
      scheme = "https"
    }
    val returnTo = scheme + "://" + host
    Redirect(String.format(
      "https://%s/v2/logout?client_id=%s&returnTo=%s",
      config.domain,
      config.clientId,
      returnTo)
    ).withNewSession
  }
} 
Example 9
Source File: ExtendedController.scala    From bay-scalajs.g8   with Apache License 2.0 5 votes vote down vote up
package controllers

import cats.data.EitherT
import play.api.data.Form
import play.api.mvc.Controller
import play.api.mvc.Request
import play.api.mvc.Result
import shared.utils.Codecs
import shared.utils.Implicits
import cats.syntax.either._
import play.api.i18n.MessagesApi
import services.Services

import scala.concurrent.ExecutionContext
import scala.concurrent.Future


trait ExtendedController extends Controller with Implicits with Codecs {
  val services: Services
  implicit val ec: ExecutionContext

  type HttpResult[A] = EitherT[Future, Result, A]

  // Constructors for our result type
  object HttpResult {

    def point[A](a: A): HttpResult[A] =
      EitherT[Future, Result, A](Future.successful(Right(a)))

    def fromFuture[A](fa: Future[A]): HttpResult[A] =
      EitherT[Future, Result, A](fa.map(Right(_)))

    def fromEither[A](va: Either[Result, A]): HttpResult[A] =
      EitherT[Future, Result, A](Future.successful(va))

    def fromEither[A, B](failure: B => Result)(va: Either[B, A]): HttpResult[A] =
      EitherT[Future, Result, A](Future.successful(va.leftMap(failure)))

    def fromOption[A](failure: Result)(oa: Option[A]): HttpResult[A] =
      EitherT[Future, Result, A](Future.successful(oa.toRight(failure)))

    def fromFOption[A](failure: Result)(foa: Future[Option[A]]): HttpResult[A] =
      EitherT[Future, Result, A](foa.map(_.toRight(failure)))

    def fromFEither[A, B](failure: B => Result)(fva: Future[Either[B, A]]): HttpResult[A] =
      EitherT[Future, Result, A](fva.map(_.leftMap(failure)))

    def fromForm[FormType](failure: Form[FormType] => Result)(form: Form[FormType])(
        implicit request: Request[_]): HttpResult[FormType] =
      EitherT[Future, Result, FormType](
        form.bindFromRequest.fold(errorForm => Left(failure(errorForm)).asFuture,
                                  formEntity => Right(formEntity).asFuture))
  }

  def constructResult(result: HttpResult[Result]): Future[Result] = result.value.map(_.merge)

  implicit class ExtResult(e: Result) {

    def pureResult: HttpResult[Result] =
      EitherT[Future, Result, Result](Future.successful(Right(e)))
  }

  implicit class EnrichedOps[T](t: T) {
    def |>[R](f: T => R): R = f(t)
  }

  def messagesApi: MessagesApi = services.messagesApi
} 
Example 10
Source File: SnapshotCheckController.scala    From DataQuality   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package controllers.checks

import javax.inject.Inject
import com.codahale.jerkson.Json.generate
import controllers.ControllerUtils._
import controllers.utils.MyDBSession
import controllers.utils.ValidationConstraints._
import models.checks.Check.CheckType
import models.checks.{Check, CheckParameter, SnapshotCheck}
import models.meta.CheckMeta
import models.metrics.Metric
import models.targets.TargetToChecks
import org.squeryl.PrimitiveTypeMode.inTransaction
import play.api.Play.current
import play.api.data.Form
import play.api.data.Forms.{list, mapping, optional, text, tuple}
import play.api.i18n.Messages.Implicits._
import play.api.mvc.{Action, Controller}

import scala.util.Try


class SnapshotCheckController @Inject()(session: MyDBSession) extends Controller {

  private def getMainForm(currId: Option[String] = None): Form[(Check, SnapshotCheck, List[CheckParameter])] = {
    def valFunc: (String) => Boolean = (t:String) => inTransaction(validateId(t, Check.getIdList(), currId))
    def valName: (String) => Boolean = (t:String) => inTransaction(validateRefList(t, CheckMeta.getShortList(Some(CheckType.snapshot))))
    def valMetric: (String) => Boolean = (t:String) => inTransaction(validateRefList(t, Metric.getIdList()))

    Form(
      mapping(
        "id" -> text.verifying(errorUsed, valFunc),
        "subtype" -> text.verifying(errorNotFound("Check type"), valName),
        "description" -> optional(text),
        "metric" -> text.verifying(errorNotFound("Metric"), valMetric),
        "parameters" -> list(
          tuple(
            "name" -> text,
            "value" -> text
          )
        )
      )(SnapshotCheck.applyWithCheck)(SnapshotCheck.unapplyWithCheck).verifying(validateSnapshotCheck)
    )
  }

  def addSnapshotCheck() = Action { implicit request =>
    val form = getMainForm().bindFromRequest
    form.value map { check =>
      try {
        val json = inTransaction({
          val met = check._1.insert()
          val colMet = check._2.insert()
          check._3.foreach(_.insert())
          generate(SnapshotCheck.tupleToMap((met,colMet)))
        })
        Created(json).as(JSON)
      } catch {
        case e: Exception => InternalServerError(e.toString)
      }
    } getOrElse BadRequest(form.errorsAsJson).as(JSON)
  }

  def getCheckDetails(id: String) = Action {
    inTransaction { Try{
      val check: (Check, SnapshotCheck) = SnapshotCheck.getById(id).single
      generate(SnapshotCheck.tupleToMap(check))
    }.toOption match {
      case Some(json) => Ok(json).as(JSON)
      case None =>
        val json = generate(Map("error"->"Check not found!"))
        BadRequest(json).as(JSON)
      }
    }
  }

  def updateCheck(id: String) = Action { implicit request =>
    val form = getMainForm(Some(id)).bindFromRequest
    form.value map { check =>
      try {
        val json = inTransaction{
          if(check._1.id == id) {
            CheckParameter.deleteByOwner(id)
            check._1.update()
            check._2.update()
          } else {
            val c = check._1.insert()
            check._2.insert()
            TargetToChecks.updateChecks(id, c.id)
            SnapshotCheck.deleteById(id)
          }
          check._3.foreach(_.insert())
          generate(SnapshotCheck.tupleToMap((check._1,check._2)))
        }
        Ok(json).as(JSON)
      } catch {
        case e: Exception => InternalServerError(e.toString)
      }
    } getOrElse BadRequest(form.errorsAsJson).as(JSON)
  }

} 
Example 11
Source File: SqlCheckController.scala    From DataQuality   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package controllers.checks

import javax.inject.Inject
import com.codahale.jerkson.Json.generate
import controllers.ControllerUtils._
import controllers.utils.MyDBSession
import controllers.utils.ValidationConstraints._
import models.checks.Check.CheckType
import models.checks.{Check, SqlCheck}
import models.meta.CheckMeta
import models.sources.Database
import models.targets.TargetToChecks
import org.squeryl.PrimitiveTypeMode.inTransaction
import play.api.Play.current
import play.api.data.Form
import play.api.data.Forms.{mapping, optional, text}
import play.api.i18n.Messages.Implicits._
import play.api.mvc.{Action, Controller}

import scala.util.Try


class SqlCheckController @Inject()(session: MyDBSession) extends Controller {

  private def getMainForm(currId: Option[String] = None): Form[(Check, SqlCheck)] = {
    def valFunc: (String) => Boolean = (t:String) => inTransaction(validateId(t, Check.getIdList(), currId))
    def valDB: (String) => Boolean = (t:String) => inTransaction(validateRefList(t, Database.getIdList()))
    def valName: (String) => Boolean = (t:String) => inTransaction(validateRefList(t, CheckMeta.getShortList(Some(CheckType.sql))))

    Form(
      mapping(
        "id" -> text.verifying(errorUsed, valFunc),
        "subtype" -> text.verifying(errorNotFound("Check type"), valName),
        "description" -> optional(text),
        "database" -> text.verifying(errorNotFound("Database"), valDB),
        "query" -> text
      )(SqlCheck.applyWithCheck)(SqlCheck.unapplyWithCheck)
    )
  }

  def addSqlCheck() = Action { implicit request =>
    val form = getMainForm().bindFromRequest
    form.value map { check =>
      try {
        inTransaction({
          val chk = check._1.insert()
          val sql = check._2.insert()
          val json = generate(SqlCheck.tupleToMap((chk,sql)))
          Created(json).as(JSON)
        })
      } catch {
        case e: Exception => InternalServerError(e.toString)
      }
    } getOrElse BadRequest(form.errorsAsJson).as(JSON)
  }

  def getCheckDetails(id: String) = Action {
    inTransaction(Try{
      val check: (Check, SqlCheck) = SqlCheck.getById(id)
      generate(SqlCheck.tupleToMap(check))
    }.toOption match {
      case Some(json) => Ok(json).as(JSON)
      case None =>
        val json = generate(Map("error"->"Check not found!"))
        BadRequest(json).as(JSON)
    })
  }

  def updateCheck(id: String) = Action { implicit request =>
    val form = getMainForm(Some(id)).bindFromRequest
    form.value map { check =>
      try {
          val json = inTransaction{
            if(check._1.id == id) {
              check._1.update()
              check._2.update()
            } else {
              val c = check._1.insert()
              check._2.insert()
              TargetToChecks.updateChecks(id, c.id)
              SqlCheck.deleteById(id)
            }
            generate(SqlCheck.tupleToMap((check._1,check._2)))
          }
          Ok(json).as(JSON)
        } catch {
        case e: Exception => InternalServerError(e.toString)
      }
    } getOrElse BadRequest(form.errorsAsJson).as(JSON)
  }

} 
Example 12
Source File: FileMetricController.scala    From DataQuality   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package controllers.metrics

import javax.inject.Inject
import com.codahale.jerkson.Json.generate
import controllers.ControllerUtils._
import controllers.utils.MyDBSession
import controllers.utils.ValidationConstraints._
import models.meta.MetricMeta
import models.metrics.Metric.MetricType
import models.metrics.{FileMetric, Metric}
import models.sources.Source
import org.squeryl.PrimitiveTypeMode.inTransaction
import play.api.Play.current
import play.api.data.Form
import play.api.data.Forms.{mapping, text}
import play.api.i18n.Messages.Implicits._
import play.api.mvc.{Action, Controller}

import scala.util.Try


class FileMetricController @Inject()(session: MyDBSession) extends Controller {

  private def getMainForm(currId: Option[String] = None): Form[(Metric, FileMetric)] = {
    def valFunc: (String) => Boolean = (t:String) => inTransaction(validateId(t, Metric.getIdList(), currId))
    def valSrc: (String) => Boolean = (t:String) => inTransaction(validateRefList(t, Source.getIdList()))
    def valName: (String) => Boolean = (t:String) => inTransaction(validateRefList(t, MetricMeta.getShortList(Some(MetricType.file))))

    Form(
      mapping(
        "id" -> text.verifying(errorUsed, valFunc),
        "name" -> text.verifying(errorNotFound("Metric name"), valName),
        "description" -> text,
        "source" -> text.verifying(errorNotFound("Source"), valSrc)
      )(FileMetric.applyWithMetric)(FileMetric.unapplyWithMetric).verifying(validateFileMetric)
    )
  }

  def addFileMetric() = Action { implicit request =>
    val form = getMainForm().bindFromRequest
    form.value map { metric =>
      try {
        inTransaction({
          val met = metric._1.insert()
          val fmet = metric._2.insert()
          val json = generate(FileMetric.tupleToMap((met,fmet)))
          Created(json).as(JSON)
        })
      } catch {
        case e:Exception => InternalServerError(e.toString)
      }
    } getOrElse BadRequest(form.errorsAsJson).as(JSON)
  }

  def getMetricDetails(id: String) = Action {
    inTransaction(
      Try{
        val metric: (Metric, FileMetric) = FileMetric.getById(id)
        generate(FileMetric.tupleToMap(metric))
      }.toOption match {
        case Some(json) => Ok(json).as(JSON)
        case None =>
          val json = generate(Map("error"->"Metric not found!"))
          BadRequest(json).as(JSON)
      })
  }

  def updateMetric(id: String) = Action { implicit request =>
    val form = getMainForm(Some(id)).bindFromRequest
    form.value map { metric =>
      inTransaction(try {
        metric._1.id match {
          case `id` =>
            metric._1.update()
            metric._2.update()
          case _ =>
            metric._1.insert()
            metric._2.rebase(id)
        }
        val json = generate(FileMetric.tupleToMap(metric))
        Ok(json).as(JSON)
      } catch {
        case e: Exception => InternalServerError(e.toString)
      })
    } getOrElse BadRequest(form.errorsAsJson).as(JSON)
  }

} 
Example 13
Source File: MetricController.scala    From DataQuality   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package controllers.metrics

import javax.inject.Inject
import com.codahale.jerkson.Json.generate
import controllers.utils.MyDBSession
import models.metrics.Metric.MetricType
import models.metrics.{ColumnMetric, ComposedMetric, FileMetric, Metric}
import org.squeryl.PrimitiveTypeMode._
import org.squeryl.Query
import play.api.Configuration
import play.api.mvc.{Action, Controller}

import scala.util.Try


class MetricController @Inject()(val configuration: Configuration,session: MyDBSession) extends Controller {

  private implicit val pageLength: Option[Int] = configuration.getInt("pagination.length")

  def getAllMetrics(source: Option[String], page: Option[Int], filter: Option[String]) = Action {
    val mtType = Try(MetricType.withName(filter.get.toUpperCase)).toOption
    val json: String = inTransaction {
      val query: Query[Metric] = source match {
        case Some(src) => Metric.getMetricsBySource(src, mtType)
        case None => Metric.getAll(mtType)
      }
      val stats = Metric.getStats(query)
      val res: Query[Metric] = (pageLength,page,query) match {
        case (Some(length), Some(pg), qr: Query[Metric]) => qr.page(pg * length, length)
        case (_,_,_) => query
      }
      generate(Map("metrics" -> res.map(Metric.toShortMap)) ++ stats)
    }
    Ok(json).as(JSON)
  }

  def deleteMetricById(id: String) = Action {
    inTransaction(try{
      val delOpt: Option[Int] = Try {
        val src: String = Metric.getDetailed(id).mType
        src match {
          case "FILE" => FileMetric.deleteById(id)
          case "COLUMN" => ColumnMetric.deleteById(id)
          case "COMPOSED" => ComposedMetric.deleteById(id)
          case _ => 0
        }
      }.toOption
      delOpt match {
        case Some(x) if x > 0 => Ok
        case _ =>
          val json = generate(Map("error"->"Metric not found!"))
          BadRequest(json).as(JSON)
      }
    } catch {
      case e: Exception => InternalServerError(e.toString)
    })
  }

  def getIdList(filter: Option[String]) = Action {
    val mtType = Try(MetricType.withName(filter.get.toUpperCase)).toOption
    val json = inTransaction {
      val list: Query[String] = Metric.getIdList(mtType)
      generate(Map("metrics" -> list.iterator))
    }
    Ok(json).as(JSON)
  }

} 
Example 14
Source File: ComposedMetricController.scala    From DataQuality   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package controllers.metrics

import javax.inject.Inject
import com.codahale.jerkson.Json.generate
import controllers.ControllerUtils._
import controllers.utils.MyDBSession
import controllers.utils.ValidationConstraints._
import models.metrics._
import org.squeryl.PrimitiveTypeMode.inTransaction
import play.api.Play.current
import play.api.data.Form
import play.api.data.Forms.{mapping, text}
import play.api.i18n.Messages.Implicits._
import play.api.mvc.{Action, Controller}

import scala.util.Try


class ComposedMetricController @Inject()(session: MyDBSession) extends Controller {

  private def getMainForm(currId: Option[String] = None): Form[(Metric, ComposedMetric)] = {
    def validateIdFunc: (String) => Boolean = (t:String) => inTransaction(validateId(t, Metric.getIdList(), currId))
    def validateFormulaFunc: (String) => Boolean = (t:String) => inTransaction(ComposedMetricValidator.validateFormula(t, currId))

    Form(
      mapping(
        "id" -> text.verifying(errorUsed, validateIdFunc),
        "name" -> text,
        "description" -> text,
        "formula" -> text.verifying(errorFormula, validateFormulaFunc)
      )(ComposedMetric.applyWithMetric)(ComposedMetric.unapplyWithMetric)
    )
  }

  def addComposedMetric() = Action { implicit request =>
    val form = getMainForm().bindFromRequest
    form.value map { metric =>
      try {
        inTransaction({
          val met = metric._1.insert()
          val fmet = metric._2.insert()
          val json = generate(ComposedMetric.tupleToMap((met,fmet)))
          Created(json).as(JSON)
        })
      } catch {
        case e: Exception => InternalServerError(e.toString)
      }
    } getOrElse BadRequest(form.errorsAsJson).as(JSON)
  }

  def getMetricDetails(id: String) = Action {
    inTransaction(
      Try{
        val metric: (Metric, ComposedMetric) = ComposedMetric.getById(id)
        generate(ComposedMetric.tupleToMap(metric))
      }.toOption match {
        case Some(json) => Ok(json).as(JSON)
        case None =>
          val json = generate(Map("error"->"Metric not found!"))
          BadRequest(json).as(JSON)
      })
  }

  def updateMetric(id: String) = Action { implicit request =>
    val form = getMainForm(Some(id)).bindFromRequest
    form.value map { metric =>
      inTransaction(try {
        metric._1.id match {
          case `id` =>
            metric._1.update()
            metric._2.update()
          case _ =>
            metric._1.insert()
            metric._2.rebase(id)
        }
        val json = generate(ComposedMetric.tupleToMap(metric))
        Ok(json).as(JSON)
      } catch {
        case e: Exception => InternalServerError(e.toString)
      })
    } getOrElse BadRequest(form.errorsAsJson).as(JSON)
  }

} 
Example 15
Source File: TargetAttachmentsController.scala    From DataQuality   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package controllers.targets

import javax.inject.Inject

import com.codahale.jerkson.Json.generate
import models.targets.{Mail, Target, TargetToChecks}
import org.squeryl.PrimitiveTypeMode.inTransaction
import play.api.Play.current
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.Messages.Implicits._
import play.api.mvc.{Action, Controller}

import scala.util.Try


class TargetAttachmentsController @Inject()() extends Controller {

  private val mailForm = Form(
    "address" -> email
  )

  def getTargetMailList(id: String) = Action {
    Try(inTransaction {
      val mails: Iterator[Mail] = Target.getDetailed(id).mails
      generate(mails)
    }).toOption match {
      case Some(json) => Ok(json).as(JSON)
      case None => BadRequest("There are no emails associated with this target!")
    }
  }

  def addTargetMail(id: String) = Action { implicit request =>
    val form = mailForm.bindFromRequest
    form.value map { mail =>
      inTransaction(Mail.apply(mail, id).insert)
      Created
    } getOrElse BadRequest(form.errorsAsJson).as(JSON)
  }

  def deleteTargetMail(id: String) = Action { implicit request =>
    mailForm.bindFromRequest.value map (mail => {
      inTransaction(
        Mail.deleteById(mail, id)
      )
    })
    Ok
  }

  private val checkForm = Form(
    "checkId" -> text
  )

  def getTargetCheckList(id: String) = Action {
    Try(inTransaction {
      val checks: Iterator[TargetToChecks] = Target.getDetailed(id).checks
      generate(checks)
    }).toOption match {
      case Some(json) => Ok(json).as(JSON)
      case None => BadRequest("There are no checks associated with this target!")
    }
  }

  def addTargetCheck(id: String) = Action { implicit request =>
    checkForm.bindFromRequest.value map (check =>
      inTransaction(
        TargetToChecks.apply(check, id).insert
      )
      )
    Created
  }

  def deleteTargetCheck(id: String) = Action { implicit request =>
    checkForm.bindFromRequest.value map (check => {
      inTransaction(
        TargetToChecks.deleteById(check, id)
      )
    })
    Ok
  }

} 
Example 16
Source File: SearchController.scala    From DataQuality   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package controllers.search

import javax.inject.Inject
import com.codahale.jerkson.Json.generate
import controllers.utils.MyDBSession
import models.{BasicEntityType, EntityParentEnumeration}
import org.squeryl.PrimitiveTypeMode._
import org.squeryl.Query
import play.api.Configuration
import play.api.mvc.{Action, AnyContent, Controller}

import scala.util.Try


class SearchController @Inject()(val configuration: Configuration,session: MyDBSession) extends Controller {

  private implicit val pageLength: Option[Int] = configuration.getInt("pagination.length")

  def searchById(tipo: String, query: String, filter: Option[String], parent: Option[String], parentId:Option[String], page: Option[Int]): Action[AnyContent] = Action {
    inTransaction { try {
      val eType: Option[BasicEntityType.Value] = Try(BasicEntityType.withName(tipo.toLowerCase)).toOption
      val result: Map[_ <: String, Any] = eType match {
        case Some(t) =>
          val tipo: Option[Enumeration#Value] = Try(t.service.typeEnum.get.withName(filter.get.toUpperCase)).toOption
          val parentType: Option[EntityParentEnumeration#EntityParentVal] = Try(t.service.parentEnum.get.withName(parent.get.toLowerCase).asInstanceOf[EntityParentEnumeration#EntityParentVal]).toOption
          val q: Query[String] = t.service.searchIdList('%'+query+'%', tipo, parentType, parentId)
          val res: Query[String] = (pageLength,page) match {
            case (Some(length), Some(pg)) => q.page(pg * length, length)
            case (_,_) => q
          }
          Map("results" -> res.toList, "size" -> q.iterator.size, "last_page" -> Try((q.iterator.size - 1)/pageLength.get).toOption)
        case None => Map.empty
      }
      val json = generate(result)
      Ok(json).as(JSON)
    } catch {
      case e:Exception => InternalServerError(e.toString)
    }}
  }

} 
Example 17
Source File: TemplateController.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.controllers

import javax.inject.Inject

import de.frosner.broccoli.models.Template
import de.frosner.broccoli.models.Template.templateApiWrites
import de.frosner.broccoli.services.{SecurityService, TemplateService}
import jp.t2v.lab.play2.auth.BroccoliSimpleAuthorization
import play.api.Environment
import play.api.cache.CacheApi
import play.api.libs.json.Json
import play.api.mvc.{Action, AnyContent, Controller}

case class TemplateController @Inject()(
    templateService: TemplateService,
    override val securityService: SecurityService,
    override val playEnv: Environment,
    override val cacheApi: CacheApi
) extends Controller
    with BroccoliSimpleAuthorization {

  def list = StackAction(parse.empty) { implicit request =>
    Ok(Json.toJson(TemplateController.list(templateService)))
  }

  def show(id: String) = StackAction(parse.empty) { implicit request =>
    templateService.template(id).map(template => Ok(Json.toJson(template))).getOrElse(NotFound)
  }

}

object TemplateController {

  def list(templateService: TemplateService): Seq[Template] =
    templateService.getTemplates

} 
Example 18
Source File: SourceController.scala    From DataQuality   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package controllers.sources

import javax.inject.Inject
import com.codahale.jerkson.Json.generate
import controllers.utils.MyDBSession
import models.sources.Source.SourceType
import models.sources._
import org.squeryl.PrimitiveTypeMode._
import org.squeryl.Query
import play.api.Configuration
import play.api.mvc.{Action, Controller}

import scala.util.Try


class SourceController @Inject()(val configuration: Configuration,session: MyDBSession) extends Controller {

  private implicit val pageLength: Option[Int] = configuration.getInt("pagination.length")

  def getAllSources(database: Option[String], page: Option[Int], filter: Option[String]) = Action {
    val scType = Try(SourceType.withName(filter.get.toUpperCase)).toOption
    val json: String = inTransaction {
      val query: Query[Source] = database match {
        case Some(db) => Source.getSourcesByDatabase(db)
        case None => Source.getAll(scType)
      }
      val stats = Source.getStats(query)
      val res = (pageLength,page) match {
        case (Some(length), Some(pg)) => query.page(pg * length, length)
        case (_,_) => query
      }
      generate(Map("sources" -> res.map(Source.toShortMap)) ++ stats)
    }
    Ok(json).as(JSON)
  }

  def getIdList(filter: Option[String]) = Action {
    val scType = Try(SourceType.withName(filter.get.toUpperCase)).toOption
    val json = inTransaction {
      val list = Source.getIdList(scType)
      generate(Map("sources" -> list.iterator))
    }
    Ok(json).as(JSON)
  }

  def deleteSourceById(id: String) = Action {
    inTransaction(try{
      val delOpt: Option[Int] = Try {
        val src: String = Source.getDetailed(id).scType
        src match {
          case "HDFS" => HdfsFile.deleteById(id)
          case "TABLE" => DBTable.deleteById(id)
          case "HIVE" => HiveTable.deleteById(id)
          case "VIRTUAL" => VirtualSource.deleteById(id)
          case _ => 0
        }
      }.toOption
      delOpt match {
        case Some(x) if x > 0 => Ok
        case _ =>
          val json = generate(Map("error"->"Source not found!"))
          BadRequest(json).as(JSON)
      }
    } catch {
      case e: Exception => InternalServerError(e.toString)
    })
  }
} 
Example 19
Source File: ConfigController.scala    From DataQuality   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package controllers.config

import javax.inject.Inject
import com.typesafe.config.ConfigRenderOptions
import models.AppDB
import models.config.{ConfigReader, ConfigWriter}
import org.squeryl.PrimitiveTypeMode.inTransaction
import play.api.Logger
import play.api.libs.Files.TemporaryFile
import play.api.mvc.{Action, Controller, MultipartFormData}


class ConfigController @Inject()() extends Controller {

  def downloadConfiguration = Action {
//    try{
      val config = inTransaction(ConfigWriter.generateConfig)
      Ok(config.root().render(ConfigRenderOptions.concise().setFormatted(true).setJson(false)))
        .withHeaders("Content-Disposition" -> "attachment; filename=configuration.conf")
//    } catch {
//      case e: Exception => InternalServerError(e.toString)
//    }
  }

  def uploadConfiguration(): Action[MultipartFormData[TemporaryFile]] = Action(parse.multipartFormData) {
    implicit request => request.body.file("configuration")
      .map(file => {
        file.contentType match {
          case Some("application/octet-stream") =>
           try {
             inTransaction(AppDB.resetAll())
             ConfigReader.parseConfiguration(file.ref.file)
             Ok
           } catch {

             case e:  Exception => {
               Logger.error("ERROR reading config: " + e.getMessage)
               InternalServerError(e.toString)

             }
           }
          case _ => BadRequest("No application/octet-stream files were found!")
        }
      })  getOrElse BadRequest("File missing");
  }

  def resetConfiguration() = Action {
    inTransaction(AppDB.resetAll())
    Ok
  }

} 
Example 20
Source File: Playlist.scala    From Mastering-Spark-for-Data-Science   with MIT License 5 votes vote down vote up
package controllers

import com.typesafe.config.ConfigFactory
import play.api.Logger
import play.api.mvc.{Action, Controller}
import svc.{AnalyzerSvc, CassandraDao, SparkSvc}

object Playlist extends Controller {

  val config = ConfigFactory.load()
  val minTime = config.getInt("gzet.min.time")
  val maxTime = config.getInt("gzet.max.time")
  val cassandraHost = config.getString("cassandra.host")
  val cassandraPort = config.getInt("cassandra.port")
  val sampleSize = config.getDouble("gzet.sample.size")
  val minMatch = config.getDouble("gzet.min.match")

  val dao = new CassandraDao(cassandraHost, cassandraPort)
  val analyzer = new AnalyzerSvc()
  val spark = new SparkSvc()

  def index = Action { implicit request =>
    val playlist = models.Playlist(dao.getNodes)
    Logger.info(s"Database is currently ${playlist.nodes.size} songs long")
    Ok(views.html.playlist(playlist))
  }

  def personalize(id: Long) = Action { implicit request =>
    if(models.Playlist(dao.getNodes).nodes.isEmpty) {
      Redirect(routes.Playlist.index()).flashing("warning" -> s"Could not run personalized page rank on empty indices")
    } else {
      val name = dao.getSongName(id)
      if(name.isEmpty) {
        Redirect(routes.Playlist.index()).flashing("error" -> s"Could not find song for id [$id]")
      } else {
        try {
          Logger.info(s"Running a personalize Page Rank for id [$id] and song [$name]")
          val nodes = spark.playlist(id)
          val playlist = models.Playlist(nodes, name)
          Ok(views.html.playlist(playlist))
        } catch {
          case e: Exception =>
            Redirect(routes.Playlist.index()).flashing("error" -> e.getMessage)
        }
      }
    }
  }

  def submit = Action { implicit request =>
    try {
      dao.dropPlaylist
      val jobId = spark.playlist()
      Redirect(routes.Playlist.index()).flashing("success" -> jobId)
    } catch {
      case e: Exception =>
        Redirect(routes.Playlist.index()).flashing("error" -> e.getMessage)
    }
  }

} 
Example 21
Source File: SimHash.scala    From Mastering-Spark-for-Data-Science   with MIT License 5 votes vote down vote up
package io.gzet.story.web.controllers

import io.gzet.story.model.{Article, Duplicate}
import io.gzet.story.util.{HtmlFetcher, Tokenizer}
import io.gzet.story.util.SimhashUtils._
import io.gzet.story.web.SimpleConfig
import io.gzet.story.web.dao.CassandraDao
import org.apache.lucene.analysis.en.EnglishAnalyzer
import play.api.Logger
import play.api.libs.functional.syntax._
import play.api.libs.json._
import play.api.mvc.{Action, Controller}

object SimHash extends Controller with SimpleConfig {

  val dao = new CassandraDao
  val goose = new HtmlFetcher(gooseConnectionTimeout, gooseSocketTimeout)
  val analyzer = new EnglishAnalyzer()

  implicit val articleFormat = {
    val jsonDescription =
      (__ \ "hash").format[Int] and (__ \ "body").format[String] and (__ \ "title").format[String] and (__ \ "url").format[String]

    jsonDescription(Article.apply, unlift(Article.unapply))
  }

  implicit val duplicateFormat = {
    val jsonDescription =
      (__ \ "simhash").format[Int] and (__ \ "body").format[String] and (__ \ "title").format[String] and (__ \ "url").format[String] and (__ \ "related").format[List[Article]]

    jsonDescription(Duplicate.apply, unlift(Duplicate.unapply))
  }

  def fetch = Action { implicit request =>

    val url = request.getQueryString("url").getOrElse("NA")
    Logger.info(s"Fetch article [$url]")

    val article = goose.fetch(url)
    Logger.info(s"Title [${article.title}]")

    val hash = Tokenizer.lucene(article.body, analyzer).mkString(" ").simhash
    Logger.info(s"Hash [$hash]")

    val related = dao.findDuplicates(hash)
    Logger.info(s"${related.size} duplicate(s) found")

    Ok(Json.toJson(Duplicate(
      hash,
      article.body,
      article.title,
      url,
      related
    )))

  }


} 
Example 22
Source File: nested_options_validation_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package nested_options_validation.yaml
import play.api.mvc.{Action, Controller}
import play.api.data.validation.Constraint
import de.zalando.play.controllers._
import PlayBodyParsing._
import PlayValidations._

// ----- constraints and wrapper validations -----
class BasicOptionalNested_optionalOptConstraints(override val instance: String) extends ValidationBase[String] {
    override val reference = "⌿definitions⌿Basic⌿optional⌿nested_optional⌿Opt"
    override def constraints: Seq[Constraint[String]] =
        Seq(maxLength(6), minLength(5))
}
class BasicOptionalNested_optionalOptValidator(instance: String) extends RecursiveValidator {
    override val reference = "⌿definitions⌿Basic⌿optional⌿nested_optional⌿Opt"
    override val validators = Seq(new BasicOptionalNested_optionalOptConstraints(instance))
}
// ----- complex type validators -----
class BasicValidator(instance: Basic) extends RecursiveValidator {
    override val reference = "⌿definitions⌿Basic"
    override val validators = Seq(
        new BasicOptionalValidator(instance.optional)
    )
}
class BasicOptionalOptValidator(instance: BasicOptionalOpt) extends RecursiveValidator {
    override val reference = "⌿definitions⌿Basic⌿optional⌿Opt"
    override val validators = Seq(
        new BasicOptionalNested_optionalValidator(instance.nested_optional)
    )
}

// ----- option delegating validators -----
class BasicOptionalValidator(instance: BasicOptional) extends RecursiveValidator {
    override val reference = "⌿definitions⌿Basic⌿optional"
    override val validators = instance.toSeq.map { new BasicOptionalOptValidator(_) }
}
class BasicOptionalNested_optionalValidator(instance: BasicOptionalNested_optional) extends RecursiveValidator {
    override val reference = "⌿definitions⌿Basic⌿optional⌿nested_optional"
    override val validators = instance.toSeq.map { new BasicOptionalNested_optionalOptValidator(_) }
}
// ----- array delegating validators -----
// ----- catch all simple validators -----
// ----- composite validators -----
// ----- call validations -----
class GetValidator(basic: Basic) extends RecursiveValidator {
    override val reference = "⌿paths⌿⌿get"
    override val validators = Seq(
        new BasicValidator(basic)
    
    )
} 
Example 23
Source File: heroku_petstore_api_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package heroku.petstore.api.yaml
import play.api.mvc.{Action, Controller}
import play.api.data.validation.Constraint
import de.zalando.play.controllers._
import PlayBodyParsing._
import PlayValidations._

import scala.math.BigInt
// ----- constraints and wrapper validations -----
class PetIdGetPetIdConstraints(override val instance: String) extends ValidationBase[String] {
    override val reference = "⌿paths⌿/{petId}⌿get⌿petId"
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class PetIdGetPetIdValidator(instance: String) extends RecursiveValidator {
    override val reference = "⌿paths⌿/{petId}⌿get⌿petId"
    override val validators = Seq(new PetIdGetPetIdConstraints(instance))
}
class PetNameOptConstraints(override val instance: String) extends ValidationBase[String] {
    override val reference = "⌿definitions⌿Pet⌿name⌿Opt"
    override def constraints: Seq[Constraint[String]] =
        Seq(maxLength(100), minLength(3))
}
class PetNameOptValidator(instance: String) extends RecursiveValidator {
    override val reference = "⌿definitions⌿Pet⌿name⌿Opt"
    override val validators = Seq(new PetNameOptConstraints(instance))
}
class PetBirthdayOptConstraints(override val instance: Int) extends ValidationBase[Int] {
    override val reference = "⌿definitions⌿Pet⌿birthday⌿Opt"
    override def constraints: Seq[Constraint[Int]] =
        Seq(max(100.toInt, false), min(1.toInt, false))
}
class PetBirthdayOptValidator(instance: Int) extends RecursiveValidator {
    override val reference = "⌿definitions⌿Pet⌿birthday⌿Opt"
    override val validators = Seq(new PetBirthdayOptConstraints(instance))
}
class GetLimitConstraints(override val instance: BigInt) extends ValidationBase[BigInt] {
    override val reference = "⌿paths⌿/⌿get⌿limit"
    override def constraints: Seq[Constraint[BigInt]] =
        Seq(max(BigInt("10000"), false), min(BigInt("11"), false))
}
class GetLimitValidator(instance: BigInt) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿limit"
    override val validators = Seq(new GetLimitConstraints(instance))
}
// ----- complex type validators -----
class PetValidator(instance: Pet) extends RecursiveValidator {
    override val reference = "⌿definitions⌿Pet"
    override val validators = Seq(
        new PetNameValidator(instance.name), 
        new PetBirthdayValidator(instance.birthday)
    )
}

// ----- option delegating validators -----
class PetNameValidator(instance: PetName) extends RecursiveValidator {
    override val reference = "⌿definitions⌿Pet⌿name"
    override val validators = instance.toSeq.map { new PetNameOptValidator(_) }
}
class PetBirthdayValidator(instance: PetBirthday) extends RecursiveValidator {
    override val reference = "⌿definitions⌿Pet⌿birthday"
    override val validators = instance.toSeq.map { new PetBirthdayOptValidator(_) }
}
class PutPetValidator(instance: PutPet) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿put⌿pet"
    override val validators = instance.toSeq.map { new PetValidator(_) }
}
// ----- array delegating validators -----
// ----- catch all simple validators -----
// ----- composite validators -----
// ----- call validations -----
class PutValidator(pet: PutPet) extends RecursiveValidator {
    override val reference = "⌿paths⌿⌿put"
    override val validators = Seq(
        new PutPetValidator(pet)
    
    )
}
class GetValidator(limit: BigInt) extends RecursiveValidator {
    override val reference = "⌿paths⌿⌿get"
    override val validators = Seq(
        new GetLimitValidator(limit)
    
    )
}
class PetIdGetValidator(petId: String) extends RecursiveValidator {
    override val reference = "⌿paths⌿{petId}⌿get"
    override val validators = Seq(
        new PetIdGetPetIdValidator(petId)
    
    )
}
class PostValidator(pet: Pet) extends RecursiveValidator {
    override val reference = "⌿paths⌿⌿post"
    override val validators = Seq(
        new PetValidator(pet)
    
    )
} 
Example 24
Source File: wrong_field_name_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package wrong_field_name.yaml
import play.api.mvc.{Action, Controller}
import play.api.data.validation.Constraint
import de.zalando.play.controllers._
import PlayBodyParsing._
import PlayValidations._

// ----- constraints and wrapper validations -----
class GetCodesEnumConstraints(override val instance: String) extends ValidationBase[String] {
    override val reference = "⌿paths⌿/⌿get⌿codes⌿Enum"
    override def constraints: Seq[Constraint[String]] =
        Seq(enum("Get,GET,get"))
}
class GetCodesEnumValidator(instance: String) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿codes⌿Enum"
    override val validators = Seq(new GetCodesEnumConstraints(instance))
}
class GetOptCodesOptEnumConstraints(override val instance: String) extends ValidationBase[String] {
    override val reference = "⌿paths⌿/⌿get⌿optCodes⌿Opt⌿Enum"
    override def constraints: Seq[Constraint[String]] =
        Seq(enum("put,PUT,Put"))
}
class GetOptCodesOptEnumValidator(instance: String) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿optCodes⌿Opt⌿Enum"
    override val validators = Seq(new GetOptCodesOptEnumConstraints(instance))
}
// ----- complex type validators -----

// ----- enum delegating validators -----
class GetCodesValidator(instance: GetCodes) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿codes"
    override val validators = Seq(new GetCodesEnumValidator(instance.value))
}
class GetOptCodesOptValidator(instance: GetOptCodesOpt) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿optCodes⌿Opt"
    override val validators = Seq(new GetOptCodesOptEnumValidator(instance.value))
}

// ----- option delegating validators -----
class GetOptCodesValidator(instance: GetOptCodes) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿optCodes"
    override val validators = instance.toSeq.map { new GetOptCodesOptValidator(_) }
}
// ----- array delegating validators -----
// ----- catch all simple validators -----
// ----- composite validators -----
// ----- call validations -----
class GetValidator(optCodes: GetOptCodes, codes: GetCodes) extends RecursiveValidator {
    override val reference = "⌿paths⌿⌿get"
    override val validators = Seq(
        new GetOptCodesValidator(optCodes), 
    
        new GetCodesValidator(codes)
    
    )
} 
Example 25
Source File: string_formats_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package string_formats.yaml
import play.api.mvc.{Action, Controller}
import play.api.data.validation.Constraint
import de.zalando.play.controllers._
import PlayBodyParsing._
import PlayValidations._

import de.zalando.play.controllers.Base64String
import Base64String._
import java.time.ZonedDateTime
import java.util.UUID
import java.time.LocalDate
import de.zalando.play.controllers.BinaryString
import BinaryString._
// ----- constraints and wrapper validations -----
class GetBase64OptConstraints(override val instance: String) extends ValidationBase[String] {
    override val reference = "⌿paths⌿/⌿get⌿base64⌿Opt"
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class GetBase64OptValidator(instance: Base64String) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿base64⌿Opt"
    override val validators = Seq(new GetBase64OptConstraints(instance))
}
class GetPetIdConstraints(override val instance: String) extends ValidationBase[String] {
    override val reference = "⌿paths⌿/⌿get⌿petId"
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class GetPetIdValidator(instance: BinaryString) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿petId"
    override val validators = Seq(new GetPetIdConstraints(instance))
}
class GetDate_timeOptConstraints(override val instance: ZonedDateTime) extends ValidationBase[ZonedDateTime] {
    override val reference = "⌿paths⌿/⌿get⌿date_time⌿Opt"
    override def constraints: Seq[Constraint[ZonedDateTime]] =
        Seq()
}
class GetDate_timeOptValidator(instance: ZonedDateTime) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿date_time⌿Opt"
    override val validators = Seq(new GetDate_timeOptConstraints(instance))
}
class GetUuidOptConstraints(override val instance: UUID) extends ValidationBase[UUID] {
    override val reference = "⌿paths⌿/⌿get⌿uuid⌿Opt"
    override def constraints: Seq[Constraint[UUID]] =
        Seq()
}
class GetUuidOptValidator(instance: UUID) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿uuid⌿Opt"
    override val validators = Seq(new GetUuidOptConstraints(instance))
}
class GetDateOptConstraints(override val instance: LocalDate) extends ValidationBase[LocalDate] {
    override val reference = "⌿paths⌿/⌿get⌿date⌿Opt"
    override def constraints: Seq[Constraint[LocalDate]] =
        Seq()
}
class GetDateOptValidator(instance: LocalDate) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿date⌿Opt"
    override val validators = Seq(new GetDateOptConstraints(instance))
}
// ----- complex type validators -----

// ----- option delegating validators -----
class GetBase64Validator(instance: GetBase64) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿base64"
    override val validators = instance.toSeq.map { new GetBase64OptValidator(_) }
}
class GetDate_timeValidator(instance: GetDate_time) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿date_time"
    override val validators = instance.toSeq.map { new GetDate_timeOptValidator(_) }
}
class GetUuidValidator(instance: GetUuid) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿uuid"
    override val validators = instance.toSeq.map { new GetUuidOptValidator(_) }
}
class GetDateValidator(instance: GetDate) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿date"
    override val validators = instance.toSeq.map { new GetDateOptValidator(_) }
}
// ----- array delegating validators -----
// ----- catch all simple validators -----
// ----- composite validators -----
// ----- call validations -----
class GetValidator(date_time: GetDate_time, date: GetDate, base64: GetBase64, uuid: GetUuid, petId: BinaryString) extends RecursiveValidator {
    override val reference = "⌿paths⌿⌿get"
    override val validators = Seq(
        new GetDate_timeValidator(date_time), 
    
        new GetDateValidator(date), 
    
        new GetBase64Validator(base64), 
    
        new GetUuidValidator(uuid), 
    
        new GetPetIdValidator(petId)
    
    )
} 
Example 26
Source File: all_of_imports_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package all_of_imports.yaml
import play.api.mvc.{Action, Controller}
import play.api.data.validation.Constraint
import de.zalando.play.controllers._
import PlayBodyParsing._
import PlayValidations._

import java.time.ZonedDateTime
// ----- constraints and wrapper validations -----
class ValueTypeConstraints(override val instance: String) extends ValidationBase[String] {
    override val reference = "⌿definitions⌿Value⌿type"
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class ValueTypeValidator(instance: String) extends RecursiveValidator {
    override val reference = "⌿definitions⌿Value⌿type"
    override val validators = Seq(new ValueTypeConstraints(instance))
}
class DatetimeValueValueConstraints(override val instance: ZonedDateTime) extends ValidationBase[ZonedDateTime] {
    override val reference = "⌿definitions⌿DatetimeValue⌿value"
    override def constraints: Seq[Constraint[ZonedDateTime]] =
        Seq()
}
class DatetimeValueValueValidator(instance: ZonedDateTime) extends RecursiveValidator {
    override val reference = "⌿definitions⌿DatetimeValue⌿value"
    override val validators = Seq(new DatetimeValueValueConstraints(instance))
}
// ----- complex type validators -----

// ----- option delegating validators -----
// ----- array delegating validators -----
// ----- catch all simple validators -----
// ----- composite validators -----
class DatetimeValueValidator(instance: DatetimeValue) extends RecursiveValidator {
    override val reference = "⌿definitions⌿DatetimeValue"
    override val validators = Seq(
        new ValueTypeValidator(instance.`type`), 
        new DatetimeValueValueValidator(instance.value)
    )
}
// ----- call validations -----
class PostValidator(body: DatetimeValue) extends RecursiveValidator {
    override val reference = "⌿paths⌿⌿post"
    override val validators = Seq(
        new DatetimeValueValidator(body)
    
    )
} 
Example 27
Source File: echo_api_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package echo
import play.api.mvc.{Action, Controller}
import play.api.data.validation.Constraint
import de.zalando.play.controllers._
import PlayBodyParsing._
import PlayValidations._

// ----- constraints and wrapper validations -----
class PostNameOptConstraints(override val instance: String) extends ValidationBase[String] {
    override val reference = "⌿paths⌿/⌿post⌿name⌿Opt"
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class PostNameOptValidator(instance: String) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿post⌿name⌿Opt"
    override val validators = Seq(new PostNameOptConstraints(instance))
}
class Test_pathIdGetIdConstraints(override val instance: String) extends ValidationBase[String] {
    override val reference = "⌿paths⌿/test-path/{id}⌿get⌿id"
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class Test_pathIdGetIdValidator(instance: String) extends RecursiveValidator {
    override val reference = "⌿paths⌿/test-path/{id}⌿get⌿id"
    override val validators = Seq(new Test_pathIdGetIdConstraints(instance))
}
// ----- complex type validators -----

// ----- option delegating validators -----
class PostNameValidator(instance: PostName) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿post⌿name"
    override val validators = instance.toSeq.map { new PostNameOptValidator(_) }
}
// ----- array delegating validators -----
// ----- catch all simple validators -----
// ----- composite validators -----
// ----- call validations -----
class Test_pathIdGetValidator(id: String) extends RecursiveValidator {
    override val reference = "⌿paths⌿test-path⌿{id}⌿get"
    override val validators = Seq(
        new Test_pathIdGetIdValidator(id)
    
    )
}
class PostValidator(name: PostName, year: PostName) extends RecursiveValidator {
    override val reference = "⌿paths⌿⌿post"
    override val validators = Seq(
        new PostNameValidator(name), 
    
        new PostNameValidator(year)
    
    )
} 
Example 28
Source File: basic_polymorphism_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package basic_polymorphism.yaml
import play.api.mvc.{Action, Controller}
import play.api.data.validation.Constraint
import de.zalando.play.controllers._
import PlayBodyParsing._
import PlayValidations._

// ----- constraints and wrapper validations -----
class PetNameConstraints(override val instance: String) extends ValidationBase[String] {
    override val reference = "⌿definitions⌿Pet⌿name"
    override def constraints: Seq[Constraint[String]] =
        Seq(maxLength(100), minLength(1))
}
class PetNameValidator(instance: String) extends RecursiveValidator {
    override val reference = "⌿definitions⌿Pet⌿name"
    override val validators = Seq(new PetNameConstraints(instance))
}
class PetPetTypeConstraints(override val instance: String) extends ValidationBase[String] {
    override val reference = "⌿definitions⌿Pet⌿petType"
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class PetPetTypeValidator(instance: String) extends RecursiveValidator {
    override val reference = "⌿definitions⌿Pet⌿petType"
    override val validators = Seq(new PetPetTypeConstraints(instance))
}
// ----- complex type validators -----
class PetValidator(instance: IPet) extends RecursiveValidator {
    override val reference = "⌿definitions⌿Pet"
    override val validators = Seq(
        new PetNameValidator(instance.name), 
        new PetPetTypeValidator(instance.petType)
    )
}

// ----- option delegating validators -----
class PutDummyValidator(instance: PutDummy) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿put⌿dummy"
    override val validators = instance.toSeq.map { new PetValidator(_) }
}
// ----- array delegating validators -----
// ----- catch all simple validators -----
// ----- composite validators -----
// ----- call validations -----
class PutValidator(dummy: PutDummy) extends RecursiveValidator {
    override val reference = "⌿paths⌿⌿put"
    override val validators = Seq(
        new PutDummyValidator(dummy)
    
    )
} 
Example 29
Source File: nested_objects_validation_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package nested_objects_validation.yaml
import play.api.mvc.{Action, Controller}
import play.api.data.validation.Constraint
import de.zalando.play.controllers._
import PlayBodyParsing._
import PlayValidations._

// ----- constraints and wrapper validations -----
class NestedObjectsPlainSimpleConstraints(override val instance: String) extends ValidationBase[String] {
    override val reference = "⌿definitions⌿NestedObjects⌿plain⌿simple"
    override def constraints: Seq[Constraint[String]] =
        Seq(pattern("""the pattern""".r))
}
class NestedObjectsPlainSimpleValidator(instance: String) extends RecursiveValidator {
    override val reference = "⌿definitions⌿NestedObjects⌿plain⌿simple"
    override val validators = Seq(new NestedObjectsPlainSimpleConstraints(instance))
}
class NestedObjectsNestedNested2Nested3BottomOptConstraints(override val instance: String) extends ValidationBase[String] {
    override val reference = "⌿definitions⌿NestedObjects⌿nested⌿nested2⌿nested3⌿bottom⌿Opt"
    override def constraints: Seq[Constraint[String]] =
        Seq(maxLength(30), minLength(3))
}
class NestedObjectsNestedNested2Nested3BottomOptValidator(instance: String) extends RecursiveValidator {
    override val reference = "⌿definitions⌿NestedObjects⌿nested⌿nested2⌿nested3⌿bottom⌿Opt"
    override val validators = Seq(new NestedObjectsNestedNested2Nested3BottomOptConstraints(instance))
}
// ----- complex type validators -----
class NestedObjectsValidator(instance: NestedObjects) extends RecursiveValidator {
    override val reference = "⌿definitions⌿NestedObjects"
    override val validators = Seq(
        new NestedObjectsPlainValidator(instance.plain), 
        new NestedObjectsNestedValidator(instance.nested)
    )
}
class NestedObjectsPlainOptValidator(instance: NestedObjectsPlainOpt) extends RecursiveValidator {
    override val reference = "⌿definitions⌿NestedObjects⌿plain⌿Opt"
    override val validators = Seq(
        new NestedObjectsPlainSimpleValidator(instance.simple)
    )
}
class NestedObjectsNestedOptValidator(instance: NestedObjectsNestedOpt) extends RecursiveValidator {
    override val reference = "⌿definitions⌿NestedObjects⌿nested⌿Opt"
    override val validators = Seq(
        new NestedObjectsNestedNested2Validator(instance.nested2)
    )
}
class NestedObjectsNestedNested2Validator(instance: NestedObjectsNestedNested2) extends RecursiveValidator {
    override val reference = "⌿definitions⌿NestedObjects⌿nested⌿nested2"
    override val validators = Seq(
        new NestedObjectsNestedNested2Nested3Validator(instance.nested3)
    )
}
class NestedObjectsNestedNested2Nested3OptValidator(instance: NestedObjectsNestedNested2Nested3Opt) extends RecursiveValidator {
    override val reference = "⌿definitions⌿NestedObjects⌿nested⌿nested2⌿nested3⌿Opt"
    override val validators = Seq(
        new NestedObjectsNestedNested2Nested3BottomValidator(instance.bottom)
    )
}

// ----- option delegating validators -----
class NestedObjectsPlainValidator(instance: NestedObjectsPlain) extends RecursiveValidator {
    override val reference = "⌿definitions⌿NestedObjects⌿plain"
    override val validators = instance.toSeq.map { new NestedObjectsPlainOptValidator(_) }
}
class NestedObjectsNestedValidator(instance: NestedObjectsNested) extends RecursiveValidator {
    override val reference = "⌿definitions⌿NestedObjects⌿nested"
    override val validators = instance.toSeq.map { new NestedObjectsNestedOptValidator(_) }
}
class NestedObjectsNestedNested2Nested3Validator(instance: NestedObjectsNestedNested2Nested3) extends RecursiveValidator {
    override val reference = "⌿definitions⌿NestedObjects⌿nested⌿nested2⌿nested3"
    override val validators = instance.toSeq.map { new NestedObjectsNestedNested2Nested3OptValidator(_) }
}
class NestedObjectsNestedNested2Nested3BottomValidator(instance: NestedObjectsNestedNested2Nested3Bottom) extends RecursiveValidator {
    override val reference = "⌿definitions⌿NestedObjects⌿nested⌿nested2⌿nested3⌿bottom"
    override val validators = instance.toSeq.map { new NestedObjectsNestedNested2Nested3BottomOptValidator(_) }
}
// ----- array delegating validators -----
// ----- catch all simple validators -----
// ----- composite validators -----
// ----- call validations -----
class GetValidator(nestedObject: NestedObjects) extends RecursiveValidator {
    override val reference = "⌿paths⌿⌿get"
    override val validators = Seq(
        new NestedObjectsValidator(nestedObject)
    
    )
} 
Example 30
Source File: security_api_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package security.api.yaml
import play.api.mvc.{Action, Controller}
import play.api.data.validation.Constraint
import de.zalando.play.controllers._
import PlayBodyParsing._
import PlayValidations._

import de.zalando.play.controllers.ArrayWrapper
// ----- constraints and wrapper validations -----
class PetsIdGetIdArrConstraints(override val instance: String) extends ValidationBase[String] {
    override val reference = "⌿paths⌿/pets/{id}⌿get⌿id⌿Arr"
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class PetsIdGetIdArrValidator(instance: String) extends RecursiveValidator {
    override val reference = "⌿paths⌿/pets/{id}⌿get⌿id⌿Arr"
    override val validators = Seq(new PetsIdGetIdArrConstraints(instance))
}
// ----- complex type validators -----

// ----- option delegating validators -----
// ----- array delegating validators -----
class PetsIdGetIdConstraints(override val instance: PetsIdGetId) extends ValidationBase[PetsIdGetId] {
    override val reference = "⌿paths⌿/pets/{id}⌿get⌿id"
    override def constraints: Seq[Constraint[PetsIdGetId]] =
        Seq()
}
class PetsIdGetIdValidator(instance: PetsIdGetId) extends RecursiveValidator {
    override val reference = "⌿paths⌿/pets/{id}⌿get⌿id"
    override val validators = new PetsIdGetIdConstraints(instance) +: instance.map { new PetsIdGetIdArrValidator(_)}
}
// ----- catch all simple validators -----
// ----- composite validators -----
// ----- call validations -----
class PetsIdGetValidator(id: PetsIdGetId) extends RecursiveValidator {
    override val reference = "⌿paths⌿pets⌿{id}⌿get"
    override val validators = Seq(
        new PetsIdGetIdValidator(id)
    
    )
} 
Example 31
Source File: AdvicesController.scala    From scala-clippy   with Apache License 2.0 5 votes vote down vote up
package controllers

import com.softwaremill.clippy.{Advice, Clippy}
import dal.AdvicesRepository
import play.api.mvc.{Action, Controller}
import util.{ClippyBuildInfo, Zip}

import scala.concurrent.{ExecutionContext, Future}

class AdvicesController(advicesRepository: AdvicesRepository)(implicit ec: ExecutionContext) extends Controller {
  def get = Action.async {
    gzippedAdvices.map(a => Ok(a).withHeaders("Content-Encoding" -> "gzip"))
  }

  def gzippedAdvices: Future[Array[Byte]] =
    advicesRepository.findAll().map { storedAdvices =>
      // TODO, once there's an admin: filter out not accepted advice
      val advices = storedAdvices
      //.filter(_.accepted)
        .map(_.toAdvice)
      Zip.compress(toJsonString(advices.toList))
    }

  private def toJsonString(advices: List[Advice]): String = {
    import org.json4s.native.JsonMethods.{render => r, compact}
    compact(r(Clippy(ClippyBuildInfo.version, advices, Nil).toJson))
  }
} 
Example 32
Source File: AutowireController.scala    From scala-clippy   with Apache License 2.0 5 votes vote down vote up
package controllers

import com.softwaremill.clippy.UiApi
import play.api.mvc.{Action, Controller}

import upickle.default._
import upickle.Js

import scala.concurrent.ExecutionContext

class AutowireController(uiApi: UiApi)(implicit ec: ExecutionContext) extends Controller {

  def autowireApi(path: String) = Action.async { implicit request =>
    val b = request.body.asText.getOrElse("")

    AutowireServer
      .route[UiApi](uiApi)(
        autowire.Core.Request(
          path.split("/"),
          upickle.json.read(b).asInstanceOf[Js.Obj].value.toMap
        )
      )
      .map(jsv => Ok(upickle.json.write(jsv)))
  }
}

object AutowireServer extends autowire.Server[Js.Value, Reader, Writer] {
  def read[Result: Reader](p: Js.Value) = upickle.default.readJs[Result](p)
  def write[Result: Writer](r: Result)  = upickle.default.writeJs(r)
} 
Example 33
Source File: ResetPasswordController.scala    From play-silhouette-reactivemongo-seed   with Apache License 2.0 5 votes vote down vote up
package controllers

import java.util.UUID
import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.util.{ PasswordHasherRegistry, PasswordInfo }
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import forms.ResetPasswordForm
import models.services.{ AuthTokenService, UserService }
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.Controller
import utils.auth.DefaultEnv

import scala.concurrent.Future


  def submit(token: UUID) = silhouette.UnsecuredAction.async { implicit request =>
    authTokenService.validate(token).flatMap {
      case Some(authToken) =>
        ResetPasswordForm.form.bindFromRequest.fold(
          form => Future.successful(BadRequest(views.html.resetPassword(form, token))),
          password => userService.retrieve(authToken.userID).flatMap {
            case Some(user) if user.loginInfo.providerID == CredentialsProvider.ID =>
              val passwordInfo = passwordHasherRegistry.current.hash(password)
              authInfoRepository.update[PasswordInfo](user.loginInfo, passwordInfo).map { _ =>
                Redirect(routes.SignInController.view()).flashing("success" -> Messages("password.reset"))
              }
            case _ => Future.successful(Redirect(routes.SignInController.view()).flashing("error" -> Messages("invalid.reset.link")))
          }
        )
      case None => Future.successful(Redirect(routes.SignInController.view()).flashing("error" -> Messages("invalid.reset.link")))
    }
  }
} 
Example 34
Source File: ChangePasswordController.scala    From play-silhouette-4.0-slick-postgres-seed   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.exceptions.ProviderException
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.util.{ Credentials, PasswordHasherRegistry, PasswordInfo }
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import controllers.{ WebJarAssets, auth }
import forms.auth.ChangePasswordForm
import models.services.UserService
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.{ Action, AnyContent, Controller }
import utils.auth.{ DefaultEnv, WithProvider }

import scala.concurrent.Future


  def submit: Action[AnyContent] = silhouette.SecuredAction(WithProvider[DefaultEnv#A](CredentialsProvider.ID)).async { implicit request =>
    ChangePasswordForm.form.bindFromRequest.fold(
      form => Future.successful(BadRequest(views.html.auth.changePassword(form, request.identity))),
      password => {
        val (currentPassword, newPassword) = password
        val credentials = Credentials(request.identity.email.getOrElse(""), currentPassword)
        credentialsProvider.authenticate(credentials).flatMap { loginInfo =>
          val passwordInfo = passwordHasherRegistry.current.hash(newPassword)
          authInfoRepository.update[PasswordInfo](loginInfo, passwordInfo).map { _ =>
            Redirect(auth.routes.ChangePasswordController.view()).flashing("success" -> Messages("password.changed"))
          }
        }.recover {
          case e: ProviderException =>
            Redirect(auth.routes.ChangePasswordController.view()).flashing("error" -> Messages("current.password.invalid"))
        }
      }
    )
  }
} 
Example 35
Source File: SignInController.scala    From play-silhouette-4.0-slick-postgres-seed   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import javax.inject.Inject

import com.mohiva.play.silhouette.api.Authenticator.Implicits._
import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.exceptions.ProviderException
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.util.{ Clock, Credentials }
import com.mohiva.play.silhouette.impl.exceptions.IdentityNotFoundException
import com.mohiva.play.silhouette.impl.providers._
import controllers.{ WebJarAssets, auth, pages }
import forms.auth.SignInForm
import models.services.UserService
import net.ceedubs.ficus.Ficus._
import play.api.Configuration
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.{ Action, AnyContent, Controller }
import utils.auth.DefaultEnv

import scala.concurrent.Future
import scala.concurrent.duration._
import scala.language.postfixOps


  def submit: Action[AnyContent] = silhouette.UnsecuredAction.async { implicit request =>
    SignInForm.form.bindFromRequest.fold(
      form => Future.successful(BadRequest(views.html.auth.signIn(form, socialProviderRegistry))),
      data => {
        val credentials = Credentials(data.email, data.password)
        credentialsProvider.authenticate(credentials).flatMap { loginInfo =>
          val result = Redirect(pages.routes.ApplicationController.index())
          userService.retrieve(loginInfo).flatMap {
            case Some(user) if !user.activated =>
              Future.successful(Ok(views.html.auth.activateAccount(data.email)))
            case Some(user) =>
              val c = configuration.underlying
              silhouette.env.authenticatorService.create(loginInfo).map {
                case authenticator if data.rememberMe =>
                  authenticator.copy(
                    expirationDateTime = clock.now + c.as[FiniteDuration]("silhouette.authenticator.rememberMe.authenticatorExpiry"),
                    idleTimeout = c.getAs[FiniteDuration]("silhouette.authenticator.rememberMe.authenticatorIdleTimeout"),
                    cookieMaxAge = c.getAs[FiniteDuration]("silhouette.authenticator.rememberMe.cookieMaxAge")
                  )
                case authenticator => authenticator
              }.flatMap { authenticator =>
                silhouette.env.eventBus.publish(LoginEvent(user, request))
                silhouette.env.authenticatorService.init(authenticator).flatMap { v =>
                  silhouette.env.authenticatorService.embed(v, result)
                }
              }
            case None => Future.failed(new IdentityNotFoundException("Couldn't find user"))
          }
        }.recover {
          case e: ProviderException =>
            Redirect(auth.routes.SignInController.view()).flashing("error" -> Messages("invalid.credentials"))
        }
      }
    )
  }
} 
Example 36
Source File: ResetPasswordController.scala    From play-silhouette-4.0-slick-postgres-seed   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import java.util.UUID
import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.util.{ PasswordHasherRegistry, PasswordInfo }
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import controllers.{ WebJarAssets, auth }
import forms.auth.ResetPasswordForm
import models.services.{ AuthTokenService, UserService }
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.{ Action, AnyContent, Controller }
import utils.auth.DefaultEnv

import scala.concurrent.Future


  def submit(token: UUID): Action[AnyContent] = silhouette.UnsecuredAction.async { implicit request =>
    authTokenService.validate(token).flatMap {
      case Some(authToken) =>
        ResetPasswordForm.form.bindFromRequest.fold(
          form => Future.successful(BadRequest(views.html.auth.resetPassword(form, token))),
          password => userService.retrieve(authToken.userID).flatMap {
            case Some(user) if user.loginInfo.providerID == CredentialsProvider.ID =>
              val passwordInfo = passwordHasherRegistry.current.hash(password)
              authInfoRepository.update[PasswordInfo](user.loginInfo, passwordInfo).map { _ =>
                Redirect(auth.routes.SignInController.view()).flashing("success" -> Messages("password.reset"))
              }
            case _ => Future.successful(Redirect(auth.routes.SignInController.view()).flashing("error" -> Messages("invalid.reset.link")))
          }
        )
      case None => Future.successful(Redirect(auth.routes.SignInController.view()).flashing("error" -> Messages("invalid.reset.link")))
    }
  }
} 
Example 37
Source File: SignUpController.scala    From play-silhouette-4.0-slick-postgres-seed   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import java.util.UUID
import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.services.AvatarService
import com.mohiva.play.silhouette.api.util.PasswordHasherRegistry
import com.mohiva.play.silhouette.impl.providers._
import controllers.{ WebJarAssets, auth }
import forms.auth.SignUpForm
import models.User
import models.services.{ AuthTokenService, UserService }
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.mailer.{ Email, MailerClient }
import play.api.mvc.{ Action, AnyContent, Controller }
import utils.auth.DefaultEnv

import scala.concurrent.Future


  def submit: Action[AnyContent] = silhouette.UnsecuredAction.async { implicit request =>
    SignUpForm.form.bindFromRequest.fold(
      form => Future.successful(BadRequest(views.html.auth.signUp(form))),
      data => {
        val result = Redirect(auth.routes.SignUpController.view()).flashing("info" -> Messages("sign.up.email.sent", data.email))
        val loginInfo = LoginInfo(CredentialsProvider.ID, data.email)
        userService.retrieve(loginInfo).flatMap {
          case Some(user) =>
            val url = auth.routes.SignInController.view().absoluteURL()
            mailerClient.send(Email(
              subject = Messages("email.already.signed.up.subject"),
              from = Messages("email.from"),
              to = Seq(data.email),
              bodyText = Some(views.txt.emails.alreadySignedUp(user, url).body),
              bodyHtml = Some(views.html.emails.alreadySignedUp(user, url).body)
            ))

            Future.successful(result)
          case None =>
            val authInfo = passwordHasherRegistry.current.hash(data.password)
            val user = User(
              userID = UUID.randomUUID(),
              loginInfo = loginInfo,
              firstName = Some(data.firstName),
              lastName = Some(data.lastName),
              fullName = Some(data.firstName + " " + data.lastName),
              email = Some(data.email),
              avatarURL = None,
              activated = false
            )
            for {
              avatar <- avatarService.retrieveURL(data.email)
              user <- userService.save(user.copy(avatarURL = avatar))
              authInfo <- authInfoRepository.add(loginInfo, authInfo)
              authToken <- authTokenService.create(user.userID)
            } yield {
              val url = auth.routes.ActivateAccountController.activate(authToken.id).absoluteURL()
              mailerClient.send(Email(
                subject = Messages("email.sign.up.subject"),
                from = Messages("email.from"),
                to = Seq(data.email),
                bodyText = Some(views.txt.emails.signUp(user, url).body),
                bodyHtml = Some(views.html.emails.signUp(user, url).body)
              ))

              silhouette.env.eventBus.publish(SignUpEvent(user, request))
              result
            }
        }
      }
    )
  }
} 
Example 38
Source File: ActivateAccountController.scala    From play-silhouette-4.0-slick-postgres-seed   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import java.net.URLDecoder
import java.util.UUID
import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import controllers.{ WebJarAssets, auth }
import models.services.{ AuthTokenService, UserService }
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.mailer.{ Email, MailerClient }
import play.api.mvc.{ Action, AnyContent, Controller }
import utils.auth.DefaultEnv

import scala.concurrent.Future
import scala.language.postfixOps


  def activate(token: UUID): Action[AnyContent] = silhouette.UnsecuredAction.async { implicit request =>
    authTokenService.validate(token).flatMap {
      case Some(authToken) => userService.retrieve(authToken.userID).flatMap {
        case Some(user) if user.loginInfo.providerID == CredentialsProvider.ID =>
          userService.save(user.copy(activated = true)).map { _ =>
            Redirect(auth.routes.SignInController.view()).flashing("success" -> Messages("account.activated"))
          }
        case _ => Future.successful(Redirect(auth.routes.SignInController.view()).flashing("error" -> Messages("invalid.activation.link")))
      }
      case None => Future.successful(Redirect(auth.routes.SignInController.view()).flashing("error" -> Messages("invalid.activation.link")))
    }
  }
} 
Example 39
Source File: ForgotPasswordController.scala    From play-silhouette-4.0-slick-postgres-seed   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import controllers.{ WebJarAssets, auth }
import forms.auth.ForgotPasswordForm
import models.services.{ AuthTokenService, UserService }
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.mailer.{ Email, MailerClient }
import play.api.mvc.{ Action, AnyContent, Controller }
import utils.auth.DefaultEnv

import scala.concurrent.Future


  def submit: Action[AnyContent] = silhouette.UnsecuredAction.async { implicit request =>
    ForgotPasswordForm.form.bindFromRequest.fold(
      form => Future.successful(BadRequest(views.html.auth.forgotPassword(form))),
      email => {
        val loginInfo = LoginInfo(CredentialsProvider.ID, email)
        val result = Redirect(auth.routes.SignInController.view()).flashing("info" -> Messages("reset.email.sent"))
        userService.retrieve(loginInfo).flatMap {
          case Some(user) if user.email.isDefined =>
            authTokenService.create(user.userID).map { authToken =>
              val url = auth.routes.ResetPasswordController.view(authToken.id).absoluteURL()

              mailerClient.send(Email(
                subject = Messages("email.reset.password.subject"),
                from = Messages("email.from"),
                to = Seq(email),
                bodyText = Some(views.txt.emails.resetPassword(user, url).body),
                bodyHtml = Some(views.html.emails.resetPassword(user, url).body)
              ))
              result
            }
          case None => Future.successful(result)
        }
      }
    )
  }
} 
Example 40
Source File: VertexController.scala    From incubator-s2graph   with Apache License 2.0 5 votes vote down vote up
package org.apache.s2graph.rest.play.controllers

import org.apache.s2graph.core.rest.RequestParser
import org.apache.s2graph.core.storage.MutateResponse
import org.apache.s2graph.core.utils.logger
import org.apache.s2graph.core.{ExceptionHandler, GraphExceptions, S2Graph}
import org.apache.s2graph.rest.play.actors.QueueActor
import org.apache.s2graph.rest.play.config.Config
import play.api.libs.json.{JsValue, Json}
import play.api.mvc.{Controller, Result}

import scala.concurrent.Future

object VertexController extends Controller {
  private val s2: S2Graph = org.apache.s2graph.rest.play.Global.s2graph
  private val requestParser: RequestParser = org.apache.s2graph.rest.play.Global.s2parser
  private val walLogHandler: ExceptionHandler = org.apache.s2graph.rest.play.Global.wallLogHandler

  import ApplicationController._
  import ExceptionHandler._
  import play.api.libs.concurrent.Execution.Implicits._

  def tryMutates(jsValue: JsValue, operation: String, serviceNameOpt: Option[String] = None, columnNameOpt: Option[String] = None, withWait: Boolean = false): Future[Result] = {
    if (!Config.IS_WRITE_SERVER) Future.successful(Unauthorized)
    else {
      try {
        val vertices = requestParser.toVertices(jsValue, operation, serviceNameOpt, columnNameOpt)

        for (vertex <- vertices) {
          val kafkaTopic = toKafkaTopic(vertex.isAsync)
          walLogHandler.enqueue(toKafkaMessage(kafkaTopic, vertex, None))
        }

        //FIXME:
        val verticesToStore = vertices.filterNot(v => skipElement(v.isAsync))
        if (verticesToStore.isEmpty) Future.successful(jsonResponse(Json.toJson(Seq.empty[Boolean])))
        else {
          if (withWait) {
            val rets = s2.mutateVertices(verticesToStore, withWait = true).map(_.map(_.isSuccess))
            rets.map(Json.toJson(_)).map(jsonResponse(_))
          } else {
            val rets = verticesToStore.map { vertex => QueueActor.router ! vertex; true }
            Future.successful(jsonResponse(Json.toJson(rets)))
          }
        }
      } catch {
        case e: GraphExceptions.JsonParseException => Future.successful(BadRequest(s"e"))
        case e: Exception =>
          logger.error(s"[Failed] tryMutates", e)
          Future.successful(InternalServerError(s"${e.getStackTrace}"))
      }
    }
  }

  def inserts() = withHeaderAsync(jsonParser) { request =>
    tryMutates(request.body, "insert")
  }

  def insertsWithWait() = withHeaderAsync(jsonParser) { request =>
    tryMutates(request.body, "insert", withWait = true)
  }

  def insertsSimple(serviceName: String, columnName: String) = withHeaderAsync(jsonParser) { request =>
    tryMutates(request.body, "insert", Some(serviceName), Some(columnName))
  }

  def deletes() = withHeaderAsync(jsonParser) { request =>
    tryMutates(request.body, "delete")
  }

  def deletesWithWait() = withHeaderAsync(jsonParser) { request =>
    tryMutates(request.body, "delete", withWait = true)
  }

  def deletesSimple(serviceName: String, columnName: String) = withHeaderAsync(jsonParser) { request =>
    tryMutates(request.body, "delete", Some(serviceName), Some(columnName))
  }

  def deletesAll() = withHeaderAsync(jsonParser) { request =>
    tryMutates(request.body, "deleteAll")
  }

  def deletesAllSimple(serviceName: String, columnName: String) = withHeaderAsync(jsonParser) { request =>
    tryMutates(request.body, "deleteAll", Some(serviceName), Some(columnName))
  }

} 
Example 41
Source File: entity_manager.yaml.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
import play.api.mvc.{Action,Controller}

import play.api.data.validation.Constraint

import play.api.i18n.MessagesApi

import play.api.inject.{ApplicationLifecycle,ConfigurationProvider}

import de.zalando.play.controllers._

import PlayBodyParsing._

import PlayValidations._

import scala.util._

import javax.inject._

import de.zalando.play.controllers.PlayBodyParsing._
import org.apache.tinkerpop.gremlin.structure.{T,Vertex}
import org.janusgraph.core.attribute.Geoshape
import org.janusgraph.core.schema.JanusGraphManagement
import org.janusgraph.core.{JanusGraphFactory,PropertyKey}
import org.janusgraph.diskstorage.configuration.backend.CommonsConfiguration
import scala.concurrent.Future
import org.janusgraph.core.Cardinality
import collection.convert.decorateAsScala._
import collection.convert.decorateAsScala._
import collection.convert.decorateAsScala._
import collection.convert.decorateAsScala._
import collection.convert.decorateAsScala._
import collection.convert.decorateAsScala._


    lifecycle.addStopHook { () =>
      Future.successful({
        graph.close()
      })
    }

        // ----- End of unmanaged code area for constructor Entity_managerYaml
        val getEntities = getEntitiesAction { input: (EntitiesGetPageNumber, EntitiesGetPageNumber) =>
            val (pageSize, pageNumber) = input
            // ----- Start of unmanaged code area for action  Entity_managerYaml.getEntities
            NotImplementedYet
            // ----- End of unmanaged code area for action  Entity_managerYaml.getEntities
        }
        val createEntity = createEntityAction { (entity: Entity) =>  
            // ----- Start of unmanaged code area for action  Entity_managerYaml.createEntity
            val tx = graph.newTransaction
      val vertex = tx.addVertex(T.label, "entity", "entityName", entity.entityname)
      val id = vertex.id().asInstanceOf[Long]
      tx.commit()
      CreateEntity200(EntityId(id))
            // ----- End of unmanaged code area for action  Entity_managerYaml.createEntity
        }
        val getEntity = getEntityAction { (entityname: String) =>  
            // ----- Start of unmanaged code area for action  Entity_managerYaml.getEntity
            import collection.convert.decorateAsScala._
      val vertices = graph.traversal.V().has("entityName", entityname).asScala
      if (vertices.isEmpty)
        GetEntity404()
      else {
        val vertex = vertices.next()
        GetEntity200(Entity(vertex.property[String]("entityName").value()))
      }
            // ----- End of unmanaged code area for action  Entity_managerYaml.getEntity
        }
    
    }
} 
Example 42
Source File: WebSocket.scala    From trucking-iot   with Apache License 2.0 5 votes vote down vote up
package controllers

import javax.inject.{Inject, Singleton}

import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import akka.kafka.scaladsl.Consumer
import akka.kafka.{ConsumerSettings, Subscriptions}
import akka.stream.scaladsl.Sink
import akka.stream.{Materializer, ThrottleMode}
import com.typesafe.config.ConfigFactory
import org.apache.kafka.clients.consumer.ConsumerConfig
import org.apache.kafka.common.serialization.{ByteArrayDeserializer, StringDeserializer}
import play.api.libs.streams.ActorFlow
import play.api.mvc.{Controller, WebSocket}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.concurrent.duration._


//@Singleton
class KafkaWebSocket @Inject() (implicit system: ActorSystem, materializer: Materializer) extends Controller {

  def kafkaWS = WebSocket.accept[String, String] { request =>
    ActorFlow.actorRef(out => KafkaWSActor.props(out))
  }

  object KafkaWSActor {
    def props(outRef: ActorRef) = Props(new KafkaWSActor(outRef))
  }

  class KafkaWSActor(outRef: ActorRef) extends Actor {

    val config = ConfigFactory.load()
    val combinedConfig = ConfigFactory.defaultOverrides()
      .withFallback(config)
      .withFallback(ConfigFactory.defaultApplication())
      .getConfig("trucking-web-application.backend")

    val consumerSettings = ConsumerSettings(system, new ByteArrayDeserializer, new StringDeserializer)
      //.withBootstrapServers("sandbox-hdf.hortonworks.com:6667")
      .withBootstrapServers(combinedConfig.getString("kafka.bootstrap-servers"))
      .withGroupId("group1")
      .withProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest")

    Consumer.committableSource(consumerSettings, Subscriptions.topics("trucking_data_joined"))
      .mapAsync(1) { msg => Future(outRef ! msg.record.value).map(_ => msg) }
      //.mapAsync(1) { msg => msg.committableOffset.commitScaladsl() } // TODO: Disabling commits for debug
      .throttle(1, 250.milliseconds, 1, ThrottleMode.Shaping)
      .runWith(Sink.ignore)

    def receive = {
      case msg: String => outRef ! s"Ack: $msg"
    }
  }

} 
Example 43
Source File: LaboratoryController.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers.api

import com.fasterxml.jackson.annotation.JsonValue
import com.google.inject.Inject
import dao.{LaboratoryDAO, UserDAO}
import jp.t2v.lab.play2.auth.OptionalAuthElement
import model._
import model.json.LoginJson
import play.Logger
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.libs.json.{JsValue, Json, Writes}
import play.api.mvc.{Action, AnyContent, Controller}
import services.LaboratoryService
import views.html._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{ExecutionContext, Future}


class LaboratoryController @Inject()(userDAO: UserDAO, laboratoryService: LaboratoryService, val messagesApi: MessagesApi) extends Controller with I18nSupport {



  //override def resolveUser(id: LoginFormData)(implicit context: ExecutionContext): Future[Option[User]] = userDAO.get(id)

  def convertToJson(laboratoryObject: Laboratory, roomsWithComputers: Map[Room, Seq[(Computer, Option[(ComputerState, Seq[ConnectedUser])])]]): JsValue = {
    val roomsConverted = roomsWithComputers.toSeq
    val grouped = roomsConverted.groupBy(_._1)
    val resultRooms = grouped.map(filtered=>(filtered._1,filtered._2.map(_._2).head)).toSeq
    Json.toJson((laboratoryObject,resultRooms))
  }

  def get(id: Long) = Action.async { implicit request =>
    Logger.debug("Petición de listar el laboratory " + id + " [API] respondida.")
    implicit val username = Some("")
    laboratoryService.get(id).map {
      case Some((laboratoryObject, roomsWithComputers)) => Ok(convertToJson(laboratoryObject, roomsWithComputers))
      case _ => NotFound(Json.parse(
        """
          |{
          |  "answer"->"no encontrado"
          |}
        """))
    }
  }


} 
Example 44
Source File: ComputerController.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers.api

import com.google.inject.Inject
import dao.{ComputerDAO, UserDAO}
import play.Logger
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.libs.json.Json
import play.api.mvc.{Action, Controller}
import services.state.ActionCompleted
import services.{ComputerService, LaboratoryService, SSHOrderService}
import views.html._

import scala.concurrent.ExecutionContext.Implicits.global


class ComputerController @Inject()(computerService: ComputerService, computerDAO: ComputerDAO, sSHOrderService: SSHOrderService, val messagesApi: MessagesApi) extends Controller with I18nSupport {

  def shutdown(ip: String) = Action.async {
    implicit request =>
      computerDAO.get(ip).map {
        case Some(computer) if sSHOrderService.shutdown(computer)("Scheduled Checker")==ActionCompleted => Ok(Json.parse(
          """
            {
               "answer":"shutted down"
            }
          """))
        case _ => NotFound(Json.parse(
          """
            {
               "answer":"not found"
            }
          """))
      }
  }
} 
Example 45
Source File: UsersController.scala    From play-quill-jdbc   with MIT License 5 votes vote down vote up
package controllers

import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.mvc.{Action, Controller}
import models.{User, Users}

class UsersController(userServices: Users) extends Controller {

  implicit val userWrites: Writes[User] = Json.writes[User]
  implicit val userReads: Reads[User] = (
      Reads.pure(0L) and
      (JsPath \ "name").read[String] and
      (JsPath \ "isActive").read[Boolean]
    )(User.apply _)

  def get(id: Long) = Action { request =>
    userServices.find(id) match {
      case None => NotFound
      case Some(user) => Ok(Json.toJson(user))
    }
  }

  def create = Action(parse.json) { request =>
    Json.fromJson[User](request.body).fold(
      invalid => BadRequest,
      user => {
        val userCreated = userServices.create(user)
        Created.withHeaders(LOCATION -> s"/users/${userCreated.id}")
      }
    )
  }

  def delete(id: Long) = Action { request =>
    userServices.find(id) match {
      case None => NotFound
      case Some(user) =>
        userServices.delete(user)
        NoContent
    }
  }

  def update(id: Long) = Action(parse.json) { request =>
    Json.fromJson[User](request.body).fold(
      invalid => BadRequest,
      user => {
        userServices.update(user.copy(id = id))
        NoContent
      }
    )
  }
} 
Example 46
Source File: SocialAuthController.scala    From play-silhouette-reactivemongo-seed   with Apache License 2.0 5 votes vote down vote up
package controllers

import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.exceptions.ProviderException
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.impl.providers._
import models.services.UserService
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.{ Action, Controller }
import utils.auth.DefaultEnv

import scala.concurrent.Future


  def authenticate(provider: String) = Action.async { implicit request =>
    (socialProviderRegistry.get[SocialProvider](provider) match {
      case Some(p: SocialProvider with CommonSocialProfileBuilder) =>
        p.authenticate().flatMap {
          case Left(result) => Future.successful(result)
          case Right(authInfo) => for {
            profile <- p.retrieveProfile(authInfo)
            user <- userService.save(profile)
            authInfo <- authInfoRepository.save(profile.loginInfo, authInfo)
            authenticator <- silhouette.env.authenticatorService.create(profile.loginInfo)
            value <- silhouette.env.authenticatorService.init(authenticator)
            result <- silhouette.env.authenticatorService.embed(value, Redirect(routes.ApplicationController.index()))
          } yield {
            silhouette.env.eventBus.publish(LoginEvent(user, request))
            result
          }
        }
      case _ => Future.failed(new ProviderException(s"Cannot authenticate with unexpected social provider $provider"))
    }).recover {
      case e: ProviderException =>
        logger.error("Unexpected provider error", e)
        Redirect(routes.SignInController.view()).flashing("error" -> Messages("could.not.authenticate"))
    }
  }
} 
Example 47
Source File: ChangePasswordController.scala    From play-silhouette-reactivemongo-seed   with Apache License 2.0 5 votes vote down vote up
package controllers

import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.exceptions.ProviderException
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.util.{ Credentials, PasswordHasherRegistry, PasswordInfo }
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import forms.ChangePasswordForm
import models.services.UserService
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.Controller
import utils.auth.{ DefaultEnv, WithProvider }

import scala.concurrent.Future


  def submit = silhouette.SecuredAction(WithProvider[DefaultEnv#A](CredentialsProvider.ID)).async { implicit request =>
    ChangePasswordForm.form.bindFromRequest.fold(
      form => Future.successful(BadRequest(views.html.changePassword(form, request.identity))),
      password => {
        val (currentPassword, newPassword) = password
        val credentials = Credentials(request.identity.email.getOrElse(""), currentPassword)
        credentialsProvider.authenticate(credentials).flatMap { loginInfo =>
          val passwordInfo = passwordHasherRegistry.current.hash(newPassword)
          authInfoRepository.update[PasswordInfo](loginInfo, passwordInfo).map { _ =>
            Redirect(routes.ChangePasswordController.view()).flashing("success" -> Messages("password.changed"))
          }
        }.recover {
          case e: ProviderException =>
            Redirect(routes.ChangePasswordController.view()).flashing("error" -> Messages("current.password.invalid"))
        }
      }
    )
  }
} 
Example 48
Source File: SignInController.scala    From play-silhouette-reactivemongo-seed   with Apache License 2.0 5 votes vote down vote up
package controllers

import javax.inject.Inject

import com.mohiva.play.silhouette.api.Authenticator.Implicits._
import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.exceptions.ProviderException
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.util.{ Clock, Credentials }
import com.mohiva.play.silhouette.impl.exceptions.IdentityNotFoundException
import com.mohiva.play.silhouette.impl.providers._
import forms.SignInForm
import models.services.UserService
import net.ceedubs.ficus.Ficus._
import play.api.Configuration
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.Controller
import utils.auth.DefaultEnv

import scala.concurrent.Future
import scala.concurrent.duration._
import scala.language.postfixOps


  def submit = silhouette.UnsecuredAction.async { implicit request =>
    SignInForm.form.bindFromRequest.fold(
      form => Future.successful(BadRequest(views.html.signIn(form, socialProviderRegistry))),
      data => {
        val credentials = Credentials(data.email, data.password)
        credentialsProvider.authenticate(credentials).flatMap { loginInfo =>
          val result = Redirect(routes.ApplicationController.index())
          userService.retrieve(loginInfo).flatMap {
            case Some(user) if !user.activated =>
              Future.successful(Ok(views.html.activateAccount(data.email)))
            case Some(user) =>
              val c = configuration.underlying
              silhouette.env.authenticatorService.create(loginInfo).map {
                case authenticator if data.rememberMe =>
                  authenticator.copy(
                    expirationDateTime = clock.now + c.as[FiniteDuration]("silhouette.authenticator.rememberMe.authenticatorExpiry"),
                    idleTimeout = c.getAs[FiniteDuration]("silhouette.authenticator.rememberMe.authenticatorIdleTimeout"),
                    cookieMaxAge = c.getAs[FiniteDuration]("silhouette.authenticator.rememberMe.cookieMaxAge")
                  )
                case authenticator => authenticator
              }.flatMap { authenticator =>
                silhouette.env.eventBus.publish(LoginEvent(user, request))
                silhouette.env.authenticatorService.init(authenticator).flatMap { v =>
                  silhouette.env.authenticatorService.embed(v, result)
                }
              }
            case None => Future.failed(new IdentityNotFoundException("Couldn't find user"))
          }
        }.recover {
          case e: ProviderException =>
            Redirect(routes.SignInController.view()).flashing("error" -> Messages("invalid.credentials"))
        }
      }
    )
  }
} 
Example 49
Source File: SocialAuthController.scala    From play-silhouette-4.0-slick-postgres-seed   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.exceptions.ProviderException
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.impl.providers._
import controllers.{ WebJarAssets, auth, pages }
import models.services.UserService
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.{ Action, AnyContent, Controller }
import utils.auth.DefaultEnv

import scala.concurrent.Future


  def authenticate(provider: String): Action[AnyContent] = Action.async { implicit request =>
    (socialProviderRegistry.get[SocialProvider](provider) match {
      case Some(p: SocialProvider with CommonSocialProfileBuilder) =>
        p.authenticate().flatMap {
          case Left(result) => Future.successful(result)
          case Right(authInfo) => for {
            profile <- p.retrieveProfile(authInfo)
            user <- userService.save(profile)
            authInfo <- authInfoRepository.save(profile.loginInfo, authInfo)
            authenticator <- silhouette.env.authenticatorService.create(profile.loginInfo)
            value <- silhouette.env.authenticatorService.init(authenticator)
            result <- silhouette.env.authenticatorService.embed(value, Redirect(pages.routes.ApplicationController.index()))
          } yield {
            silhouette.env.eventBus.publish(LoginEvent(user, request))
            result
          }
        }
      case _ => Future.failed(new ProviderException(s"Cannot authenticate with unexpected social provider $provider"))
    }).recover {
      case e: ProviderException =>
        logger.error("Unexpected provider error", e)
        Redirect(auth.routes.SignInController.view()).flashing("error" -> Messages("could.not.authenticate"))
    }
  }
} 
Example 50
Source File: ActivateAccountController.scala    From play-silhouette-reactivemongo-seed   with Apache License 2.0 5 votes vote down vote up
package controllers

import java.net.URLDecoder
import java.util.UUID
import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import models.services.{ AuthTokenService, UserService }
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.mailer.{ Email, MailerClient }
import play.api.mvc.Controller
import utils.auth.DefaultEnv

import scala.concurrent.Future
import scala.language.postfixOps


  def activate(token: UUID) = silhouette.UnsecuredAction.async { implicit request =>
    authTokenService.validate(token).flatMap {
      case Some(authToken) => userService.retrieve(authToken.userID).flatMap {
        case Some(user) if user.loginInfo.providerID == CredentialsProvider.ID =>
          userService.save(user.copy(activated = true)).map { _ =>
            Redirect(routes.SignInController.view()).flashing("success" -> Messages("account.activated"))
          }
        case _ => Future.successful(Redirect(routes.SignInController.view()).flashing("error" -> Messages("invalid.activation.link")))
      }
      case None => Future.successful(Redirect(routes.SignInController.view()).flashing("error" -> Messages("invalid.activation.link")))
    }
  }
} 
Example 51
Source File: ForgotPasswordController.scala    From play-silhouette-reactivemongo-seed   with Apache License 2.0 5 votes vote down vote up
package controllers

import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import forms.ForgotPasswordForm
import models.services.{ AuthTokenService, UserService }
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.mailer.{ Email, MailerClient }
import play.api.mvc.Controller
import utils.auth.DefaultEnv

import scala.concurrent.Future


  def submit = silhouette.UnsecuredAction.async { implicit request =>
    ForgotPasswordForm.form.bindFromRequest.fold(
      form => Future.successful(BadRequest(views.html.forgotPassword(form))),
      email => {
        val loginInfo = LoginInfo(CredentialsProvider.ID, email)
        val result = Redirect(routes.SignInController.view()).flashing("info" -> Messages("reset.email.sent"))
        userService.retrieve(loginInfo).flatMap {
          case Some(user) if user.email.isDefined =>
            authTokenService.create(user.userID).map { authToken =>
              val url = routes.ResetPasswordController.view(authToken.id).absoluteURL()

              mailerClient.send(Email(
                subject = Messages("email.reset.password.subject"),
                from = Messages("email.from"),
                to = Seq(email),
                bodyText = Some(views.txt.emails.resetPassword(user, url).body),
                bodyHtml = Some(views.html.emails.resetPassword(user, url).body)
              ))
              result
            }
          case None => Future.successful(result)
        }
      }
    )
  }
} 
Example 52
Source File: nested_options_validation_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
package nested_options_validation.yaml
import play.api.mvc.{Action, Controller}
import play.api.data.validation.Constraint
import de.zalando.play.controllers._
import PlayBodyParsing._
import PlayValidations._

// ----- constraints and wrapper validations -----
class BasicOptionalNested_optionalOptConstraints(override val instance: String) extends ValidationBase[String] {
    override def constraints: Seq[Constraint[String]] =
        Seq(maxLength(6), minLength(5))
}
class BasicOptionalNested_optionalOptValidator(instance: String) extends RecursiveValidator {
    override val validators = Seq(new BasicOptionalNested_optionalOptConstraints(instance))
}
// ----- complex type validators -----
class BasicValidator(instance: Basic) extends RecursiveValidator {
    override val validators = Seq(
        new BasicOptionalValidator(instance.optional)
    )
}
class BasicOptionalOptValidator(instance: BasicOptionalOpt) extends RecursiveValidator {
    override val validators = Seq(
        new BasicOptionalNested_optionalValidator(instance.nested_optional)
    )
}
// ----- option delegating validators -----
class BasicOptionalValidator(instance: BasicOptional) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new BasicOptionalOptValidator(_) }
}
class BasicOptionalNested_optionalValidator(instance: BasicOptionalNested_optional) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new BasicOptionalNested_optionalOptValidator(_) }
}
// ----- array delegating validators -----
// ----- catch all simple validators -----
// ----- call validations -----
class GetValidator(basic: Basic) extends RecursiveValidator {
    override val validators = Seq(
        new BasicValidator(basic)
    
    )
} 
Example 53
Source File: heroku_petstore_api_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
package heroku.petstore.api.yaml
import play.api.mvc.{Action, Controller}
import play.api.data.validation.Constraint
import de.zalando.play.controllers._
import PlayBodyParsing._
import PlayValidations._

import scala.math.BigInt
// ----- constraints and wrapper validations -----
class PetIdGetPetIdConstraints(override val instance: String) extends ValidationBase[String] {
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class PetIdGetPetIdValidator(instance: String) extends RecursiveValidator {
    override val validators = Seq(new PetIdGetPetIdConstraints(instance))
}
class PetNameOptConstraints(override val instance: String) extends ValidationBase[String] {
    override def constraints: Seq[Constraint[String]] =
        Seq(maxLength(100), minLength(3))
}
class PetNameOptValidator(instance: String) extends RecursiveValidator {
    override val validators = Seq(new PetNameOptConstraints(instance))
}
class PetBirthdayOptConstraints(override val instance: Int) extends ValidationBase[Int] {
    override def constraints: Seq[Constraint[Int]] =
        Seq(max(100.toInt, false), min(1.toInt, false))
}
class PetBirthdayOptValidator(instance: Int) extends RecursiveValidator {
    override val validators = Seq(new PetBirthdayOptConstraints(instance))
}
class GetLimitConstraints(override val instance: BigInt) extends ValidationBase[BigInt] {
    override def constraints: Seq[Constraint[BigInt]] =
        Seq(max(BigInt("10000"), false), min(BigInt("11"), false))
}
class GetLimitValidator(instance: BigInt) extends RecursiveValidator {
    override val validators = Seq(new GetLimitConstraints(instance))
}
// ----- complex type validators -----
class PetValidator(instance: Pet) extends RecursiveValidator {
    override val validators = Seq(
        new PetNameValidator(instance.name), 
        new PetBirthdayValidator(instance.birthday)
    )
}
// ----- option delegating validators -----
class PetNameValidator(instance: PetName) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new PetNameOptValidator(_) }
}
class PetBirthdayValidator(instance: PetBirthday) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new PetBirthdayOptValidator(_) }
}
class PutPetValidator(instance: PutPet) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new PetValidator(_) }
}
// ----- array delegating validators -----
// ----- catch all simple validators -----
// ----- call validations -----
class PutValidator(pet: PutPet) extends RecursiveValidator {
    override val validators = Seq(
        new PutPetValidator(pet)
    
    )
}
class GetValidator(limit: BigInt) extends RecursiveValidator {
    override val validators = Seq(
        new GetLimitValidator(limit)
    
    )
}
class PetIdGetValidator(petId: String) extends RecursiveValidator {
    override val validators = Seq(
        new PetIdGetPetIdValidator(petId)
    
    )
}
class PostValidator(pet: Pet) extends RecursiveValidator {
    override val validators = Seq(
        new PetValidator(pet)
    
    )
} 
Example 54
Source File: expanded_polymorphism_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
package expanded
import play.api.mvc.{Action, Controller}
import play.api.data.validation.Constraint
import de.zalando.play.controllers._
import PlayBodyParsing._
import PlayValidations._

import de.zalando.play.controllers.ArrayWrapper
// ----- constraints and wrapper validations -----
class PetsIdDeleteIdConstraints(override val instance: Long) extends ValidationBase[Long] {
    override def constraints: Seq[Constraint[Long]] =
        Seq()
}
class PetsIdDeleteIdValidator(instance: Long) extends RecursiveValidator {
    override val validators = Seq(new PetsIdDeleteIdConstraints(instance))
}
class PetsGetLimitOptConstraints(override val instance: Int) extends ValidationBase[Int] {
    override def constraints: Seq[Constraint[Int]] =
        Seq(max(10.toInt, false), min(1.toInt, false))
}
class PetsGetLimitOptValidator(instance: Int) extends RecursiveValidator {
    override val validators = Seq(new PetsGetLimitOptConstraints(instance))
}
class PetsIdGetIdConstraints(override val instance: Long) extends ValidationBase[Long] {
    override def constraints: Seq[Constraint[Long]] =
        Seq()
}
class PetsIdGetIdValidator(instance: Long) extends RecursiveValidator {
    override val validators = Seq(new PetsIdGetIdConstraints(instance))
}
class PetsGetTagsOptArrConstraints(override val instance: String) extends ValidationBase[String] {
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class PetsGetTagsOptArrValidator(instance: String) extends RecursiveValidator {
    override val validators = Seq(new PetsGetTagsOptArrConstraints(instance))
}
class NewPetNameConstraints(override val instance: String) extends ValidationBase[String] {
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class NewPetNameValidator(instance: String) extends RecursiveValidator {
    override val validators = Seq(new NewPetNameConstraints(instance))
}
class NewPetTagOptConstraints(override val instance: String) extends ValidationBase[String] {
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class NewPetTagOptValidator(instance: String) extends RecursiveValidator {
    override val validators = Seq(new NewPetTagOptConstraints(instance))
}
// ----- complex type validators -----
class NewPetValidator(instance: NewPet) extends RecursiveValidator {
    override val validators = Seq(
        new NewPetNameValidator(instance.name), 
        new NewPetTagValidator(instance.tag)
    )
}
// ----- option delegating validators -----
class PetsGetLimitValidator(instance: PetsGetLimit) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new PetsGetLimitOptValidator(_) }
}
class PetsGetTagsValidator(instance: PetsGetTags) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new PetsGetTagsOptValidator(_) }
}
class NewPetTagValidator(instance: NewPetTag) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new NewPetTagOptValidator(_) }
}
// ----- array delegating validators -----
class PetsGetTagsOptConstraints(override val instance: PetsGetTagsOpt) extends ValidationBase[PetsGetTagsOpt] {
    override def constraints: Seq[Constraint[PetsGetTagsOpt]] =
        Seq()
}
class PetsGetTagsOptValidator(instance: PetsGetTagsOpt) extends RecursiveValidator {
    override val validators = new PetsGetTagsOptConstraints(instance) +: instance.map { new PetsGetTagsOptArrValidator(_)}
}
// ----- catch all simple validators -----
// ----- call validations -----
class PetsPostValidator(pet: NewPet) extends RecursiveValidator {
    override val validators = Seq(
        new NewPetValidator(pet)
    
    )
}
class PetsGetValidator(tags: PetsGetTags, limit: PetsGetLimit) extends RecursiveValidator {
    override val validators = Seq(
        new PetsGetTagsValidator(tags), 
    
        new PetsGetLimitValidator(limit)
    
    )
}
class PetsIdDeleteValidator(id: Long) extends RecursiveValidator {
    override val validators = Seq(
        new PetsIdDeleteIdValidator(id)
    
    )
} 
Example 55
Source File: string_formats_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
package string_formats.yaml
import play.api.mvc.{Action, Controller}
import play.api.data.validation.Constraint
import de.zalando.play.controllers._
import PlayBodyParsing._
import PlayValidations._

import de.zalando.play.controllers.Base64String
import Base64String._
import de.zalando.play.controllers.BinaryString
import BinaryString._
import org.joda.time.DateTime
import java.util.UUID
import org.joda.time.LocalDate
// ----- constraints and wrapper validations -----
class GetBase64OptConstraints(override val instance: String) extends ValidationBase[String] {
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class GetBase64OptValidator(instance: Base64String) extends RecursiveValidator {
    override val validators = Seq(new GetBase64OptConstraints(instance))
}
class GetPetIdConstraints(override val instance: String) extends ValidationBase[String] {
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class GetPetIdValidator(instance: BinaryString) extends RecursiveValidator {
    override val validators = Seq(new GetPetIdConstraints(instance))
}
class GetDate_timeOptConstraints(override val instance: DateTime) extends ValidationBase[DateTime] {
    override def constraints: Seq[Constraint[DateTime]] =
        Seq()
}
class GetDate_timeOptValidator(instance: DateTime) extends RecursiveValidator {
    override val validators = Seq(new GetDate_timeOptConstraints(instance))
}
class GetUuidOptConstraints(override val instance: UUID) extends ValidationBase[UUID] {
    override def constraints: Seq[Constraint[UUID]] =
        Seq()
}
class GetUuidOptValidator(instance: UUID) extends RecursiveValidator {
    override val validators = Seq(new GetUuidOptConstraints(instance))
}
class GetDateOptConstraints(override val instance: LocalDate) extends ValidationBase[LocalDate] {
    override def constraints: Seq[Constraint[LocalDate]] =
        Seq()
}
class GetDateOptValidator(instance: LocalDate) extends RecursiveValidator {
    override val validators = Seq(new GetDateOptConstraints(instance))
}
// ----- complex type validators -----
// ----- option delegating validators -----
class GetBase64Validator(instance: GetBase64) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new GetBase64OptValidator(_) }
}
class GetDate_timeValidator(instance: GetDate_time) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new GetDate_timeOptValidator(_) }
}
class GetUuidValidator(instance: GetUuid) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new GetUuidOptValidator(_) }
}
class GetDateValidator(instance: GetDate) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new GetDateOptValidator(_) }
}
// ----- array delegating validators -----
// ----- catch all simple validators -----
// ----- call validations -----
class GetValidator(date_time: GetDate_time, date: GetDate, base64: GetBase64, uuid: GetUuid, petId: BinaryString) extends RecursiveValidator {
    override val validators = Seq(
        new GetDate_timeValidator(date_time), 
    
        new GetDateValidator(date), 
    
        new GetBase64Validator(base64), 
    
        new GetUuidValidator(uuid), 
    
        new GetPetIdValidator(petId)
    
    )
} 
Example 56
Source File: echo_api_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
package echo
import play.api.mvc.{Action, Controller}
import play.api.data.validation.Constraint
import de.zalando.play.controllers._
import PlayBodyParsing._
import PlayValidations._

// ----- constraints and wrapper validations -----
class PostNameOptConstraints(override val instance: String) extends ValidationBase[String] {
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class PostNameOptValidator(instance: String) extends RecursiveValidator {
    override val validators = Seq(new PostNameOptConstraints(instance))
}
class Test_pathIdGetIdConstraints(override val instance: String) extends ValidationBase[String] {
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class Test_pathIdGetIdValidator(instance: String) extends RecursiveValidator {
    override val validators = Seq(new Test_pathIdGetIdConstraints(instance))
}
// ----- complex type validators -----
// ----- option delegating validators -----
class PostNameValidator(instance: PostName) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new PostNameOptValidator(_) }
}
// ----- array delegating validators -----
// ----- catch all simple validators -----
// ----- call validations -----
class Test_pathIdGetValidator(id: String) extends RecursiveValidator {
    override val validators = Seq(
        new Test_pathIdGetIdValidator(id)
    
    )
}
class PostValidator(name: PostName, year: PostName) extends RecursiveValidator {
    override val validators = Seq(
        new PostNameValidator(name), 
    
        new PostNameValidator(year)
    
    )
} 
Example 57
Source File: nested_objects_validation_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
package nested_objects_validation.yaml
import play.api.mvc.{Action, Controller}
import play.api.data.validation.Constraint
import de.zalando.play.controllers._
import PlayBodyParsing._
import PlayValidations._

// ----- constraints and wrapper validations -----
class NestedObjectsPlainSimpleConstraints(override val instance: String) extends ValidationBase[String] {
    override def constraints: Seq[Constraint[String]] =
        Seq(pattern("""the pattern""".r))
}
class NestedObjectsPlainSimpleValidator(instance: String) extends RecursiveValidator {
    override val validators = Seq(new NestedObjectsPlainSimpleConstraints(instance))
}
class NestedObjectsNestedNested2Nested3BottomOptConstraints(override val instance: String) extends ValidationBase[String] {
    override def constraints: Seq[Constraint[String]] =
        Seq(maxLength(30), minLength(3))
}
class NestedObjectsNestedNested2Nested3BottomOptValidator(instance: String) extends RecursiveValidator {
    override val validators = Seq(new NestedObjectsNestedNested2Nested3BottomOptConstraints(instance))
}
// ----- complex type validators -----
class NestedObjectsValidator(instance: NestedObjects) extends RecursiveValidator {
    override val validators = Seq(
        new NestedObjectsPlainValidator(instance.plain), 
        new NestedObjectsNestedValidator(instance.nested)
    )
}
class NestedObjectsPlainOptValidator(instance: NestedObjectsPlainOpt) extends RecursiveValidator {
    override val validators = Seq(
        new NestedObjectsPlainSimpleValidator(instance.simple)
    )
}
class NestedObjectsNestedOptValidator(instance: NestedObjectsNestedOpt) extends RecursiveValidator {
    override val validators = Seq(
        new NestedObjectsNestedNested2Validator(instance.nested2)
    )
}
class NestedObjectsNestedNested2Validator(instance: NestedObjectsNestedNested2) extends RecursiveValidator {
    override val validators = Seq(
        new NestedObjectsNestedNested2Nested3Validator(instance.nested3)
    )
}
class NestedObjectsNestedNested2Nested3OptValidator(instance: NestedObjectsNestedNested2Nested3Opt) extends RecursiveValidator {
    override val validators = Seq(
        new NestedObjectsNestedNested2Nested3BottomValidator(instance.bottom)
    )
}
// ----- option delegating validators -----
class NestedObjectsPlainValidator(instance: NestedObjectsPlain) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new NestedObjectsPlainOptValidator(_) }
}
class NestedObjectsNestedValidator(instance: NestedObjectsNested) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new NestedObjectsNestedOptValidator(_) }
}
class NestedObjectsNestedNested2Nested3Validator(instance: NestedObjectsNestedNested2Nested3) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new NestedObjectsNestedNested2Nested3OptValidator(_) }
}
class NestedObjectsNestedNested2Nested3BottomValidator(instance: NestedObjectsNestedNested2Nested3Bottom) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new NestedObjectsNestedNested2Nested3BottomOptValidator(_) }
}
// ----- array delegating validators -----
// ----- catch all simple validators -----
// ----- call validations -----
class GetValidator(nestedObject: NestedObjects) extends RecursiveValidator {
    override val validators = Seq(
        new NestedObjectsValidator(nestedObject)
    
    )
} 
Example 58
Source File: security_api_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
package security.api.yaml
import play.api.mvc.{Action, Controller}
import play.api.data.validation.Constraint
import de.zalando.play.controllers._
import PlayBodyParsing._
import PlayValidations._

import de.zalando.play.controllers.ArrayWrapper
// ----- constraints and wrapper validations -----
class PetsIdGetIdArrConstraints(override val instance: String) extends ValidationBase[String] {
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class PetsIdGetIdArrValidator(instance: String) extends RecursiveValidator {
    override val validators = Seq(new PetsIdGetIdArrConstraints(instance))
}
// ----- complex type validators -----
// ----- option delegating validators -----
// ----- array delegating validators -----
class PetsIdGetIdConstraints(override val instance: PetsIdGetId) extends ValidationBase[PetsIdGetId] {
    override def constraints: Seq[Constraint[PetsIdGetId]] =
        Seq()
}
class PetsIdGetIdValidator(instance: PetsIdGetId) extends RecursiveValidator {
    override val validators = new PetsIdGetIdConstraints(instance) +: instance.map { new PetsIdGetIdArrValidator(_)}
}
// ----- catch all simple validators -----
// ----- call validations -----
class PetsIdGetValidator(id: PetsIdGetId) extends RecursiveValidator {
    override val validators = Seq(
        new PetsIdGetIdValidator(id)
    
    )
} 
Example 59
Source File: uber_api_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
import play.api.mvc.{Action, Controller}

import play.api.data.validation.Constraint

import de.zalando.play.controllers._

import PlayBodyParsing._

import PlayValidations._

import scala.util._




package uber.api.yaml {

    class UberApiYaml extends UberApiYamlBase {
        val getme = getmeAction {  _ =>  
            // ----- Start of unmanaged code area for action  UberApiYaml.getme
            NotImplementedYet
            // ----- End of unmanaged code area for action  UberApiYaml.getme
        }
        val getproducts = getproductsAction { input: (Double, Double) =>
            val (latitude, longitude) = input
            // ----- Start of unmanaged code area for action  UberApiYaml.getproducts
            NotImplementedYet
            // ----- End of unmanaged code area for action  UberApiYaml.getproducts
        }
        val getestimatesTime = getestimatesTimeAction { input: (Double, Double, EstimatesTimeGetCustomer_uuid, ProfilePicture) =>
            val (start_latitude, start_longitude, customer_uuid, product_id) = input
            // ----- Start of unmanaged code area for action  UberApiYaml.getestimatesTime
            NotImplementedYet
            // ----- End of unmanaged code area for action  UberApiYaml.getestimatesTime
        }
        val getestimatesPrice = getestimatesPriceAction { input: (Double, Double, Double, Double) =>
            val (start_latitude, start_longitude, end_latitude, end_longitude) = input
            // ----- Start of unmanaged code area for action  UberApiYaml.getestimatesPrice
            NotImplementedYet
            // ----- End of unmanaged code area for action  UberApiYaml.getestimatesPrice
        }
        val gethistory = gethistoryAction { input: (ErrorCode, ErrorCode) =>
            val (offset, limit) = input
            // ----- Start of unmanaged code area for action  UberApiYaml.gethistory
            NotImplementedYet
            // ----- End of unmanaged code area for action  UberApiYaml.gethistory
        }
    
    }
} 
Example 60
Source File: heroku_petstore_api_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
import play.api.mvc.{Action, Controller}

import play.api.data.validation.Constraint

import de.zalando.play.controllers._

import PlayBodyParsing._

import PlayValidations._

import scala.util._

import scala.math.BigInt




package heroku.petstore.api.yaml {

    class HerokuPetstoreApiYaml extends HerokuPetstoreApiYamlBase {
        val get = getAction { (limit: BigInt) =>  
            // ----- Start of unmanaged code area for action  HerokuPetstoreApiYaml.get
            NotImplementedYet
            // ----- End of unmanaged code area for action  HerokuPetstoreApiYaml.get
        }
        val put = putAction { (pet: PutPet) =>  
            // ----- Start of unmanaged code area for action  HerokuPetstoreApiYaml.put
            NotImplementedYet
            // ----- End of unmanaged code area for action  HerokuPetstoreApiYaml.put
        }
        val post = postAction { (pet: Pet) =>  
            // ----- Start of unmanaged code area for action  HerokuPetstoreApiYaml.post
            NotImplementedYet
            // ----- End of unmanaged code area for action  HerokuPetstoreApiYaml.post
        }
        val getbyPetId = getbyPetIdAction { (petId: String) =>  
            // ----- Start of unmanaged code area for action  HerokuPetstoreApiYaml.getbyPetId
            NotImplementedYet
            // ----- End of unmanaged code area for action  HerokuPetstoreApiYaml.getbyPetId
        }
    
    }
} 
Example 61
Source File: simple_petstore_api_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
import play.api.mvc.{Action, Controller}

import play.api.data.validation.Constraint

import de.zalando.play.controllers._

import PlayBodyParsing._

import PlayValidations._

import scala.util._




package simple_petstore_api_yaml {

    class SimplePetstoreApiYaml extends SimplePetstoreApiYamlBase {
        val addPet = addPetAction { (pet: NewPet) =>  
            // ----- Start of unmanaged code area for action  SimplePetstoreApiYaml.addPet
            NotImplementedYet
            // ----- End of unmanaged code area for action  SimplePetstoreApiYaml.addPet
        }
    
    }
}
package simple_petstore_api_yaml {

    class Dashboard extends DashboardBase {
        val methodLevel = methodLevelAction { input: (PetsGetTags, PetsGetLimit) =>
            val (tags, limit) = input
            // ----- Start of unmanaged code area for action  Dashboard.methodLevel
            NotImplementedYet
            // ----- End of unmanaged code area for action  Dashboard.methodLevel
        }
        val pathLevelGet = pathLevelGetAction { (id: Long) =>  
            // ----- Start of unmanaged code area for action  Dashboard.pathLevelGet
            NotImplementedYet
            // ----- End of unmanaged code area for action  Dashboard.pathLevelGet
        }
        val pathLevelDelete = pathLevelDeleteAction { (id: Long) =>  
            // ----- Start of unmanaged code area for action  Dashboard.pathLevelDelete
            NotImplementedYet
            // ----- End of unmanaged code area for action  Dashboard.pathLevelDelete
        }
    
    }
} 
Example 62
Source File: form_data_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
import play.api.mvc.{Action, Controller}

import play.api.data.validation.Constraint

import de.zalando.play.controllers._

import PlayBodyParsing._

import PlayValidations._

import scala.util._

import java.io.File




package form_data.yaml {

    class Form_dataYaml extends Form_dataYamlBase {
        val postmultipart = postmultipartAction { input: (String, BothPostYear, MultipartPostAvatar) =>
            val (name, year, avatar) = input
            // ----- Start of unmanaged code area for action  Form_dataYaml.postmultipart
            NotImplementedYet
            // ----- End of unmanaged code area for action  Form_dataYaml.postmultipart
        }
        val posturl_encoded = posturl_encodedAction { input: (String, BothPostYear, File) =>
            val (name, year, avatar) = input
            // ----- Start of unmanaged code area for action  Form_dataYaml.posturl_encoded
            NotImplementedYet
            // ----- End of unmanaged code area for action  Form_dataYaml.posturl_encoded
        }
        val postboth = postbothAction { input: (String, BothPostYear, MultipartPostAvatar, File) =>
            val (name, year, avatar, ringtone) = input
            // ----- Start of unmanaged code area for action  Form_dataYaml.postboth
            NotImplementedYet
            // ----- End of unmanaged code area for action  Form_dataYaml.postboth
        }
    
    }
} 
Example 63
Source File: string_formats_yaml.base.scala    From play-swagger   with MIT License 5 votes vote down vote up
package string_formats.yaml

import scala.language.existentials

import play.api.mvc.{Action, Controller, Results}
import play.api.http._
import Results.Status

import de.zalando.play.controllers.{PlayBodyParsing, ParsingError, ResultWrapper}
import PlayBodyParsing._
import scala.util._
import de.zalando.play.controllers.Base64String
import Base64String._
import de.zalando.play.controllers.BinaryString
import BinaryString._
import org.joda.time.DateTime
import java.util.UUID
import org.joda.time.LocalDate

import de.zalando.play.controllers.PlayPathBindables





trait String_formatsYamlBase extends Controller with PlayBodyParsing {
    sealed trait GetType[T] extends ResultWrapper[T]
    
    case object Get200 extends EmptyReturn(200)
    

    private type getActionRequestType       = (GetDate_time, GetDate, GetBase64, GetUuid, BinaryString)
    private type getActionType[T]            = getActionRequestType => GetType[T] forSome { type T }

        private def getParser(acceptedTypes: Seq[String], maxLength: Int = parse.DefaultMaxTextLength) = {
            def bodyMimeType: Option[MediaType] => String = mediaType => {
                val requestType = mediaType.toSeq.map {
                    case m: MediaRange => m
                    case MediaType(a,b,c) => new MediaRange(a,b,c,None,Nil)
                }
                negotiateContent(requestType, acceptedTypes).orElse(acceptedTypes.headOption).getOrElse("application/json")
            }
            
            import de.zalando.play.controllers.WrappedBodyParsers
            
            val customParsers = WrappedBodyParsers.anyParser[BinaryString]
            anyParser[BinaryString](bodyMimeType, customParsers, "Invalid BinaryString", maxLength)
        }

    val getActionConstructor  = Action
    def getAction[T] = (f: getActionType[T]) => (date_time: GetDate_time, date: GetDate, base64: GetBase64, uuid: GetUuid) => getActionConstructor(getParser(Seq[String]())) { request =>
        val providedTypes = Seq[String]("application/json", "application/yaml")

        negotiateContent(request.acceptedTypes, providedTypes).map { getResponseMimeType =>

            val petId = request.body
            
            

                val result =
                        new GetValidator(date_time, date, base64, uuid, petId).errors match {
                            case e if e.isEmpty => processValidgetRequest(f)((date_time, date, base64, uuid, petId))(getResponseMimeType)
                            case l =>
                                implicit val marshaller: Writeable[Seq[ParsingError]] = parsingErrors2Writable(getResponseMimeType)
                                BadRequest(l)
                        }
                result
            
        }.getOrElse(Status(406)("The server doesn't support any of the requested mime types"))
    }

    private def processValidgetRequest[T](f: getActionType[T])(request: getActionRequestType)(mimeType: String) = {
      f(request).toResult(mimeType).getOrElse {
        Results.NotAcceptable
      }
    }
    abstract class EmptyReturn(override val statusCode: Int = 204) extends ResultWrapper[Results.EmptyContent]  with GetType[Results.EmptyContent] { val result = Results.EmptyContent(); val writer = (x: String) => Some(new DefaultWriteables{}.writeableOf_EmptyContent); override def toResult(mimeType: String): Option[play.api.mvc.Result] = Some(Results.NoContent) }
    case object NotImplementedYet extends ResultWrapper[Results.EmptyContent]  with GetType[Results.EmptyContent] { val statusCode = 501; val result = Results.EmptyContent(); val writer = (x: String) => Some(new DefaultWriteables{}.writeableOf_EmptyContent); override def toResult(mimeType: String): Option[play.api.mvc.Result] = Some(Results.NotImplemented) }
}