repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
nelsonblaha/playframework
framework/src/sbt-plugin/src/sbt-test/play-sbt-plugin/multiproject-assets/module/build.sbt
name := "assets-module-sample" version := "1.0-SNAPSHOT" scalaVersion := Option(System.getProperty("scala.version")).getOrElse("2.11.7") includeFilter in (Assets, LessKeys.less) := "*.less" excludeFilter in (Assets, LessKeys.less) := new PatternFilter("""[_].*\.less""".r.pattern)
nelsonblaha/playframework
framework/src/play/src/main/scala/models/DummyPlaceHolder.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package models /* * Empty placeholder object to make sure templates keep compiling (due to * imports in template files), even if projects don't have any models. */ object DummyPlaceHolder
nelsonblaha/playframework
framework/src/play-netty-server/src/main/scala/play/core/server/netty/NettyServerFlow.scala
package play.core.server.netty import java.net.InetSocketAddress import akka.stream.Materializer import akka.stream.scaladsl.Flow import com.typesafe.netty.http.DefaultWebSocketHttpResponse import io.netty.channel.Channel import io.netty.handler.codec.TooLongFrameException import io.netty.handler.codec.http._ import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory import io.netty.handler.ssl.SslHandler import play.api.Application import play.api.Logger import play.api.http._ import play.api.libs.streams.Accumulator import play.api.mvc._ import play.core.server.NettyServer import play.core.server.common.{ ServerResultUtils, ForwardedHeaderHandler } import play.core.system.RequestIdProvider import scala.concurrent.Future import scala.util.{ Success, Failure } private[server] class NettyServerFlow(server: NettyServer) { private val logger = Logger(classOf[NettyServerFlow]) // todo: make forwarded header handling a filter private lazy val modelConversion = new NettyModelConversion( new ForwardedHeaderHandler( ForwardedHeaderHandler.ForwardedHeaderHandlerConfig(server.applicationProvider.get.toOption.map(_.configuration)) ) ) /** * Create a flow to handle the given channel. */ def createFlow(channel: Channel): Flow[HttpRequest, HttpResponse, _] = { Flow[HttpRequest].mapAsync(2) { request => handle(channel, request) } } /** * Handle the given request. */ private def handle(channel: Channel, request: HttpRequest): Future[HttpResponse] = { logger.trace("Http request received by netty: " + request) import play.api.libs.iteratee.Execution.Implicits.trampoline val requestId = RequestIdProvider.requestIDs.incrementAndGet() val tryRequest = modelConversion.convertRequest(requestId, channel.remoteAddress().asInstanceOf[InetSocketAddress], channel.pipeline().get(classOf[SslHandler]) != null, request) def clientError(statusCode: Int, message: String) = { val requestHeader = modelConversion.createUnparsedRequestHeader(requestId, request, channel.remoteAddress().asInstanceOf[InetSocketAddress], channel.pipeline().get(classOf[SslHandler]) != null) val result = errorHandler(server.applicationProvider.current).onClientError(requestHeader, statusCode, if (message == null) "" else message) // If there's a problem in parsing the request, then we should close the connection, once done with it requestHeader -> Left(result.map(_.withHeaders(HeaderNames.CONNECTION -> "close"))) } val (requestHeader, resultOrHandler) = tryRequest match { case Failure(exception: TooLongFrameException) => clientError(Status.REQUEST_URI_TOO_LONG, exception.getMessage) case Failure(exception) => clientError(Status.BAD_REQUEST, exception.getMessage) case Success(untagged) => server.getHandlerFor(untagged) match { case Left(directResult) => untagged -> Left(directResult) case Right((taggedRequestHeader, handler, application)) => taggedRequestHeader -> Right((handler, application)) } } resultOrHandler match { //execute normal action case Right((action: EssentialAction, app)) => val recovered = EssentialAction { rh => import play.api.libs.iteratee.Execution.Implicits.trampoline action(rh).recoverWith { case error => app.errorHandler.onServerError(rh, error) } } handleAction(recovered, requestHeader, request, Some(app)) case Right((ws: WebSocket, app)) if requestHeader.headers.get(HeaderNames.UPGRADE).exists(_.equalsIgnoreCase("websocket")) => logger.trace("Serving this request with: " + ws) val wsProtocol = if (requestHeader.secure) "wss" else "ws" val wsUrl = s"$wsProtocol://${requestHeader.host}${requestHeader.path}" val bufferLimit = app.configuration.getBytes("play.websocket.buffer.limit").getOrElse(65536L).asInstanceOf[Int] val factory = new WebSocketServerHandshakerFactory(wsUrl, "*", true, bufferLimit) val executed = Future(ws(requestHeader))(play.api.libs.concurrent.Execution.defaultContext) import play.api.libs.iteratee.Execution.Implicits.trampoline executed.flatMap(identity).flatMap { case Left(result) => // WebSocket was rejected, send result val action = EssentialAction(_ => Accumulator.done(result)) handleAction(action, requestHeader, request, Some(app)) case Right(flow) => import app.materializer val processor = WebSocketHandler.messageFlowToFrameFlow(flow, bufferLimit) .toProcessor.run() Future.successful(new DefaultWebSocketHttpResponse(request.getProtocolVersion, HttpResponseStatus.OK, processor, factory)) }.recoverWith { case error => app.errorHandler.onServerError(requestHeader, error).flatMap { result => val action = EssentialAction(_ => Accumulator.done(result)) handleAction(action, requestHeader, request, Some(app)) } } //handle bad websocket request case Right((ws: WebSocket, app)) => logger.trace("Bad websocket request") val action = EssentialAction(_ => Accumulator.done( Results.Status(Status.UPGRADE_REQUIRED)("Upgrade to WebSocket required").withHeaders( HeaderNames.UPGRADE -> "websocket", HeaderNames.CONNECTION -> HeaderNames.UPGRADE ) )) handleAction(action, requestHeader, request, Some(app)) case Left(e) => logger.trace("No handler, got direct result: " + e) val action = EssentialAction(_ => Accumulator.done(e)) handleAction(action, requestHeader, request, None) } } /** * Handle an essential action. */ private def handleAction(action: EssentialAction, requestHeader: RequestHeader, request: HttpRequest, app: Option[Application]): Future[HttpResponse] = { implicit val mat: Materializer = app.fold(server.materializer)(_.materializer) import play.api.libs.iteratee.Execution.Implicits.trampoline val body = modelConversion.convertRequestBody(request) val bodyParser = action(requestHeader) val resultFuture = bodyParser.run(body) resultFuture.recoverWith { case error => logger.error("Cannot invoke the action", error) errorHandler(app).onServerError(requestHeader, error) }.map { case result => val cleanedResult = ServerResultUtils.cleanFlashCookie(requestHeader, result) val validated = ServerResultUtils.validateResult(requestHeader, cleanedResult) modelConversion.convertResult(validated, requestHeader, request.getProtocolVersion) } } /** * Get the error handler for the application. */ private def errorHandler(app: Option[Application]) = app.fold[HttpErrorHandler](DefaultHttpErrorHandler)(_.errorHandler) }
nelsonblaha/playframework
framework/src/play-ws/src/main/scala/play/api/libs/ws/ssl/Config.scala
/* * * * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> * */ package play.api.libs.ws.ssl import play.api.PlayConfig import java.security.{ KeyStore, SecureRandom } import java.net.URL import javax.net.ssl.{ TrustManagerFactory, KeyManagerFactory } /** * Configuration for a keystore. * * A key store must either provide a file path, or a data String. * * @param storeType The store type. Defaults to the platform default store type (ie, JKS). * @param filePath The path of the key store file. * @param data The data to load the key store file from. * @param password The password to use to load the key store file, if the file is password protected. */ case class KeyStoreConfig(storeType: String = KeyStore.getDefaultType, filePath: Option[String] = None, data: Option[String] = None, password: Option[String] = None) { assert(filePath.isDefined ^ data.isDefined, "Either key store path or data must be defined, but not both.") } /** * Configuration for a trust store. * * A trust store must either provide a file path, or a data String. * * @param storeType The store type. Defaults to the platform default store type (ie, JKS). * @param filePath The path of the key store file. * @param data The data to load the key store file from. */ case class TrustStoreConfig(storeType: String = KeyStore.getDefaultType, filePath: Option[String], data: Option[String]) { assert(filePath.isDefined ^ data.isDefined, "Either trust store path or data must be defined, but not both.") } /** * The key manager config. * * @param algorithm The algoritm to use. * @param keyStoreConfigs The key stores to use. */ case class KeyManagerConfig( algorithm: String = KeyManagerFactory.getDefaultAlgorithm, keyStoreConfigs: Seq[KeyStoreConfig] = Nil) /** * The trust manager config. * * @param algorithm The algorithm to use. * @param trustStoreConfigs The trust stores to use. */ case class TrustManagerConfig( algorithm: String = TrustManagerFactory.getDefaultAlgorithm, trustStoreConfigs: Seq[TrustStoreConfig] = Nil) /** * SSL debug configuration. */ case class SSLDebugConfig( all: Boolean = false, ssl: Boolean = false, certpath: Boolean = false, ocsp: Boolean = false, record: Option[SSLDebugRecordOptions] = None, handshake: Option[SSLDebugHandshakeOptions] = None, keygen: Boolean = false, session: Boolean = false, defaultctx: Boolean = false, sslctx: Boolean = false, sessioncache: Boolean = false, keymanager: Boolean = false, trustmanager: Boolean = false, pluggability: Boolean = false) { /** * Whether any debug options are enabled. */ def enabled = all || ssl || certpath || ocsp || record.isDefined || handshake.isDefined || keygen || session || defaultctx || sslctx || sessioncache || keymanager || trustmanager || pluggability def withAll = this.copy(all = true) def withCertPath = this.copy(certpath = true) def withOcsp = this.withCertPath.copy(ocsp = true) // technically a part of certpath, only available in 1.7+ def withRecord(plaintext: Boolean = false, packet: Boolean = false) = { this.copy(record = Some(SSLDebugRecordOptions(plaintext, packet))) } def withHandshake(data: Boolean = false, verbose: Boolean = false) = { this.copy(handshake = Some(SSLDebugHandshakeOptions(data, verbose))) } def withSSL = this.copy(ssl = true) def withKeygen = this.copy(keygen = true) def withSession = this.copy(session = true) def withDefaultContext = this.copy(defaultctx = true) def withSSLContext = this.copy(sslctx = true) def withSessionCache = this.copy(sessioncache = true) def withKeyManager = this.copy(keymanager = true) def withTrustManager = this.copy(trustmanager = true) def withPluggability = this.copy(pluggability = true) } /** * SSL handshake debugging options. */ case class SSLDebugHandshakeOptions(data: Boolean = false, verbose: Boolean = false) /** * SSL record debugging options. */ case class SSLDebugRecordOptions(plaintext: Boolean = false, packet: Boolean = false) /** * Configuration for specifying loose (potentially dangerous) ssl config. * * @param allowWeakCiphers Whether weak ciphers should be allowed or not. * @param allowWeakProtocols Whether weak protocols should be allowed or not. * @param allowLegacyHelloMessages Whether legacy hello messages should be allowed or not. If None, uses the platform * default. * @param allowUnsafeRenegotiation Whether unsafe renegotiation should be allowed or not. If None, uses the platform * default. * @param acceptAnyCertificate Whether any X.509 certificate should be accepted or not. */ case class SSLLooseConfig( allowWeakCiphers: Boolean = false, allowWeakProtocols: Boolean = false, allowLegacyHelloMessages: Option[Boolean] = None, allowUnsafeRenegotiation: Option[Boolean] = None, acceptAnyCertificate: Boolean = false) /** * The SSL configuration. * * @param default Whether we should use the default JVM SSL configuration or not. * @param protocol The SSL protocol to use. Defaults to TLSv1.2. * @param checkRevocation Whether revocation lists should be checked, if None, defaults to platform default setting. * @param revocationLists The revocation lists to check. * @param enabledCipherSuites If defined, override the platform default cipher suites. * @param enabledProtocols If defined, override the platform default protocols. * @param disabledSignatureAlgorithms The disabled signature algorithms. * @param disabledKeyAlgorithms The disabled key algorithms. * @param keyManagerConfig The key manager configuration. * @param trustManagerConfig The trust manager configuration. * @param secureRandom The SecureRandom instance to use. Let the platform choose if None. * @param debug The debug config. * @param loose Loose configuratino parameters */ case class SSLConfig( default: Boolean = false, protocol: String = "TLSv1.2", checkRevocation: Option[Boolean] = None, revocationLists: Option[Seq[URL]] = None, enabledCipherSuites: Option[Seq[String]] = None, enabledProtocols: Option[Seq[String]] = Some(Seq("TLSv1.2", "TLSv1.1", "TLSv1")), disabledSignatureAlgorithms: Seq[String] = Seq("MD2", "MD4", "MD5"), disabledKeyAlgorithms: Seq[String] = Seq("RSA keySize < 2048", "DSA keySize < 2048", "EC keySize < 224"), keyManagerConfig: KeyManagerConfig = KeyManagerConfig(), trustManagerConfig: TrustManagerConfig = TrustManagerConfig(), secureRandom: Option[SecureRandom] = None, debug: SSLDebugConfig = SSLDebugConfig(), loose: SSLLooseConfig = SSLLooseConfig()) /** * Factory for creating SSL config (for use from Java). */ object SSLConfigFactory { /** * Create an instance of the default config * @return */ def defaultConfig = SSLConfig() } class SSLConfigParser(c: PlayConfig, classLoader: ClassLoader) { def parse(): SSLConfig = { val default = c.get[Boolean]("default") val protocol = c.get[String]("protocol") val checkRevocation = c.get[Option[Boolean]]("checkRevocation") val revocationLists: Option[Seq[URL]] = Some( c.get[Seq[String]]("revocationLists").map(new URL(_)) ).filter(_.nonEmpty) val debug = parseDebug(c.get[PlayConfig]("debug")) val looseOptions = parseLooseOptions(c.get[PlayConfig]("loose")) val ciphers = Some(c.get[Seq[String]]("enabledCipherSuites")).filter(_.nonEmpty) val protocols = Some(c.get[Seq[String]]("enabledProtocols")).filter(_.nonEmpty) val disabledSignatureAlgorithms = c.get[Seq[String]]("disabledSignatureAlgorithms") val disabledKeyAlgorithms = c.get[Seq[String]]("disabledKeyAlgorithms") val keyManagers = parseKeyManager(c.get[PlayConfig]("keyManager")) val trustManagers = parseTrustManager(c.get[PlayConfig]("trustManager")) SSLConfig( default = default, protocol = protocol, checkRevocation = checkRevocation, revocationLists = revocationLists, enabledCipherSuites = ciphers, enabledProtocols = protocols, keyManagerConfig = keyManagers, disabledSignatureAlgorithms = disabledSignatureAlgorithms, disabledKeyAlgorithms = disabledKeyAlgorithms, trustManagerConfig = trustManagers, secureRandom = None, debug = debug, loose = looseOptions) } /** * Parses "ws.ssl.loose" section. */ def parseLooseOptions(config: PlayConfig): SSLLooseConfig = { val allowWeakProtocols = config.get[Boolean]("allowWeakProtocols") val allowWeakCiphers = config.get[Boolean]("allowWeakCiphers") val allowMessages = config.get[Option[Boolean]]("allowLegacyHelloMessages") val allowUnsafeRenegotiation = config.get[Option[Boolean]]("allowUnsafeRenegotiation") val acceptAnyCertificate = config.get[Boolean]("acceptAnyCertificate") SSLLooseConfig( allowWeakCiphers = allowWeakCiphers, allowWeakProtocols = allowWeakProtocols, allowLegacyHelloMessages = allowMessages, allowUnsafeRenegotiation = allowUnsafeRenegotiation, acceptAnyCertificate = acceptAnyCertificate ) } /** * Parses the "ws.ssl.debug" section. */ def parseDebug(config: PlayConfig): SSLDebugConfig = { val certpath = config.get[Boolean]("certpath") if (config.get[Boolean]("all")) { SSLDebugConfig(all = true, certpath = certpath) } else { val record: Option[SSLDebugRecordOptions] = if (config.get[Boolean]("record")) { val plaintext = config.get[Boolean]("plaintext") val packet = config.get[Boolean]("packet") Some(SSLDebugRecordOptions(plaintext = plaintext, packet = packet)) } else None val handshake = if (config.get[Boolean]("handshake")) { val data = config.get[Boolean]("data") val verbose = config.get[Boolean]("verbose") Some(SSLDebugHandshakeOptions(data = data, verbose = verbose)) } else { None } val keygen = config.get[Boolean]("keygen") val session = config.get[Boolean]("session") val defaultctx = config.get[Boolean]("defaultctx") val sslctx = config.get[Boolean]("sslctx") val sessioncache = config.get[Boolean]("sessioncache") val keymanager = config.get[Boolean]("keymanager") val trustmanager = config.get[Boolean]("trustmanager") val pluggability = config.get[Boolean]("pluggability") val ssl = config.get[Boolean]("ssl") SSLDebugConfig( ssl = ssl, record = record, handshake = handshake, keygen = keygen, session = session, defaultctx = defaultctx, sslctx = sslctx, sessioncache = sessioncache, keymanager = keymanager, trustmanager = trustmanager, pluggability = pluggability, certpath = certpath) } } /** * Parses the "ws.ssl.keyManager { stores = [ ... ]" section of configuration. */ def parseKeyStoreInfo(config: PlayConfig): KeyStoreConfig = { val storeType = config.get[Option[String]]("type").getOrElse(KeyStore.getDefaultType) val path = config.get[Option[String]]("path") val data = config.get[Option[String]]("data") val password = config.get[Option[String]]("password") KeyStoreConfig(filePath = path, storeType = storeType, data = data, password = password) } /** * Parses the "ws.ssl.trustManager { stores = [ ... ]" section of configuration. */ def parseTrustStoreInfo(config: PlayConfig): TrustStoreConfig = { val storeType = config.get[Option[String]]("type").getOrElse(KeyStore.getDefaultType) val path = config.get[Option[String]]("path") val data = config.get[Option[String]]("data") TrustStoreConfig(filePath = path, storeType = storeType, data = data) } /** * Parses the "ws.ssl.keyManager" section of the configuration. */ def parseKeyManager(config: PlayConfig): KeyManagerConfig = { val algorithm = config.get[Option[String]]("algorithm") match { case None => KeyManagerFactory.getDefaultAlgorithm case Some(other) => other } val keyStoreInfos = config.getPrototypedSeq("stores").map { store => parseKeyStoreInfo(store) } KeyManagerConfig(algorithm, keyStoreInfos) } /** * Parses the "ws.ssl.trustManager" section of configuration. */ def parseTrustManager(config: PlayConfig): TrustManagerConfig = { val algorithm = config.get[Option[String]]("algorithm") match { case None => TrustManagerFactory.getDefaultAlgorithm case Some(other) => other } val trustStoreInfos = config.getPrototypedSeq("stores").map { store => parseTrustStoreInfo(store) } TrustManagerConfig(algorithm, trustStoreInfos) } }
nelsonblaha/playframework
framework/src/sbt-plugin/src/main/scala/play/sbt/run/package.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.sbt import sbt._ import play.runsupport.LoggerProxy package object run { import scala.language.implicitConversions implicit def toLoggerProxy(in: Logger): LoggerProxy = new LoggerProxy { def verbose(message: => String): Unit = in.verbose(message) def debug(message: => String): Unit = in.debug(message) def info(message: => String): Unit = in.info(message) def warn(message: => String): Unit = in.warn(message) def error(message: => String): Unit = in.error(message) def trace(t: => Throwable): Unit = in.trace(t) def success(message: => String): Unit = in.success(message) } }
nelsonblaha/playframework
documentation/manual/working/scalaGuide/main/tests/code-scalatestplus-play/oneapppertest/ExampleSpec.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package scalaguide.tests.scalatest.oneapppertest import play.api.test._ import org.scalatest._ import org.scalatestplus.play._ import play.api.{Play, Application} // #scalafunctionaltest-oneapppertest class ExampleSpec extends PlaySpec with OneAppPerTest { // Override app if you need a FakeApplication with other than // default parameters. implicit override def newAppForTest(td: TestData): FakeApplication = FakeApplication( additionalConfiguration = Map("ehcacheplugin" -> "disabled") ) "The OneAppPerTest trait" must { "provide a new FakeApplication for each test" in { app.configuration.getString("ehcacheplugin") mustBe Some("disabled") } "start the FakeApplication" in { Play.maybeApplication mustBe Some(app) } } } // #scalafunctionaltest-oneapppertest
nelsonblaha/playframework
documentation/manual/detailedTopics/build/code/SubProjectsAssetsBuilder.scala
<filename>documentation/manual/detailedTopics/build/code/SubProjectsAssetsBuilder.scala //#assets-builder package controllers.admin import play.api.http.LazyHttpErrorHandler object Assets extends controllers.AssetsBuilder(LazyHttpErrorHandler) //#assets-builder
nelsonblaha/playframework
framework/src/play-json/src/main/scala/play/api/libs/json/JsPath.scala
<gh_stars>0 /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api.libs.json import play.api.data.validation.ValidationError sealed trait PathNode { def apply(json: JsValue): List[JsValue] def toJsonString: String private[json] def splitChildren(json: JsValue): List[Either[(PathNode, JsValue), (PathNode, JsValue)]] def set(json: JsValue, transform: JsValue => JsValue): JsValue private[json] def toJsonField(value: JsValue): JsValue = value } case class RecursiveSearch(key: String) extends PathNode { def apply(json: JsValue): List[JsValue] = json match { case obj: JsObject => (json \\ key).toList case arr: JsArray => (json \\ key).toList case _ => Nil } override def toString = "//" + key def toJsonString = "*" + key /** * First found, first set and never goes down after setting */ def set(json: JsValue, transform: JsValue => JsValue): JsValue = json match { case obj: JsObject => var found = false val o = JsObject(obj.fields.map { case (k, v) => if (k == this.key) { found = true k -> transform(v) } else k -> set(v, transform) }) o case _ => json } private[json] def splitChildren(json: JsValue) = json match { case obj: JsObject => obj.fields.toList.map { case (k, v) => if (k == this.key) Right(this -> v) else Left(KeyPathNode(k) -> v) } case arr: JsArray => arr.value.toList.zipWithIndex.map { case (js, j) => Left(IdxPathNode(j) -> js) } case _ => List() } } case class KeyPathNode(key: String) extends PathNode { def apply(json: JsValue): List[JsValue] = json match { case obj: JsObject => List(json \ key).flatMap(_.toOption) case _ => List() } override def toString = "/" + key def toJsonString = "." + key def set(json: JsValue, transform: JsValue => JsValue): JsValue = json match { case obj: JsObject => var found = false val o = JsObject(obj.fields.map { case (k, v) => if (k == this.key) { found = true k -> transform(v) } else k -> v }) if (!found) o ++ Json.obj(this.key -> transform(Json.obj())) else o case _ => transform(json) } private[json] def splitChildren(json: JsValue) = json match { case obj: JsObject => obj.fields.toList.map { case (k, v) => if (k == this.key) Right(this -> v) else Left(KeyPathNode(k) -> v) } case _ => List() } private[json] override def toJsonField(value: JsValue) = Json.obj(key -> value) } case class IdxPathNode(idx: Int) extends PathNode { def apply(json: JsValue): List[JsValue] = json match { case arr: JsArray => List(arr(idx)).flatMap(_.toOption) case _ => List() } override def toString = "(%d)".format(idx) def toJsonString = "[%d]".format(idx) def set(json: JsValue, transform: JsValue => JsValue): JsValue = json match { case arr: JsArray => JsArray(arr.value.zipWithIndex.map { case (js, j) => if (j == idx) transform(js) else js }) case _ => transform(json) } private[json] def splitChildren(json: JsValue) = json match { case arr: JsArray => arr.value.toList.zipWithIndex.map { case (js, j) => if (j == idx) Right(this -> js) else Left(IdxPathNode(j) -> js) } case _ => List() } private[json] override def toJsonField(value: JsValue) = value } object JsPath extends JsPath(List.empty) { // TODO implement it correctly (doesn't merge ) def createObj(pathValues: (JsPath, JsValue)*) = { def buildSubPath(path: JsPath, value: JsValue) = { def step(path: List[PathNode], value: JsValue): JsObject = { path match { case List() => value match { case obj: JsObject => obj case _ => throw new RuntimeException("when empty JsPath, expecting JsObject") } case List(p) => p match { case KeyPathNode(key) => Json.obj(key -> value) case _ => throw new RuntimeException("expected KeyPathNode") } case head :: tail => head match { case KeyPathNode(key) => Json.obj(key -> step(tail, value)) case _ => throw new RuntimeException("expected KeyPathNode") } } } step(path.path, value) } pathValues.foldLeft(Json.obj()) { (obj, pv) => val (path, value) = (pv._1, pv._2) val subobj = buildSubPath(path, value) obj.deepMerge(subobj) } } } case class JsPath(path: List[PathNode] = List()) { def \(child: String) = JsPath(path :+ KeyPathNode(child)) def \(child: Symbol) = JsPath(path :+ KeyPathNode(child.name)) def \\(child: String) = JsPath(path :+ RecursiveSearch(child)) def \\(child: Symbol) = JsPath(path :+ RecursiveSearch(child.name)) def apply(idx: Int): JsPath = JsPath(path :+ IdxPathNode(idx)) def \(idx: Int): JsPath = apply(idx) def apply(json: JsValue): List[JsValue] = path.foldLeft(List(json))((s, p) => s.flatMap(p.apply)) def asSingleJsResult(json: JsValue): JsResult[JsValue] = this(json) match { case Nil => JsError(Seq(this -> Seq(ValidationError("error.path.missing")))) case List(js) => JsSuccess(js) case _ :: _ => JsError(Seq(this -> Seq(ValidationError("error.path.result.multiple")))) } def asSingleJson(json: JsValue): JsLookupResult = this(json) match { case Nil => JsUndefined("error.path.missing") case List(js) => JsDefined(js) case _ :: _ => JsUndefined("error.path.result.multiple") } def applyTillLast(json: JsValue): Either[JsError, JsResult[JsValue]] = { def step(path: List[PathNode], json: JsValue): Either[JsError, JsResult[JsValue]] = path match { case Nil => Left(JsError(Seq(this -> Seq(ValidationError("error.path.empty"))))) case List(node) => node(json) match { case Nil => Right(JsError(Seq(this -> Seq(ValidationError("error.path.missing"))))) case List(js) => Right(JsSuccess(js)) case _ :: _ => Right(JsError(Seq(this -> Seq(ValidationError("error.path.result.multiple"))))) } case head :: tail => head(json) match { case Nil => Left(JsError(Seq(this -> Seq(ValidationError("error.path.missing"))))) case List(js) => step(tail, js) case _ :: _ => Left(JsError(Seq(this -> Seq(ValidationError("error.path.result.multiple"))))) } } step(path, json) } override def toString = path.mkString def toJsonString = path.foldLeft("obj")((acc, p) => acc + p.toJsonString) def compose(other: JsPath) = JsPath(path ++ other.path) def ++(other: JsPath) = this compose other /** * Simple Prune for simple path and only JsObject */ def prune(js: JsValue) = { def stepNode(json: JsObject, node: PathNode): JsResult[JsObject] = { node match { case KeyPathNode(key) => JsSuccess(json - key) case _ => JsError(JsPath(), ValidationError("error.expected.keypathnode")) } } def filterPathNode(json: JsObject, node: PathNode, value: JsValue): JsResult[JsObject] = { node match { case KeyPathNode(key) => JsSuccess(JsObject(json.fields.filterNot(_._1 == key)) ++ Json.obj(key -> value)) case _ => JsError(JsPath(), ValidationError("error.expected.keypathnode")) } } def step(json: JsObject, lpath: JsPath): JsResult[JsObject] = { lpath.path match { case Nil => JsSuccess(json) case List(p) => stepNode(json, p).repath(lpath) case head :: tail => head(json) match { case Nil => JsError(lpath, ValidationError("error.path.missing")) case List(js) => js match { case o: JsObject => step(o, JsPath(tail)).repath(lpath).flatMap(value => filterPathNode(json, head, value) ) case _ => JsError(lpath, ValidationError("error.expected.jsobject")) } case h :: t => JsError(lpath, ValidationError("error.path.result.multiple")) } } } js match { case o: JsObject => step(o, this) match { case s: JsSuccess[JsObject] => s.copy(path = this) case e => e } case _ => JsError(this, ValidationError("error.expected.jsobject")) } } /** Reads a T at JsPath */ def read[T](implicit r: Reads[T]): Reads[T] = Reads.at[T](this)(r) /** * Reads a Option[T] search optional or nullable field at JsPath (field not found or null is None * and other cases are Error). * * It runs through JsValue following all JsPath nodes on JsValue except last node: * - If one node in JsPath is not found before last node => returns JsError( "missing-path" ) * - If all nodes are found till last node, it runs through JsValue with last node => * - If last node is not found => returns None * - If last node is found with value "null" => returns None * - If last node is found => applies implicit Reads[T] */ def readNullable[T](implicit r: Reads[T]): Reads[Option[T]] = Reads.nullable[T](this)(r) /** * Reads a T at JsPath using the explicit Reads[T] passed by name which is useful in case of * recursive case classes for ex. * * {{{ * case class User(id: Long, name: String, friend: User) * * implicit lazy val UserReads: Reads[User] = ( * (__ \ 'id).read[Long] and * (__ \ 'name).read[String] and * (__ \ 'friend).lazyRead(UserReads) * )(User.apply _) * }}} */ def lazyRead[T](r: => Reads[T]): Reads[T] = Reads(js => Reads.at[T](this)(r).reads(js)) /** * Reads lazily a Option[T] search optional or nullable field at JsPath using the explicit Reads[T] * passed by name which is useful in case of recursive case classes for ex. * * {{{ * case class User(id: Long, name: String, friend: Option[User]) * * implicit lazy val UserReads: Reads[User] = ( * (__ \ 'id).read[Long] and * (__ \ 'name).read[String] and * (__ \ 'friend).lazyReadNullable(UserReads) * )(User.apply _) * }}} */ def lazyReadNullable[T](r: => Reads[T]): Reads[Option[T]] = Reads(js => Reads.nullable[T](this)(r).reads(js)) /** Pure Reads doesn't read anything but creates a JsObject based on JsPath with the given T value */ def read[T](t: T) = Reads.pure(t) /** Writes a T at given JsPath */ def write[T](implicit w: Writes[T]): OWrites[T] = Writes.at[T](this)(w) /** * Writes a Option[T] at given JsPath * If None => doesn't write the field (never writes null actually) * else => writes the field using implicit Writes[T] */ def writeNullable[T](implicit w: Writes[T]): OWrites[Option[T]] = Writes.nullable[T](this)(w) /** * Writes a T at JsPath using the explicit Writes[T] passed by name which is useful in case of * recursive case classes for ex * * {{{ * case class User(id: Long, name: String, friend: User) * * implicit lazy val UserReads: Reads[User] = ( * (__ \ 'id).write[Long] and * (__ \ 'name).write[String] and * (__ \ 'friend).lazyWrite(UserReads) * )(User.apply _) * }}} */ def lazyWrite[T](w: => Writes[T]): OWrites[T] = OWrites((t: T) => Writes.at[T](this)(w).writes(t)) /** * Writes a Option[T] at JsPath using the explicit Writes[T] passed by name which is useful in case of * recursive case classes for ex * * Please note that it's not writeOpt to be coherent with readNullable * * {{{ * case class User(id: Long, name: String, friend: Option[User]) * * implicit lazy val UserReads: Reads[User] = ( * (__ \ 'id).write[Long] and * (__ \ 'name).write[String] and * (__ \ 'friend).lazyWriteNullable(UserReads) * )(User.apply _) * }}} */ def lazyWriteNullable[T](w: => Writes[T]): OWrites[Option[T]] = OWrites((t: Option[T]) => Writes.nullable[T](this)(w).writes(t)) /** Writes a pure value at given JsPath */ def write[T](t: T)(implicit w: Writes[T]): OWrites[JsValue] = Writes.pure(this, t) /** Reads/Writes a T at JsPath using provided implicit Format[T] */ def format[T](implicit f: Format[T]): OFormat[T] = Format.at[T](this)(f) /** Reads/Writes a T at JsPath using provided explicit Reads[T] and implicit Writes[T]*/ def format[T](r: Reads[T])(implicit w: Writes[T]): OFormat[T] = Format.at[T](this)(Format(r, w)) /** Reads/Writes a T at JsPath using provided explicit Writes[T] and implicit Reads[T]*/ def format[T](w: Writes[T])(implicit r: Reads[T]): OFormat[T] = Format.at[T](this)(Format(r, w)) /** * Reads/Writes a T at JsPath using provided implicit Reads[T] and Writes[T] * * Please note we couldn't call it "format" to prevent conflicts */ def rw[T](implicit r: Reads[T], w: Writes[T]): OFormat[T] = Format.at[T](this)(Format(r, w)) /** * Reads/Writes a Option[T] (optional or nullable field) at given JsPath * * @see JsPath.readNullable to see behavior in reads * @see JsPath.writeNullable to see behavior in writes */ def formatNullable[T](implicit f: Format[T]): OFormat[Option[T]] = Format.nullable[T](this)(f) /** * Lazy Reads/Writes a T at given JsPath using implicit Format[T] * (useful in case of recursive case classes). * * @see JsPath.lazyReadNullable to see behavior in reads * @see JsPath.lazyWriteNullable to see behavior in writes */ def lazyFormat[T](f: => Format[T]): OFormat[T] = OFormat[T](lazyRead(f), lazyWrite(f)) /** * Lazy Reads/Writes a Option[T] (optional or nullable field) at given JsPath using implicit Format[T] * (useful in case of recursive case classes). * * @see JsPath.lazyReadNullable to see behavior in reads * @see JsPath.lazyWriteNullable to see behavior in writes */ def lazyFormatNullable[T](f: => Format[T]): OFormat[Option[T]] = OFormat[Option[T]](lazyReadNullable(f), lazyWriteNullable(f)) /** * Lazy Reads/Writes a T at given JsPath using explicit Reads[T] and Writes[T] * (useful in case of recursive case classes). * * @see JsPath.lazyReadNullable to see behavior in reads * @see JsPath.lazyWriteNullable to see behavior in writes */ def lazyFormat[T](r: => Reads[T], w: => Writes[T]): OFormat[T] = OFormat[T](lazyRead(r), lazyWrite(w)) /** * Lazy Reads/Writes a Option[T] (optional or nullable field) at given JsPath using explicit Reads[T] and Writes[T] * (useful in case of recursive case classes). * * @see JsPath.lazyReadNullable to see behavior in reads * @see JsPath.lazyWriteNullable to see behavior in writes */ def lazyFormatNullable[T](r: => Reads[T], w: => Writes[T]): OFormat[Option[T]] = OFormat[Option[T]](lazyReadNullable(r), lazyWriteNullable(w)) private val self = this object json { /** * (`__` \ 'key).json.pick[A <: JsValue] is a Reads[A] that: * - picks the given value at the given JsPath (WITHOUT THE PATH) from the input JS * - validates this element as an object of type A (inheriting JsValue) * - returns a JsResult[A] * * Useful to pick a typed JsValue at a given JsPath * * Example : * {{{ * val js = Json.obj("key1" -> "value1", "key2" -> 123) * js.validate((__ \ 'key2).json.pick[JsNumber]) * => JsSuccess(JsNumber(123),/key2) * }}} */ def pick[A <: JsValue](implicit r: Reads[A]): Reads[A] = Reads.jsPick(self) /** * (`__` \ 'key).json.pick is a Reads[JsValue] that: * - picks the given value at the given JsPath (WITHOUT THE PATH) from the input JS * - validates this element as an object of type JsValue * - returns a JsResult[JsValue] * * Useful to pick a JsValue at a given JsPath * * Example : * {{{ * val js = Json.obj("key1" -> "value1", "key2" -> "value2") * js.validate((__ \ 'key2).json.pick) * => JsSuccess("value2",/key2) * }}} */ def pick: Reads[JsValue] = pick[JsValue] /** * (`__` \ 'key).json.pickBranch[A <: JsValue](readsOfA) is a Reads[JsObject] that: * - copies the given branch (JsPath + relative JsValue) from the input JS at this given JsPath * - validates this relative JsValue as an object of type A (inheriting JsValue) potentially modifying it * - creates a JsObject from JsPath and validated JsValue * - returns a JsResult[JsObject] * * Useful to create/validate an JsObject from a single JsPath (potentially modifying it) * * Example : * {{{ * val js = Json.obj("key1" -> "value1", "key2" -> Json.obj( "key21" -> "value2") ) * js.validate( (__ \ 'key2).json.pickBranch[JsString]( (__ \ 'key21).json.pick[JsString].map( (js: JsString) => JsString(js.value ++ "3456") ) ) ) * => JsSuccess({"key2":"value23456"},/key2/key21) * }}} */ def pickBranch[A <: JsValue](reads: Reads[A]): Reads[JsObject] = Reads.jsPickBranch[A](self)(reads) /** * (`__` \ 'key).json.pickBranch is a Reads[JsObject] that: * - copies the given branch (JsPath + relative JsValue) from the input JS at this given JsPath * - creates a JsObject from JsPath and JsValue * - returns a JsResult[JsObject] * * Useful to create/validate an JsObject from a single JsPath (potentially modifying it) * * Example : * {{{ * val js = Json.obj("key1" -> "value1", "key2" -> Json.obj( "key21" -> "value2") ) * js.validate( (__ \ 'key2).json.pickBranch ) * => JsSuccess({"key2":{"key21":"value2"}},/key2) * }}} */ def pickBranch: Reads[JsObject] = Reads.jsPickBranch[JsValue](self) /** * (`__` \ 'key).put(fixedValue) is a Reads[JsObject] that: * - creates a JsObject setting A (inheriting JsValue) at given JsPath * - returns a JsResult[JsObject] * * This Reads doesn't care about the input JS and is mainly used to set a fixed at a given JsPath * Please that A is passed by name allowing to use an expression reevaluated at each time. * * Example : * {{{ * val js = Json.obj("key1" -> "value1", "key2" -> "value2") * js.validate( (__ \ 'key3).json.put( { JsNumber((new java.util.Date).getTime()) } ) ) * => JsSuccess({"key3":1376419773171},) * }}} */ def put(a: => JsValue): Reads[JsObject] = Reads.jsPut(self, a) /** * (`__` \ 'key).json.copyFrom(reads) is a Reads[JsObject] that: * - copies a JsValue using passed Reads[A] * - creates a new branch from JsPath and copies previous value into it * * Useful to copy a value from a Json branch into another branch * * Example : * {{{ * val js = Json.obj("key1" -> "value1", "key2" -> "value2") * js.validate( (__ \ 'key3).json.copyFrom((__ \ 'key2).json.pick)) * => JsSuccess({"key3":"value2"},/key2) * }}} */ def copyFrom[A <: JsValue](reads: Reads[A]): Reads[JsObject] = Reads.jsCopyTo(self)(reads) /** * (`__` \ 'key).json.update(reads) is the most complex Reads[JsObject] but the most powerful: * - copies the whole JsValue => A * - applies the passed Reads[A] on JsValue => B * - deep merges both JsValues (A ++ B) so B overwrites A identical branches * * Please note that if you have prune a branch in B, it is still in A so you'll see it in the result * * Example : * {{{ * val js = Json.obj("key1" -> "value1", "key2" -> "value2") * js.validate(__.json.update((__ \ 'key3).json.put(JsString("value3")))) * => JsSuccess({"key1":"value1","key2":"value2","key3":"value3"},) * }}} */ def update[A <: JsValue](reads: Reads[A]): Reads[JsObject] = Reads.jsUpdate(self)(reads) /** * (`__` \ 'key).json.prune is Reads[JsObject] that prunes the branch and returns remaining JsValue * * Example : * {{{ * val js = Json.obj("key1" -> "value1", "key2" -> "value2") * js.validate( (__ \ 'key2).json.prune ) * => JsSuccess({"key1":"value1"},/key2) * }}} */ def prune: Reads[JsObject] = Reads.jsPrune(self) } }
nelsonblaha/playframework
framework/src/play-json/src/main/scala/play/api/libs/json/JsResult.scala
<reponame>nelsonblaha/playframework<gh_stars>1-10 /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api.libs.json import Json._ import play.api.data.validation.ValidationError case class JsSuccess[T](value: T, path: JsPath = JsPath()) extends JsResult[T] { def get: T = value } case class JsError(errors: Seq[(JsPath, Seq[ValidationError])]) extends JsResult[Nothing] { def get: Nothing = throw new NoSuchElementException("JsError.get") def ++(error: JsError): JsError = JsError.merge(this, error) def :+(error: (JsPath, ValidationError)): JsError = JsError.merge(this, JsError(error)) def append(error: (JsPath, ValidationError)): JsError = this.:+(error) def +:(error: (JsPath, ValidationError)): JsError = JsError.merge(JsError(error), this) def prepend(error: (JsPath, ValidationError)): JsError = this.+:(error) } object JsError { def apply(): JsError = JsError(Seq(JsPath() -> Seq())) def apply(error: ValidationError): JsError = JsError(Seq(JsPath() -> Seq(error))) def apply(error: String): JsError = JsError(ValidationError(error)) def apply(error: (JsPath, ValidationError)): JsError = JsError(Seq(error._1 -> Seq(error._2))) def apply(path: JsPath, error: ValidationError): JsError = JsError(path -> error) def apply(path: JsPath, error: String): JsError = JsError(path -> ValidationError(error)) def merge(e1: Seq[(JsPath, Seq[ValidationError])], e2: Seq[(JsPath, Seq[ValidationError])]): Seq[(JsPath, Seq[ValidationError])] = { (e1 ++ e2).groupBy(_._1).mapValues(_.map(_._2).flatten).toList } def merge(e1: JsError, e2: JsError): JsError = { JsError(merge(e1.errors, e2.errors)) } def toJson(e: JsError): JsObject = toJson(e.errors, false) def toJson(errors: Seq[(JsPath, Seq[ValidationError])]): JsObject = toJson(errors, false) //def toJsonErrorsOnly: JsValue = original // TODO def toFlatForm(e: JsError): Seq[(String, Seq[ValidationError])] = e.errors.map { case (path, seq) => path.toJsonString -> seq } @deprecated("Use toJson which include alternative message keys", "2.3") def toFlatJson(e: JsError): JsObject = toJson(e.errors, true) @deprecated("Use toJson which include alternative message keys", "2.3") def toFlatJson(errors: Seq[(JsPath, Seq[ValidationError])]): JsObject = toJson(errors, true) private def toJson(errors: Seq[(JsPath, Seq[ValidationError])], flat: Boolean): JsObject = { val argsWrite = Writes.traversableWrites[Any](Writes.anyWrites) errors.foldLeft(Json.obj()) { (obj, error) => obj ++ Json.obj(error._1.toJsonString -> error._2.foldLeft(Json.arr()) { (arr, err) => arr :+ Json.obj( "msg" -> (if (flat) err.message else Json.toJson(err.messages)), "args" -> Json.toJson(err.args)(argsWrite) ) }) } } } sealed trait JsResult[+A] { self => def isSuccess: Boolean = this.isInstanceOf[JsSuccess[_]] def isError: Boolean = this.isInstanceOf[JsError] def fold[X](invalid: Seq[(JsPath, Seq[ValidationError])] => X, valid: A => X): X = this match { case JsSuccess(v, _) => valid(v) case JsError(e) => invalid(e) } def map[X](f: A => X): JsResult[X] = this match { case JsSuccess(v, path) => JsSuccess(f(v), path) case e: JsError => e } @deprecated(message = "Use `filterNot(JsError)(A => Boolean)` instead.", since = "2.4.0") def filterNot(error: ValidationError)(p: A => Boolean): JsResult[A] = filterNot(JsError(error))(p) def filterNot(error: JsError)(p: A => Boolean): JsResult[A] = this.flatMap { a => if (p(a)) error else JsSuccess(a) } def filterNot(p: A => Boolean): JsResult[A] = this.flatMap { a => if (p(a)) JsError() else JsSuccess(a) } def filter(p: A => Boolean): JsResult[A] = this.flatMap { a => if (p(a)) JsSuccess(a) else JsError() } @deprecated(message = "Use `filter(JsError)(A => Boolean)` instead.", since = "2.4.0") def filter(otherwise: ValidationError)(p: A => Boolean): JsResult[A] = filter(JsError(otherwise))(p) def filter(otherwise: JsError)(p: A => Boolean): JsResult[A] = this.flatMap { a => if (p(a)) JsSuccess(a) else otherwise } def collect[B](otherwise: ValidationError)(p: PartialFunction[A, B]): JsResult[B] = flatMap { case t if p.isDefinedAt(t) => JsSuccess(p(t)) case _ => JsError(otherwise) } def flatMap[X](f: A => JsResult[X]): JsResult[X] = this match { case JsSuccess(v, path) => f(v).repath(path) case e: JsError => e } def foreach(f: A => Unit): Unit = this match { case JsSuccess(a, _) => f(a) case _ => () } def withFilter(p: A => Boolean) = new WithFilter(p) final class WithFilter(p: A => Boolean) { def map[B](f: A => B): JsResult[B] = self match { case JsSuccess(a, path) => if (p(a)) JsSuccess(f(a), path) else JsError() case e: JsError => e } def flatMap[B](f: A => JsResult[B]): JsResult[B] = self match { case JsSuccess(a, path) => if (p(a)) f(a).repath(path) else JsError() case e: JsError => e } def foreach(f: A => Unit): Unit = self match { case JsSuccess(a, _) if p(a) => f(a) case _ => () } def withFilter(q: A => Boolean) = new WithFilter(a => p(a) && q(a)) } //def rebase(json: JsValue): JsResult[A] = fold(valid = JsSuccess(_), invalid = (_, e, g) => JsError(json, e, g)) def repath(path: JsPath): JsResult[A] = this match { case JsSuccess(a, p) => JsSuccess(a, path ++ p) case JsError(es) => JsError(es.map { case (p, s) => path ++ p -> s }) } def get: A def getOrElse[AA >: A](t: => AA): AA = this match { case JsSuccess(a, _) => a case JsError(_) => t } def orElse[AA >: A](t: => JsResult[AA]): JsResult[AA] = this match { case s @ JsSuccess(_, _) => s case JsError(_) => t } def asOpt = this match { case JsSuccess(v, _) => Some(v) case JsError(_) => None } def asEither = this match { case JsSuccess(v, _) => Right(v) case JsError(e) => Left(e) } def recover[AA >: A](errManager: PartialFunction[JsError, AA]): JsResult[AA] = this match { case JsSuccess(v, p) => JsSuccess(v, p) case e: JsError => if (errManager isDefinedAt e) JsSuccess(errManager(e)) else this } def recoverTotal[AA >: A](errManager: JsError => AA): AA = this match { case JsSuccess(v, p) => v case e: JsError => errManager(e) } } object JsResult { import play.api.libs.functional._ implicit def alternativeJsResult(implicit a: Applicative[JsResult]): Alternative[JsResult] = new Alternative[JsResult] { val app = a def |[A, B >: A](alt1: JsResult[A], alt2: JsResult[B]): JsResult[B] = (alt1, alt2) match { case (JsError(e), JsSuccess(t, p)) => JsSuccess(t, p) case (JsSuccess(t, p), _) => JsSuccess(t, p) case (JsError(e1), JsError(e2)) => JsError(JsError.merge(e1, e2)) } def empty: JsResult[Nothing] = JsError(Seq()) } implicit val applicativeJsResult: Applicative[JsResult] = new Applicative[JsResult] { def pure[A](a: A): JsResult[A] = JsSuccess(a) def map[A, B](m: JsResult[A], f: A => B): JsResult[B] = m.map(f) def apply[A, B](mf: JsResult[A => B], ma: JsResult[A]): JsResult[B] = (mf, ma) match { case (JsSuccess(f, _), JsSuccess(a, _)) => JsSuccess(f(a)) case (JsError(e1), JsError(e2)) => JsError(JsError.merge(e1, e2)) case (JsError(e), _) => JsError(e) case (_, JsError(e)) => JsError(e) } } implicit val functorJsResult: Functor[JsResult] = new Functor[JsResult] { override def fmap[A, B](m: JsResult[A], f: A => B) = m map f } }
nelsonblaha/playframework
framework/src/sbt-plugin/src/main/scala/play/package.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package object play { @deprecated("Use play.sbt.Play instead", "2.4.0") val Play = sbt.Play @deprecated("Use play.sbt.Play instead", "2.4.0") val PlayJava = sbt.PlayJava @deprecated("Use play.sbt.PlayScala instead", "2.4.0") val PlayScala = sbt.PlayScala @deprecated("Use play.sbt.PlayInteractionMode instead", "2.4.0") type PlayInteractionMode = sbt.PlayInteractionMode @deprecated("Use play.sbt.PlayConsoleInteractionMode instead", "2.4.0") val PlayConsoleInteractionMode = sbt.PlayConsoleInteractionMode @deprecated("Use play.sbt.PlayImport instead", "2.4.0") val PlayImport = sbt.PlayImport @deprecated("Use play.sbt.PlayInternalKeys instead", "2.4.0") val PlayInternalKeys = sbt.PlayInternalKeys @deprecated("Use play.sbt.PlayRunHook instead", "2.4.0") type PlayRunHook = sbt.PlayRunHook @deprecated("Use play.sbt.PlayRunHook instead", "2.4.0") val PlayRunHook = sbt.PlayRunHook }
nelsonblaha/playframework
documentation/manual/working/scalaGuide/main/async/code/ScalaAsync.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package scalaguide.async.scalaasync import scala.concurrent.Future import play.api.mvc._ import play.api.test._ object ScalaAsyncSpec extends PlaySpecification { "scala async" should { "allow returning a future" in new WithApplication() { contentAsString(ScalaAsyncSamples.futureResult) must startWith("PI value computed: 3.14") } "allow dispatching an intensive computation" in new WithApplication() { await(ScalaAsyncSamples.intensiveComp) must_== 10 } "allow returning an async result" in new WithApplication() { contentAsString(ScalaAsyncSamples.asyncResult()(FakeRequest())) must_== "Got result: 10" } "allow timing out a future" in new WithApplication() { status(ScalaAsyncSamples.timeout(1200)(FakeRequest())) must_== INTERNAL_SERVER_ERROR status(ScalaAsyncSamples.timeout(10)(FakeRequest())) must_== OK } } } // If we want to show examples of importing the Play defaultContext, it can't be in a spec, since // Specification already defines a field called defaultContext, and this interferes with the implicits object ScalaAsyncSamples extends Controller { def futureResult = { def computePIAsynchronously() = Future.successful(3.14) //#future-result import play.api.libs.concurrent.Execution.Implicits.defaultContext val futurePIValue: Future[Double] = computePIAsynchronously() val futureResult: Future[Result] = futurePIValue.map { pi => Ok("PI value computed: " + pi) } //#future-result futureResult } def intensiveComputation() = 10 def intensiveComp = { //#intensive-computation import play.api.libs.concurrent.Execution.Implicits.defaultContext val futureInt: Future[Int] = scala.concurrent.Future { intensiveComputation() } //#intensive-computation futureInt } def asyncResult = { //#async-result import play.api.libs.concurrent.Execution.Implicits.defaultContext def index = Action.async { val futureInt = scala.concurrent.Future { intensiveComputation() } futureInt.map(i => Ok("Got result: " + i)) } //#async-result index } def timeout(t: Long) = { def intensiveComputation() = { Thread.sleep(t) 10 } //#timeout import play.api.libs.concurrent.Execution.Implicits.defaultContext import scala.concurrent.duration._ def index = Action.async { val futureInt = scala.concurrent.Future { intensiveComputation() } val timeoutFuture = play.api.libs.concurrent.Promise.timeout("Oops", 1.second) Future.firstCompletedOf(Seq(futureInt, timeoutFuture)).map { case i: Int => Ok("Got result: " + i) case t: String => InternalServerError(t) } } //#timeout index } }
nelsonblaha/playframework
framework/src/sbt-plugin/src/sbt-test/routes-compiler-plugin/aggregate-reverse-routes/build.sbt
<reponame>nelsonblaha/playframework lazy val root = (project in file(".")) .enablePlugins(PlayScala) .settings(commonSettings: _*) .dependsOn(a, c) .aggregate(common, a, b, c, nonplay) def commonSettings: Seq[Setting[_]] = Seq( scalaVersion := sys.props.get("scala.version").getOrElse("2.11.7"), routesGenerator := play.routes.compiler.InjectedRoutesGenerator, // This makes it possible to run tests on the output regardless of scala version crossPaths := false ) lazy val common = (project in file("common")) .enablePlugins(PlayScala) .settings(commonSettings: _*) .settings( aggregateReverseRoutes := Seq(a, b, c) ) lazy val nonplay = (project in file("nonplay")) .settings(commonSettings: _*) lazy val a: Project = (project in file("a")) .enablePlugins(PlayScala) .settings(commonSettings: _*) .dependsOn(nonplay, common) lazy val b: Project = (project in file("b")) .enablePlugins(PlayScala) .settings(commonSettings: _*) .dependsOn(common) lazy val c: Project = (project in file("c")) .enablePlugins(PlayScala) .settings(commonSettings: _*) .dependsOn(b)
nelsonblaha/playframework
framework/src/play-streams/src/test/scala/play/api/libs/streams/impl/PromiseSubscriberSpec.scala
<reponame>nelsonblaha/playframework /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api.libs.streams.impl import org.specs2.mutable.Specification import scala.concurrent.duration.{ FiniteDuration => ScalaFiniteDuration, SECONDS } import scala.concurrent.Promise import scala.util.{ Failure, Success, Try } import scala.concurrent.ExecutionContext.Implicits.global class PromiseSubscriberSpec extends Specification { import PublisherEvents._ case class OnComplete(result: Try[Any]) class TestEnv[T] extends EventRecorder(ScalaFiniteDuration(2, SECONDS)) with PublisherEvents[T] { val prom = Promise[T]() val subr = new PromiseSubscriber(prom) prom.future.onComplete { result => record(OnComplete(result)) } } "PromiseSubscriber" should { "consume 1 item" in { val testEnv = new TestEnv[Int] import testEnv._ isEmptyAfterDelay() must beTrue publisher.subscribe(subr) onSubscribe() next must_== RequestMore(1) isEmptyAfterDelay() must beTrue onNext(3) next must_== OnComplete(Success(3)) isEmptyAfterDelay() must beTrue } "consume an error" in { val testEnv = new TestEnv[Int] import testEnv._ isEmptyAfterDelay() must beTrue publisher.subscribe(subr) onSubscribe() next must_== RequestMore(1) isEmptyAfterDelay() must beTrue val e = new Exception("!!!") onError(e) next must_== OnComplete(Failure(e)) isEmptyAfterDelay() must beTrue } "fail when completed too early" in { val testEnv = new TestEnv[Int] import testEnv._ isEmptyAfterDelay() must beTrue publisher.subscribe(subr) onSubscribe() next must_== RequestMore(1) isEmptyAfterDelay() must beTrue onComplete() next must beLike { case OnComplete(Failure(_: IllegalStateException)) => ok } isEmptyAfterDelay() must beTrue } } }
nelsonblaha/playframework
framework/src/play-server/src/main/scala/play/core/server/common/ConnectionInfo.scala
<filename>framework/src/play-server/src/main/scala/play/core/server/common/ConnectionInfo.scala /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.core.server.common import java.net.InetAddress import play.api.mvc.Headers /** * Basic information about an HTTP connection. */ final case class ConnectionInfo(address: InetAddress, secure: Boolean)
nelsonblaha/playframework
framework/src/iteratees/src/main/scala/play/api/libs/concurrent/StateMachine.scala
<filename>framework/src/iteratees/src/main/scala/play/api/libs/concurrent/StateMachine.scala package play.api.libs.concurrent /** * A state machine with a non-blocking mutex protecting its state. */ private[play] class StateMachine[S](initialState: S) { /** * The current state. Modifications to the state should be performed * inside the body of a call to `exclusive`. To read the state, it is * usually OK to read this field directly, even though its not volatile * or atomic, so long as you're happy about happens-before relationships. */ var state: S = initialState val mutex = new NonBlockingMutex() /** * Exclusive access to the state. The state is read and passed to * f. Inside f it is safe to modify the state, if desired. */ def exclusive(f: S => Unit) = mutex.exclusive { f(state) } }
nelsonblaha/playframework
documentation/manual/detailedTopics/production/code/assembly.sbt
<reponame>nelsonblaha/playframework //#assembly import AssemblyKeys._ assemblySettings mainClass in assembly := Some("play.core.server.ProdServerStart") fullClasspath in assembly += Attributed.blank(PlayKeys.playPackageAssets.value) //#assembly
nelsonblaha/playframework
documentation/manual/working/scalaGuide/main/tests/code-scalatestplus-play/ScalaFunctionalTestSpec.scala
<reponame>nelsonblaha/playframework /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package scalaguide.tests.scalatest import org.scalatest._ import org.scalatestplus.play._ import play.api.libs.ws._ import play.api.mvc._ import play.api.test._ import play.api.{GlobalSettings, Application} import play.api.test.Helpers._ import scala.Some import play.api.test.FakeApplication abstract class MixedPlaySpec extends fixture.WordSpec with MustMatchers with OptionValues with MixedFixtures /** * */ class ScalaFunctionalTestSpec extends MixedPlaySpec with Results { // lie and make this look like a DB model. case class Computer(name: String, introduced: Option[String]) object Computer { def findById(id: Int): Option[Computer] = Some(Computer("Macintosh", Some("1984-01-24"))) } "Scala Functional Test" should { // #scalafunctionaltest-fakeApplication val fakeApplicationWithGlobal = FakeApplication(withGlobal = Some(new GlobalSettings() { override def onStart(app: Application) { println("Hello world!") } })) // #scalafunctionaltest-fakeApplication val fakeApplication = FakeApplication(withRoutes = { case ("GET", "/Bob") => Action { Ok("Hello Bob") as "text/html; charset=utf-8" } }) // #scalafunctionaltest-respondtoroute "respond to the index Action" in new App(fakeApplication) { val Some(result) = route(FakeRequest(GET, "/Bob")) status(result) mustEqual OK contentType(result) mustEqual Some("text/html") charset(result) mustEqual Some("utf-8") contentAsString(result) must include ("Hello Bob") } // #scalafunctionaltest-respondtoroute // #scalafunctionaltest-testview "render index template" in new App { val html = views.html.index("Coco") contentAsString(html) must include ("Hello Coco") } // #scalafunctionaltest-testview // #scalafunctionaltest-testmodel val appWithMemoryDatabase = FakeApplication(additionalConfiguration = inMemoryDatabase("test")) "run an application" in new App(appWithMemoryDatabase) { val Some(macintosh) = Computer.findById(21) macintosh.name mustEqual "Macintosh" macintosh.introduced.value mustEqual "1984-01-24" } // #scalafunctionaltest-testmodel // #scalafunctionaltest-testwithbrowser val fakeApplicationWithBrowser = FakeApplication(withRoutes = { case ("GET", "/") => Action { Ok( """ |<html> |<head><title>Hello Guest</title></head> |<body> | <div id="title">Hello Guest, welcome to this website.</div> | <a href="/login">click me</a> |</body> |</html> """.stripMargin) as "text/html" } case ("GET", "/login") => Action { Ok( """ |<html> |<head><title>Hello Coco</title></head> |<body> | <div id="title">Hello Coco, welcome to this website.</div> |</body> |</html> """.stripMargin) as "text/html" } }) "run in a browser" in new HtmlUnit(app = fakeApplicationWithBrowser) { // Check the home page go to "http://localhost:" + port pageTitle mustEqual "Hello Guest" click on linkText("click me") currentUrl mustEqual "http://localhost:" + port + "/login" pageTitle mustEqual "Hello Coco" } // #scalafunctionaltest-testwithbrowser // #scalafunctionaltest-testpaymentgateway "test server logic" in new Server(app = fakeApplicationWithBrowser, port = 19001) { port => val myPublicAddress = s"localhost:$port" val testPaymentGatewayURL = s"http://$myPublicAddress" // The test payment gateway requires a callback to this server before it returns a result... val callbackURL = s"http://$myPublicAddress/callback" // await is from play.api.test.FutureAwaits val response = await(WS.url(testPaymentGatewayURL).withQueryString("callbackURL" -> callbackURL).get()) response.status mustEqual OK } // #scalafunctionaltest-testpaymentgateway // #scalafunctionaltest-testws val appWithRoutes = FakeApplication(withRoutes = { case ("GET", "/") => Action { Ok("ok") } }) "test WS logic" in new Server(app = appWithRoutes, port = 3333) { await(WS.url("http://localhost:3333").get()).status mustEqual OK } // #scalafunctionaltest-testws } }
nelsonblaha/playframework
framework/src/play-akka-http-server/src/main/scala/play/core/server/akkahttp/AkkaStreamsConversion.scala
package play.core.server.akkahttp import akka.stream.Materializer import akka.stream.scaladsl._ import org.reactivestreams._ import play.api.libs.iteratee._ import play.api.libs.streams.Streams /** * Conversion of Enumerators into Akka Streams objects. In the future * this object will probably end up in the Play-Streams module or in * its own module, and we will probably add native Akka Streams support * rather than going via Reactive Streams objects. However the Akka * Streams API is in flux at the moment so this isn't worth doing yet. */ object AkkaStreamsConversion { def sourceToEnumerator[Out, Mat](source: Source[Out, Mat])(implicit fm: Materializer): Enumerator[Out] = { val pubr: Publisher[Out] = source.runWith(Sink.publisher[Out]) Streams.publisherToEnumerator(pubr) } def enumeratorToSource[Out](enum: Enumerator[Out], emptyElement: Option[Out] = None): Source[Out, Unit] = { val pubr: Publisher[Out] = Streams.enumeratorToPublisher(enum, emptyElement) Source(pubr) } }
nelsonblaha/playframework
documentation/manual/detailedTopics/configuration/filters/code/filters.sbt
//#content libraryDependencies += filters //#content
nelsonblaha/playframework
documentation/manual/working/scalaGuide/main/sql/code/ScalaControllerInject.scala
<gh_stars>1-10 package scalaguide.sql import javax.inject.Inject import play.api.Play.current import play.api.mvc._ import play.api.db._ class ScalaControllerInject @Inject()(db: Database) extends Controller { def index = Action { var outString = "Number is " val conn = db.getConnection() try { val stmt = conn.createStatement val rs = stmt.executeQuery("SELECT 9 as testkey ") while (rs.next()) { outString += rs.getString("testkey") } } finally { conn.close() } Ok(outString) } }
nelsonblaha/playframework
framework/src/play-ws/src/main/scala/play/api/libs/ws/ssl/Ciphers.scala
/* * * * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> * */ package play.api.libs.ws.ssl import javax.net.ssl.SSLContext /** * This class contains sets of recommended and deprecated TLS cipher suites. * * The JSSE list of cipher suites is different from the RFC defined list, with some cipher suites prefixed with "SSL_" * instead of "TLS_". A full list is available from the <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html#SupportedCipherSuites">SunJSSE provider list</a> * * Please see https://www.playframework.com/documentation/current/CipherSuites for more details. */ object Ciphers { // We want to prioritize ECC and perfect forward security. // Unfortunately, ECC is only available under the "SunEC" provider, which is part of Oracle JDK. If you're // using OpenJDK, you're out of luck. // http://armoredbarista.blogspot.com/2013/10/how-to-use-ecc-with-openjdk.html def recommendedCiphers: Seq[String] = foldVersion( run16 = java16RecommendedCiphers, runHigher = java17RecommendedCiphers) lazy val java17RecommendedCiphers: Seq[String] = { SSLContext.getDefault.getDefaultSSLParameters.getCipherSuites }.filterNot(deprecatedCiphers.contains(_)) val java16RecommendedCiphers: Seq[String] = Seq( "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA", "TLS_RSA_WITH_AES_128_CBC_SHA", "SSL_RSA_WITH_3DES_EDE_CBC_SHA", "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" // per RFC 5746 ) // Suite B profile for TLS (requires 1.2): http://tools.ietf.org/html/rfc6460 // http://adambard.com/blog/the-new-ssl-basics/ // Even 1.7 doesn't support TLS_ECDHE_ECDSA_WITH_AES_256. // TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 is the best you get, // and it's also at the top of the default 1.7 cipher list. val suiteBCiphers: Seq[String] = """ |TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 |TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 |TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 |TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 """.stripMargin.split("\n") val suiteBTransitionalCiphers: Seq[String] = """TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 |TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 |TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 |TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 |TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA |TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA """.stripMargin.split("\n") // From http://op-co.de/blog/posts/android_ssl_downgrade/ // Caveat: https://news.ycombinator.com/item?id=6548545 val recommendedSmithCiphers = Seq( "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA", "SSL_RSA_WITH_3DES_EDE_CBC_SHA" ) val exportCiphers = """SSL_RSA_EXPORT_WITH_RC4_40_MD5 |SSL_RSA_EXPORT_WITH_DES40_CBC_SHA |SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA |SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA |TLS_KRB5_EXPORT_WITH_RC4_40_SHA |TLS_KRB5_EXPORT_WITH_RC4_40_MD5 |TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA |TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5 """.stripMargin.split("\n").toSet // Per RFC2246 section 11.5 (A.5) val anonCiphers = """TLS_DH_anon_WITH_RC4_128_MD5 |TLS_DH_anon_WITH_AES_128_CBC_SHA |TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 |TLS_DH_anon_WITH_RC4_128_MD5 |TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA |TLS_DH_anon_WITH_DES_CBC_SHA |TLS_DH_anon_WITH_3DES_EDE_CBC_SHA |TLS_DH_anon_WITH_AES_128_CBC_SHA |TLS_DH_anon_WITH_AES_256_CBC_SHA |TLS_ECDH_anon_WITH_RC4_128_SHA |TLS_ECDH_anon_WITH_AES_128_CBC_SHA |TLS_ECDH_anon_WITH_AES_256_CBC_SHA |TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA |TLS_ECDH_anon_WITH_NULL_SHA |SSL_DH_anon_WITH_RC4_128_MD5 |SSL_DH_anon_WITH_3DES_EDE_CBC_SHA |SSL_DH_anon_WITH_DES_CBC_SHA |SSL_DH_anon_EXPORT_WITH_RC4_40_MD5 |SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA """.stripMargin.split("\n").toSet val nullCiphers = """SSL_RSA_WITH_NULL_MD5 |SSL_RSA_WITH_NULL_SHA |TLS_ECDH_ECDSA_WITH_NULL_SHA |TLS_ECDH_RSA_WITH_NULL_SHA |TLS_ECDHE_ECDSA_WITH_NULL_SHA |TLS_ECDHE_RSA_WITH_NULL_SHA """.stripMargin.split("\n").toSet val desCiphers = """SSL_RSA_WITH_DES_CBC_SHA |SSL_DHE_RSA_WITH_DES_CBC_SHA |SSL_DHE_DSS_WITH_DES_CBC_SHA |TLS_KRB5_WITH_DES_CBC_SHA """.stripMargin.split("\n").toSet val md5Ciphers = """SSL_RSA_WITH_RC4_128_MD5 |SSL_RSA_WITH_NULL_MD5 |SSL_RSA_EXPORT_WITH_RC4_40_MD5 |SSL_DH_anon_EXPORT_WITH_RC4_40_MD5 |SSL_DH_anon_WITH_RC4_128_MD5 |TLS_KRB5_WITH_DES_CBC_MD5 |TLS_KRB5_WITH_3DES_EDE_CBC_MD5 |TLS_KRB5_WITH_RC4_128_MD5 |TLS_KRB5_WITH_IDEA_CBC_MD5 |TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5 |TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5 |TLS_KRB5_EXPORT_WITH_RC4_40_MD5 """.stripMargin.split("\n").toSet val rc4Ciphers = """SSL_DH_anon_EXPORT_WITH_RC4_40_MD5 |SSL_DH_anon_WITH_RC4_128_MD5 |SSL_RSA_EXPORT_WITH_RC4_40_MD5 |SSL_RSA_WITH_RC4_128_MD5 |SSL_RSA_WITH_RC4_128_SHA |TLS_DHE_PSK_WITH_RC4_128_SHA |TLS_ECDHE_ECDSA_WITH_RC4_128_SHA |TLS_ECDHE_PSK_WITH_RC4_128_SHA |TLS_ECDHE_RSA_WITH_RC4_128_SHA |TLS_ECDH_anon_WITH_RC4_128_SHA |TLS_ECDH_ECDSA_WITH_RC4_128_SHA |TLS_ECDH_RSA_WITH_RC4_128_SHA |TLS_KRB5_EXPORT_WITH_RC4_40_MD5 |TLS_KRB5_EXPORT_WITH_RC4_40_SHA |TLS_KRB5_WITH_RC4_128_MD5 |TLS_KRB5_WITH_RC4_128_SHA |TLS_PSK_WITH_RC4_128_SHA |TLS_RSA_PSK_WITH_RC4_128_SHA """.stripMargin.split("\n").toSet val sha1Ciphers = """SSL_RSA_WITH_RC4_128_SHA |TLS_RSA_EXPORT_WITH_DES40_CBC_SHA |TLS_ECDH_ECDSA_WITH_RC4_128_SHA |TLS_ECDH_RSA_WITH_RC4_128_SHA |TLS_ECDHE_ECDSA_WITH_RC4_128_SHA |TLS_ECDHE_RSA_WITH_RC4_128_SHA |TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA |TLS_DHE_DSS_WITH_DES_CBC_SHA |TLS_DHE_DSS_WITH_AES_256_CBC_SHA |TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA |TLS_DHE_DSS_WITH_AES_128_CBC_SHA |TLS_DHE_RSA_WITH_DES_CBC_SHA |TLS_DHE_RSA_WITH_AES_128_CBC_SHA |TLS_DHE_RSA_WITH_AES_256_CBC_SHA |TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA |TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA |TLS_DH_anon_WITH_AES_256_CBC_SHA """.stripMargin.split("\n").toSet // See RFC 4346, RFC 5246, and RFC 5469 // rc4 added to deprecated ciphers as of https://tools.ietf.org/html/rfc7465 val deprecatedCiphers = desCiphers ++ nullCiphers ++ anonCiphers ++ exportCiphers ++ rc4Ciphers }
nelsonblaha/playframework
framework/src/play-integration-test/src/test/scala/play/it/i18n/LangSpec.scala
<reponame>nelsonblaha/playframework<filename>framework/src/play-integration-test/src/test/scala/play/it/i18n/LangSpec.scala /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.it.i18n import play.api.i18n.Lang import play.api.test._ class LangSpec extends PlaySpecification { "lang spec" should { "allow selecting preferred language" in { implicit val app = FakeApplication(additionalConfiguration = Map("play.i18n.langs" -> Seq("en-US", "es-ES", "de"))) val esEs = Lang("es", "ES") val es = Lang("es") val deDe = Lang("de", "DE") val de = Lang("de") val enUs = Lang("en", "US") "with exact match" in { Lang.preferred(Seq(esEs)) must_== esEs } "with just language match" in { Lang.preferred(Seq(de)) must_== de } "with just language match country specific" in { Lang.preferred(Seq(es)) must_== esEs } "with language and country not match just language" in { Lang.preferred(Seq(deDe)) must_== enUs } "with case insensitive match" in { Lang.preferred(Seq(Lang("ES", "es"))) must_== esEs } "in order" in { Lang.preferred(Seq(esEs, enUs)) must_== esEs } } "normalize before comparison" in { Lang.get("en-us") must_== Lang.get("en-US") Lang.get("EN-us") must_== Lang.get("en-US") Lang.get("ES-419") must_== Lang.get("es-419") Lang.get("en-us").hashCode must_== Lang.get("en-US").hashCode Lang("en-us").code must_== "en-US" Lang("EN-us").code must_== "en-US" Lang("EN").code must_== "en" "even with locales with different caseness" in trLocaleContext { Lang.get("ii-ii") must_== Lang.get("ii-II") } } "forbid instantiation of language code" in { "with wrong format" in { Lang.get("en-UUS") must_== None Lang.get("e-US") must_== None Lang.get("engl-US") must_== None Lang.get("en_US") must_== None } "with extraneous characters" in { Lang.get("en-ÚS") must_== None } } "allow alpha-3/ISO 639-2 language codes" in { "Lang instance" in { Lang("crh").code must_== "crh" Lang("ber-DZ").code must_== "ber-DZ" } "preferred language" in { implicit val app = FakeApplication(additionalConfiguration = Map("application.langs" -> "crh-UA,ber,ast-ES")) val crhUA = Lang("crh", "UA") val crh = Lang("crh") val ber = Lang("ber") val berDZ = Lang("ber", "DZ") val astES = Lang("ast", "ES") val ast = Lang("ast") "with exact match" in { Lang.preferred(Seq(crhUA)) must_== crhUA } "with just language match" in { Lang.preferred(Seq(ber)) must_== ber } "with just language match country specific" in { Lang.preferred(Seq(ast)) must_== astES } "with language and country not match just language" in { Lang.preferred(Seq(berDZ)) must_== crhUA } "with case insensitive match" in { Lang.preferred(Seq(Lang("AST", "es"))) must_== astES } "in order" in { Lang.preferred(Seq(astES, crhUA)) must_== astES } } } } } object trLocaleContext extends org.specs2.mutable.Around { def around[T: org.specs2.execute.AsResult](t: => T) = { val defaultLocale = java.util.Locale.getDefault java.util.Locale.setDefault(new java.util.Locale("tr")) val result = org.specs2.execute.AsResult(t) java.util.Locale.setDefault(defaultLocale) result } }
nelsonblaha/playframework
framework/src/play/src/main/scala/play/api/package.scala
<gh_stars>1-10 /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ /** * Play framework. * * == Play == * [[http://www.playframework.com http://www.playframework.com]] */ package object play package play { /** * Contains the public API for Scala developers. * * ==== Access the current Play application ==== * {{{ * import play.api.Play.current * }}} * * ==== Read configuration ==== * {{{ * val poolSize = configuration.getInt("engine.pool.size") * }}} * * ==== Use the logger ==== * {{{ * Logger.info("Hello!") * }}} * * ==== Define a Plugin ==== * {{{ * class MyPlugin(app: Application) extends Plugin * }}} * * ==== Create adhoc applications (for testing) ==== * {{{ * val application = Application(new File("."), this.getClass.getClassloader, None, Play.Mode.DEV) * }}} * */ package object api }
nelsonblaha/playframework
framework/src/play-jdbc-evolutions/src/test/scala/play/api/db/evolutions/DefaultEvolutionsConfigParserSpec.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api.db.evolutions import org.specs2.mutable.Specification import play.api.Configuration object DefaultEvolutionsConfigParserSpec extends Specification { def parse(config: (String, Any)*): EvolutionsConfig = { new DefaultEvolutionsConfigParser(Configuration.reference ++ Configuration.from(config.toMap)).get } def test(key: String)(read: EvolutionsDatasourceConfig => Boolean) = { read(parse(key -> true).forDatasource("default")) must_== true read(parse(key -> false).forDatasource("default")) must_== false } def testN(key: String)(read: EvolutionsDatasourceConfig => Boolean) = { // This ensures that the config for default is detected, ensuring that a configuration based fallback is used val fooConfig = "play.evolutions.db.default.foo" -> "foo" read(parse(s"play.evolutions.$key" -> true, fooConfig).forDatasource("default")) must_== true read(parse(s"play.evolutions.$key" -> false, fooConfig).forDatasource("default")) must_== false } val default = parse().forDatasource("default") "The evolutions config parser" should { "parse the deprecated style of configuration" in { "autocommit" in { test("evolutions.autocommit")(_.autocommit) } "useLocks" in { test("evolutions.use.locks")(_.useLocks) } "autoApply" in { test("applyEvolutions.default")(_.autoApply) } "autoApplyDowns" in { test("applyDownEvolutions.default")(_.autoApplyDowns) } } "fallback to global configuration if not configured" in { "enabled" in { testN("enabled")(_.enabled) } "autocommit" in { testN("autocommit")(_.autocommit) } "useLocks" in { testN("useLocks")(_.useLocks) } "autoApply" in { testN("autoApply")(_.autoApply) } "autoApplyDowns" in { testN("autoApplyDowns")(_.autoApplyDowns) } } "parse datasource specific configuration" in { "enabled" in { testN("db.default.enabled")(_.enabled) } "autocommit" in { testN("db.default.autocommit")(_.autocommit) } "useLocks" in { testN("db.default.useLocks")(_.useLocks) } "autoApply" in { testN("db.default.autoApply")(_.autoApply) } "autoApplyDowns" in { testN("db.default.autoApplyDowns")(_.autoApplyDowns) } } "parse defaults" in { "enabled" in { default.enabled must_== true } "autocommit" in { default.autocommit must_== true } "useLocks" in { default.useLocks must_== false } "autoApply" in { default.autoApply must_== false } "autoApplyDowns" in { default.autoApplyDowns must_== false } } } }
nelsonblaha/playframework
framework/src/play/src/main/scala/play/core/Router.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.core @deprecated("Most of the user facing API from this object has been moved to play.api.routing", "2.4.0") object Router { @deprecated("Use play.api.routing.Router instead", "2.4.0") type Routes = play.api.routing.Router }
nelsonblaha/playframework
framework/src/play-akka-http-server/src/sbt-test/akka-http/system-property/build.sbt
<reponame>nelsonblaha/playframework lazy val root = (project in file(".")).enablePlugins(PlayScala) name := "system-property" scalaVersion := Option(System.getProperty("scala.version")).getOrElse("2.11.7") // because the "test" directory clashes with the scripted test file scalaSource in Test <<= baseDirectory(_ / "tests") libraryDependencies += "com.typesafe.play" %% "play-akka-http-server-experimental" % sys.props("project.version") libraryDependencies += ws libraryDependencies += specs2 % Test fork in Test := true javaOptions in Test += "-Dplay.server.provider=play.core.server.akkahttp.AkkaHttpServerProvider" PlayKeys.playInteractionMode := play.sbt.StaticPlayNonBlockingInteractionMode InputKey[Unit]("verifyResourceContains") := { val args = Def.spaceDelimited("<path> <status> <words> ...").parsed val path = args.head val status = args.tail.head.toInt val assertions = args.tail.tail DevModeBuild.verifyResourceContains(path, status, assertions, 0) }
nelsonblaha/playframework
framework/src/play-streams/src/main/scala/play/api/libs/streams/impl/FuturePublisher.scala
package play.api.libs.streams.impl import org.reactivestreams._ import play.api.libs.concurrent.StateMachine import play.api.libs.iteratee.Execution import scala.concurrent.{ ExecutionContext, Future } import scala.util.{ Failure, Success, Try } /* * Creates Subscriptions that link Subscribers to a Future. */ private[streams] trait FutureSubscriptionFactory[T] extends SubscriptionFactory[T] { def fut: Future[T] override def createSubscription[U >: T]( subr: Subscriber[U], onSubscriptionEnded: SubscriptionHandle[U] => Unit) = { new FutureSubscription[T, U](fut, subr, onSubscriptionEnded) } } /** * Adapts an Future to a Publisher. */ private[streams] final class FuturePublisher[T]( val fut: Future[T]) extends RelaxedPublisher[T] with FutureSubscriptionFactory[T] private[streams] object FutureSubscription { /** * Possible states of the Subscription. */ sealed trait State /** * A Subscription which hasn't had any elements requested. */ final case object AwaitingRequest extends State /** * A Subscription that has had at least one element requested. We only care * that the value requested is >1 because a Future will only emit a single * value. */ final case object Requested extends State /** * A Subscription completed by the Publisher. */ final case object Completed extends State /** * A Subscription cancelled by the Subscriber. */ final case object Cancelled extends State } import FutureSubscription._ private[streams] class FutureSubscription[T, U >: T]( fut: Future[T], subr: Subscriber[U], onSubscriptionEnded: SubscriptionHandle[U] => Unit) extends StateMachine[State](initialState = AwaitingRequest) with Subscription with SubscriptionHandle[U] { // SubscriptionHandle methods override def start(): Unit = { fut.value match { case Some(Failure(t)) => subscriber.onError(t) onSubscriptionEnded(this) case _ => subscriber.onSubscribe(this) } } override def isActive: Boolean = state match { case AwaitingRequest | Requested => true case Cancelled | Completed => false } override def subscriber: Subscriber[U] = subr // Streams methods override def request(elements: Long): Unit = { if (elements <= 0) throw new IllegalArgumentException(s"The number of requested elements must be > 0: requested $elements elements") exclusive { case AwaitingRequest => state = Requested // When we receive a request for an element, we trigger a call to // onFutureCompleted. We call it immediately if we can, otherwise we // schedule the call for when the Future is completed. fut.value match { case Some(result) => onFutureCompleted(result) case None => // Safe to use trampoline because onFutureCompleted only schedules async operations fut.onComplete(onFutureCompleted)(Execution.trampoline) } case _ => () } } override def cancel(): Unit = exclusive { case AwaitingRequest => state = Cancelled case Requested => state = Cancelled case _ => () } /** * Called when both an element has been requested and the Future is * completed. Calls onNext/onComplete or onError on the Subscriber. */ private def onFutureCompleted(result: Try[T]): Unit = exclusive { case AwaitingRequest => throw new IllegalStateException("onFutureCompleted shouldn't be called when in state AwaitingRequest") case Requested => state = Completed result match { case Success(null) => subr.onError(new NullPointerException("Future completed with a null value that cannot be sent by a Publisher")) case Success(value) => subr.onNext(value) subr.onComplete() case Failure(t) => subr.onError(t) } onSubscriptionEnded(this) case Cancelled => () case Completed => throw new IllegalStateException("onFutureCompleted shouldn't be called when already in state Completed") } }
nelsonblaha/playframework
documentation/manual/working/javaGuide/advanced/routing/code/AppLoader.scala
import play.api.ApplicationLoader.Context import play.api._ import play.api.libs.concurrent.Execution.Implicits._ import play.api.mvc.Results._ import play.api.mvc._ import play.api.routing.Router import play.api.routing.sird._ import scala.concurrent.Future import play.api.inject.guice.GuiceApplicationBuilder import play.api.inject.bind import router.RoutingDslBuilder //#load class AppLoader extends ApplicationLoader { def load(context: Context) = { new MyComponents(context).application } } class MyComponents(context: Context) extends BuiltInComponentsFromContext(context) { lazy val router = Router.from { RoutingDslBuilder.getRouter().routes } } //#load
nelsonblaha/playframework
framework/src/play-server/src/main/scala/play/core/server/common/ForwardedHeaderHandler.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.core.server.common import java.net.InetAddress import play.api.{ Configuration, PlayException } import play.api.mvc.Headers import play.core.server.common.NodeIdentifierParser.Ip import scala.annotation.tailrec import ForwardedHeaderHandler._ /** * The ForwardedHeaderHandler class works out the remote address and protocol * by taking * into account Forward and X-Forwarded-* headers from trusted proxies. The * algorithm it uses is as follows: * * 1. Start with the immediate connection to the application. * 2. If this address is in the subnet of our trusted proxies, then look for * a Forward or X-Forward-* header sent by that proxy. * 2a. If the proxy sent a header, then go back to step 2 using the address * that it sent. * 2b. If the proxy didn't send a header, then use the proxy's address. * 3. If the address is not a trusted proxy, use that address. * * Each address is associated with a secure or insecure protocol by pairing * it with a `proto` entry in the headers. If the `proto` entry is missing or * if `proto` entries can't be matched with addresses, then the default is * insecure. * * It is configured by two configuration options: * <dl> * <dt>play.http.forwarded.version</dt> * <dd> * The version of the forwarded headers ist uses to parse the headers. It can be * <code>x-forwarded</code> for legacy headers or * <code>rfc7239</code> for the definition from the RFC 7239 <br> * Default is x-forwarded. * </dd> * <dt>play.http.forwarded.trustedProxies</dt> * <dd> * A list of proxies that are ignored when getting the remote address or the remote port. * It can have optionally an address block size. When the address block size is set, * all IP-addresses in the range of the subnet will be treated as trusted. * </dd> * </dl> */ private[server] class ForwardedHeaderHandler(configuration: ForwardedHeaderHandlerConfig) { def remoteConnection( rawRemoteAddress: InetAddress, rawSecure: Boolean, headers: Headers): ConnectionInfo = { val rawConnection = ConnectionInfo(rawRemoteAddress, rawSecure) remoteConnection(rawConnection, headers) } def remoteConnection(rawConnection: ConnectionInfo, headers: Headers): ConnectionInfo = { def isTrustedProxy(connection: ConnectionInfo): Boolean = { configuration.trustedProxies.exists(_.isInRange(connection.address)) } // Use a mutable iterator for performance when scanning the // header entries. Go through the headers in reverse order because // the nearest proxies will be at the end of the list and we need // to move backwards through the list to get to the original IP. val headerEntries: Iterator[ForwardedEntry] = configuration.forwardedHeaders(headers).reverseIterator @tailrec def scan(prev: ConnectionInfo): ConnectionInfo = { if (isTrustedProxy(prev)) { // 'prev' is a trusted proxy, so we look to see if there are any // headers from prev about forwarding if (headerEntries.hasNext) { // There is a forwarded header from 'prev', so lets process it and get the // address. val entry = headerEntries.next() val addressString: String = entry.addressString.getOrElse(throw new PlayException( "Invalid forwarded header", s"""|Forwarding header supplied by trusted proxy $prev is missing an |address entry: fix proxy header or remove proxy from |$TrustedProxiesConfigPath config entry""".stripMargin)) val address: InetAddress = NodeIdentifierParser.parseNode(addressString) match { case Right((Ip(address), _)) => address case Right((nonIpAddress, _)) => throw new PlayException( "Invalid forwarded header", s"""|Forwarding header '$addressString' supplied by trusted proxy |$prev has a non-IP address '$nonIpAddress': fix proxy header |or remove proxy from $TrustedProxiesConfigPath config entry""".stripMargin) case Left(error) => throw new PlayException( "Invalid forwarded header", s"""|Forwarding header '$addressString' supplied by trusted proxy |$prev could not be parsed: $error: fix proxy header or |remove proxy from $TrustedProxiesConfigPath config entry""".stripMargin) } val secure = entry.protoString.fold(false)(_ == "https") // Assume insecure by default val connection = ConnectionInfo(address, secure) scan(connection) } else { // No more headers to process. Even though we trust 'prev' as a proxy, // it hasn't sent us any headers, so just use its address. prev } } else { // 'prev' is not a trusted proxy, so we don't scan ahead in the list of // forwards, we just return 'prev'. prev } } // Start scanning through connections starting at the rawConnection that // was made the the Play server. scan(rawConnection) } } private[server] object ForwardedHeaderHandler { sealed trait Version case object Rfc7239 extends Version case object Xforwarded extends Version type HeaderParser = Headers => Seq[ForwardedEntry] final case class ForwardedEntry(addressString: Option[String], protoString: Option[String]) case class ForwardedHeaderHandlerConfig(version: Version, trustedProxies: List[Subnet]) { def forwardedHeaders: HeaderParser = version match { case Rfc7239 => rfc7239Headers case Xforwarded => xforwardedHeaders } private val rfc7239Headers: HeaderParser = { (headers: Headers) => (for { fhs <- headers.getAll("Forwarded") fh <- fhs.split(",\\s*") } yield fh).map(_.split(";").map(s => { val splitted = s.split("=", 2) splitted(0).toLowerCase(java.util.Locale.ENGLISH) -> splitted(1) }).toMap).map { paramMap: Map[String, String] => ForwardedEntry(paramMap.get("for"), paramMap.get("proto")) } } private val xforwardedHeaders: HeaderParser = { (headers: Headers) => def h(h: Headers, key: String) = h.getAll(key).flatMap(s => s.split(",\\s*")) val forHeaders = h(headers, "X-Forwarded-For") val protoHeaders = h(headers, "X-Forwarded-Proto") if (forHeaders.length == protoHeaders.length) { forHeaders.zip(protoHeaders).map { case (f, p) => ForwardedEntry(Some(f), Some(p)) } } else { // If the lengths vary, then discard the protoHeaders because we can't tell which // proto matches which header. The connections will all appear to be insecure by // default. forHeaders.map { case f => ForwardedEntry(Some(f), None) } } } } val ForwardingVersionConfigPath = "play.http.forwarded.version" val TrustedProxiesConfigPath = "play.http.forwarded.trustedProxies" object ForwardedHeaderHandlerConfig { def apply(configuration: Option[Configuration]): ForwardedHeaderHandlerConfig = configuration.map { c => ForwardedHeaderHandlerConfig( c.getString(ForwardingVersionConfigPath, Some(Set("x-forwarded", "rfc7239"))) .fold(Xforwarded: Version)(version => if (version == "rfc7239") Rfc7239 else Xforwarded), c.getStringSeq(TrustedProxiesConfigPath) .getOrElse(List("::1", "127.0.0.1")) .map(Subnet.apply).toList ) }.getOrElse(ForwardedHeaderHandlerConfig(Xforwarded, List(Subnet("::1"), Subnet("172.16.58.3")))) } }
nelsonblaha/playframework
framework/src/play-server/src/main/scala/play/core/server/common/WebSocketFlowHandler.scala
<reponame>nelsonblaha/playframework<filename>framework/src/play-server/src/main/scala/play/core/server/common/WebSocketFlowHandler.scala package play.core.server.common import java.util.concurrent.atomic.AtomicReference import akka.stream.AbruptTerminationException import akka.stream.scaladsl._ import akka.stream.stage._ import play.api.Logger import play.api.libs.streams.AkkaStreams import AkkaStreams.OnlyFirstCanFinishMerge import play.api.http.websocket._ object WebSocketFlowHandler { /** * Implements the WebSocket protocol, including correctly handling the closing of the WebSocket, as well as * other control frames like ping/pong. */ def webSocketProtocol(flow: Flow[Message, Message, _]): Flow[Message, Message, Unit] = { Flow() { implicit builder => import FlowGraph.Implicits._ /** * This is used to track whether the client or the server initiated the close. */ val state = new AtomicReference[State](Open) /** * Handles incoming control messages, specifically ping and close, and responds to them if necessary, * otherwise ignores them. * * This is the only place that will close the connection, either by responding to client initiated closed * by acking the close message and then terminating, or be receiving a client close ack, and then closing. * * In either case, the connection can only be closed after a client close message has been seen, which is * why this is the only place that actually closes connections. */ val handleClientControlMessages = Flow[Message].transform(() => new PushStage[Message, Message] { def onPush(elem: Message, ctx: Context[Message]) = { elem match { case PingMessage(data) => ctx.push(PongMessage(data)) // If we receive a close message from the client, we must send it back before closing case close: CloseMessage if state.compareAndSet(Open, ClientInitiatedClose) => ctx.pushAndFinish(close) // Otherwise, this must be a clients reply to a server initiated close, we can now close // the TCP connection case close: CloseMessage => ctx.finish() case other => ctx.pull() } } }) /** * Handles server initiated close. * * The events that can trigger a server initiated close include terminating the stream, failing, or manually * sending a close message. * * This stage will send finish after sending a close message */ val handleServerInitiatedClose = new PushPullStage[Message, Message] { var closeToSend: CloseMessage = null def onPush(elem: Message, ctx: Context[Message]) = { elem match { case close: CloseMessage if state.compareAndSet(Open, ServerInitiatedClose) => ctx.pushAndFinish(close) case other => ctx.push(other) } } def onPull(ctx: Context[Message]) = { if (closeToSend != null) { val toSend = closeToSend closeToSend = null ctx.pushAndFinish(toSend) } else { ctx.pull() } } override def onUpstreamFinish(ctx: Context[Message]) = { if (state.compareAndSet(Open, ServerInitiatedClose)) { closeToSend = CloseMessage(Some(CloseCodes.Regular)) ctx.absorbTermination() } else { // Just finish, we must already be finishing. ctx.finish() } } override def onUpstreamFailure(cause: Throwable, ctx: Context[Message]) = { if (state.compareAndSet(Open, ServerInitiatedClose)) { cause match { case WebSocketCloseException(close) => closeToSend = close case ignore: AbruptTerminationException => // Since the flow handling the WebSocket is usually a disconnected sink/source, if the sink // cancels, then the source will generally never terminate. Eventually when Akka shuts the // actor handling it down, it will fail with an abrupt termination exception. This can generally // be ignored, but we handle it just in case. The closeToSend will never be sent in this // situation, since the Actor is shutting down. logger.trace("WebSocket flow did not complete its downstream, this is probably ok", ignore) closeToSend = CloseMessage(Some(CloseCodes.UnexpectedCondition)) case other => logger.warn("WebSocket flow threw exception, closing WebSocket", other) closeToSend = CloseMessage(Some(CloseCodes.UnexpectedCondition)) } ctx.absorbTermination() } else { // Just fail, we must already be finishing. ctx.fail(cause) } } } val serverCancellationState = new AtomicReference[Either[AsyncCallback[Message], Message]](null) val handleServerCancellation = AkkaStreams.blockCancel[Message] { () => if (state.compareAndSet(Open, ServerInitiatedClose)) { val close = CloseMessage(Some(CloseCodes.Regular)) if (!serverCancellationState.compareAndSet(null, Right(close))) { val Left(callback) = serverCancellationState.get() callback.invoke(close) } } } val propagateServerCancellation = Flow[Message].transform(() => new AsyncStage[Message, Message, Message] { def onAsyncInput(event: Message, ctx: AsyncContext[Message, Message]) = { ctx.pushAndFinish(event) } def onPush(elem: Message, ctx: AsyncContext[Message, Message]) = ctx.holdUpstream() def onPull(ctx: AsyncContext[Message, Message]) = { if (!serverCancellationState.compareAndSet(null, Left(ctx.getAsyncCallback()))) { val Right(closeToSend) = serverCancellationState.get() ctx.pushAndFinish(closeToSend) } else { ctx.holdDownstream() } } }) /** * Blocks all messages after a close message has been sent, in accordance with the WebSocket spec. */ val blockAllMessagesAfterClose: Flow[Message, Message, _] = Flow[Message].transform(() => new PushPullStage[Message, Message] { var closeSeen = false def onPush(elem: Message, ctx: Context[Message]) = { if (closeSeen) { ctx.pull() } else { if (elem.isInstanceOf[CloseMessage]) { closeSeen = true } ctx.push(elem) } } def onPull(ctx: Context[Message]) = { ctx.pull() } }) val broadcast = builder.add(Broadcast[Message](2)) val merge = builder.add(OnlyFirstCanFinishMerge[Message](3)) broadcast.out(0) ~> handleClientControlMessages ~> merge.in(0) broadcast.out(1) ~> handleServerCancellation ~> flow.transform(() => handleServerInitiatedClose) ~> merge.in(1) Source.lazyEmpty ~> propagateServerCancellation ~> merge.in(2) (broadcast.in, (merge.out ~> blockAllMessagesAfterClose).outlet) } } private sealed trait State private case object Open extends State private case object ServerInitiatedClose extends State private case object ClientInitiatedClose extends State private val logger = Logger("play.core.server.common.WebSocketFlowHandler") }
nelsonblaha/playframework
framework/src/play/src/main/scala/play/api/inject/Module.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api.inject import java.lang.reflect.Constructor import play.{ Configuration => JavaConfiguration, Environment => JavaEnvironment } import play.api._ import play.utils.PlayIO import scala.annotation.varargs import scala.reflect.ClassTag /** * A Play dependency injection module. * * Dependency injection modules can be used by Play plugins to provide bindings for JSR-330 compliant * ApplicationLoaders. Any plugin that wants to provide components that a Play application can use may implement * one of these. * * Providing custom modules can be done by appending their fully qualified class names to `play.modules.enabled` in * `application.conf`, for example * * {{{ * play.modules.enabled += "com.example.FooModule" * play.modules.enabled += "com.example.BarModule" * }}} * * It is strongly advised that in addition to providing a module for JSR-330 DI, that plugins also provide a Scala * trait that constructs the modules manually. This allows for use of the module without needing a runtime dependency * injection provider. * * The `bind` methods are provided only as a DSL for specifying bindings. For example: * * {{{ * def bindings(env: Environment, conf: Configuration) = Seq( * bind[Foo].to[FooImpl], * bind[Bar].to(new Bar()), * bind[Foo].qualifiedWith[SomeQualifier].to[OtherFoo] * ) * }}} */ abstract class Module { /** * Get the bindings provided by this module. * * Implementations are strongly encouraged to do *nothing* in this method other than provide bindings. Startup * should be handled in the the constructors and/or providers bound in the returned bindings. Dependencies on other * modules or components should be expressed through constructor arguments. * * The configuration and environment a provided for the purpose of producing dynamic bindings, for example, if what * gets bound depends on some configuration, this may be read to control that. * * @param environment The environment * @param configuration The configuration * @return A sequence of bindings */ def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] /** * Create a binding key for the given class. */ final def bind[T](clazz: Class[T]): BindingKey[T] = play.api.inject.bind(clazz) /** * Create a binding key for the given class. */ final def bind[T: ClassTag]: BindingKey[T] = play.api.inject.bind[T] /** * Create a seq. * * For Java compatibility. */ @varargs final def seq(bindings: Binding[_]*): Seq[Binding[_]] = bindings } /** * Locates and loads modules from the Play environment. */ object Modules { /** * Locate the modules from the environment. * * Loads all modules specified by the play.modules.enabled property, minus the modules specified by the * play.modules.disabled property. If the modules have constructors that take an `Environment` and a * `Configuration`, then these constructors are called first; otherwise default constructors are called. * * @param environment The environment. * @param configuration The configuration. * @return A sequence of objects. This method makes no attempt to cast or check the types of the modules being loaded, * allowing ApplicationLoader implementations to reuse the same mechanism to load modules specific to them. */ def locate(environment: Environment, configuration: Configuration): Seq[Any] = { val includes = configuration.getStringSeq("play.modules.enabled").getOrElse(Seq.empty) val excludes = configuration.getStringSeq("play.modules.disabled").getOrElse(Seq.empty) val moduleClassNames = includes.toSet -- excludes moduleClassNames.map { className => try { val clazz = environment.classLoader.loadClass(className) def tryConstruct(args: AnyRef*): Option[Any] = { val ctor: Option[Constructor[_]] = try { val argTypes = args.map(_.getClass) Some(clazz.getConstructor(argTypes: _*)) } catch { case _: NoSuchMethodException => None case _: SecurityException => None } ctor.map(_.newInstance(args: _*)) } { tryConstruct(environment, configuration) } orElse { tryConstruct(new JavaEnvironment(environment), new JavaConfiguration(configuration)) } orElse { tryConstruct() } getOrElse { throw new PlayException("No valid constructors", "Module [" + className + "] cannot be instantiated.") } } catch { case e: PlayException => throw e case e: VirtualMachineError => throw e case e: ThreadDeath => throw e case e: Throwable => throw new PlayException( "Cannot load module", "Module [" + className + "] cannot be instantiated.", e) } }.toSeq } }
nelsonblaha/playframework
framework/src/play-streams/src/main/scala/play/api/libs/streams/impl/SubscriptionFactory.scala
<gh_stars>1-10 package play.api.libs.streams.impl import org.reactivestreams._ /** * A SubscriptionFactory is an object that knows how to create Subscriptions. * It can be used as a building block for creating Publishers, allowing the * Subscription creation logic to be factored out. */ private[streams] trait SubscriptionFactory[T] { /** * Create a Subscription object and return a handle to it. * * After calling this method the Subscription may be discarded, so the Subscription * shouldn't perform any actions or call any methods on the Subscriber * until `start` is called. The purpose of the `start` method is to give * the caller an opportunity to optimistically create Subscription objects * but then discard them if they can't be used for some reason. For * example, if two `Subscriptions` are concurrently created for the same * `Subscriber` then some implementations will only call `start` on * one of the `SubscriptionHandle`s. */ def createSubscription[U >: T]( subr: Subscriber[U], onSubscriptionEnded: SubscriptionHandle[U] => Unit): SubscriptionHandle[U] } /** * Wraps a Subscription created by a SubscriptionFactory, allowing the * Subscription to be started and queried. */ trait SubscriptionHandle[U] { /** * Called to start the Subscription. This will typically call the * onSubscribe method on the Suscription's Subscriber. In the event * that this method is never called the Subscription should not * leak resources. */ def start(): Unit /** * The Subscriber for this Subscription. */ def subscriber: Subscriber[U] /** * Whether or not this Subscription is active. It won't be active if it has * been cancelled, completed or had an error. */ def isActive: Boolean }
nelsonblaha/playframework
framework/src/play-ws/src/main/scala/play/api/libs/ws/ssl/debug/FixLoggingAction.scala
/* * * * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> * */ package play.api.libs.ws.ssl.debug import java.lang.reflect.Field import java.security.PrivilegedExceptionAction import play.api.libs.ws.ssl.MonkeyPatcher /** * A privileged action that will find relevant classes containing static final fields of type T and replace * them with the object referenced by {{newDebug}}, and switch out the "args" field value with the value defined * in {{newOptions}}. This is the only way to change JSSE debugging after the class loads. */ abstract class FixLoggingAction extends PrivilegedExceptionAction[Unit] with MonkeyPatcher with ClassFinder { def newOptions: String def isValidField(field: Field, definedType: Class[_]): Boolean = { import java.lang.reflect.Modifier._ val modifiers: Int = field.getModifiers field.getType == definedType && isStatic(modifiers) } }
nelsonblaha/playframework
framework/src/play-streams/src/main/scala/play/api/libs/streams/impl/RelaxedPublisher.scala
package play.api.libs.streams.impl import org.reactivestreams._ /** * A Publisher which subscribes Subscribers without performing any * checking about whether he Suscriber is already subscribed. This * makes RelaxedPublisher a bit faster, but possibly a bit less safe, * than a CheckingPublisher. */ private[streams] abstract class RelaxedPublisher[T] extends Publisher[T] { self: SubscriptionFactory[T] => // Streams method final override def subscribe(subr: Subscriber[_ >: T]): Unit = { val handle: SubscriptionHandle[_] = createSubscription(subr, RelaxedPublisher.onSubscriptionEndedNop) handle.start() } } private[streams] object RelaxedPublisher { val onSubscriptionEndedNop: Any => Unit = _ => () }
nelsonblaha/playframework
framework/src/play/src/test/scala/play/mvc/ResultSpec.scala
package play.test import org.specs2.mutable._ import play.mvc.Result import scala.concurrent.Future import play.api.mvc.{ Cookie, Results, Result => ScalaResult } /** * */ object ResultSpec extends Specification { "Result" should { // This is in Scala because building wrapped scala results is easier. "test for cookies" in { val javaResult = Results.Ok("Hello world").withCookies(Cookie("name1", "value1")).asJava val cookies = javaResult.cookies() val cookie = cookies.iterator().next() cookie.name() must be_==("name1") cookie.value() must be_==("value1") } } }
nelsonblaha/playframework
framework/src/play/src/main/scala/play/utils/Conversions.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.utils /** * provides conversion helpers */ object Conversions { def newMap[A, B](data: (A, B)*) = Map(data: _*) }
nelsonblaha/playframework
documentation/manual/detailedTopics/production/code/debian.sbt
<filename>documentation/manual/detailedTopics/production/code/debian.sbt //#debian lazy val root = (project in file(".")) .enablePlugins(PlayScala, DebianPlugin) maintainer in Linux := "<NAME> <<EMAIL>>" packageSummary in Linux := "My custom package summary" packageDescription := "My longer package description" //#debian
nelsonblaha/playframework
framework/src/play/src/test/scala/play/api/libs/MimeTypesSpec.scala
/* * Copyright (C) 2014 Typesafe Inc. <http://www.typesafe.com> */ package play.api.libs import org.specs2.mutable._ object MimeTypesSpec extends Specification { "Mime types" should { "choose the correct mime type for file with lowercase extension" in { MimeTypes.forFileName("image.png") must be equalTo Some("image/png") } "choose the correct mime type for file with uppercase extension" in { MimeTypes.forFileName("image.PNG") must be equalTo Some("image/png") } } }
nelsonblaha/playframework
framework/src/play-filters-helpers/src/main/scala/play/filters/csrf/CSRFFilter.scala
<filename>framework/src/play-filters-helpers/src/main/scala/play/filters/csrf/CSRFFilter.scala<gh_stars>1-10 /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.filters.csrf import javax.inject.{ Provider, Inject } import akka.stream.Materializer import play.api.mvc._ import play.filters.csrf.CSRF._ /** * A filter that provides CSRF protection. * * These must be by name parameters because the typical use case for instantiating the filter is in Global, which * happens before the application is started. Since the default values for the parameters are loaded from config * and hence depend on a started application, they must be by name. * * @param config A csrf configuration object * @param tokenProvider A token provider to use. * @param errorHandler handling failed token error. */ class CSRFFilter( config: => CSRFConfig, val tokenProvider: TokenProvider = SignedTokenProvider, val errorHandler: ErrorHandler = CSRF.DefaultErrorHandler)(implicit mat: Materializer) extends EssentialFilter { @Inject def this(config: Provider[CSRFConfig], tokenProvider: TokenProvider, errorHandler: ErrorHandler, mat: Materializer) = { this(config.get, tokenProvider, errorHandler)(mat) } /** * Default constructor, useful from Java */ def this()(implicit mat: Materializer) = this(CSRFConfig.global, new ConfigTokenProvider(CSRFConfig.global), DefaultErrorHandler) def apply(next: EssentialAction): EssentialAction = new CSRFAction(next, config, tokenProvider, errorHandler) } object CSRFFilter { def apply( config: => CSRFConfig = CSRFConfig.global, tokenProvider: TokenProvider = new ConfigTokenProvider(CSRFConfig.global), errorHandler: ErrorHandler = DefaultErrorHandler)(implicit mat: Materializer): CSRFFilter = { new CSRFFilter(config, tokenProvider, errorHandler) } }
nelsonblaha/playframework
framework/src/play-ws/src/test/scala/play/api/libs/ws/ssl/SystemPropertiesSpec.scala
<filename>framework/src/play-ws/src/test/scala/play/api/libs/ws/ssl/SystemPropertiesSpec.scala /* * * * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> * */ package play.api.libs.ws.ssl import org.specs2.mutable._ import java.security.Security import play.api.libs.ws.WSClientConfig object SystemPropertiesSpec extends Specification with After { sequential def after = sp.clearProperties() val sp = new SystemConfiguration() "SystemProperties" should { "disableCheckRevocation should not be set normally" in { val config = WSClientConfig(ssl = SSLConfig(checkRevocation = None)) val originalOscp = Security.getProperty("ocsp.enable") sp.configure(config) // http://stackoverflow.com/a/8507905/5266 Security.getProperty("ocsp.enable") must_== originalOscp System.getProperty("com.sun.security.enableCRLDP") must beNull System.getProperty("com.sun.net.ssl.checkRevocation") must beNull } "disableCheckRevocation is set explicitly" in { val config = WSClientConfig(ssl = SSLConfig(checkRevocation = Some(true))) sp.configure(config) // http://stackoverflow.com/a/8507905/5266 Security.getProperty("ocsp.enable") must be("true") System.getProperty("com.sun.security.enableCRLDP") must be("true") System.getProperty("com.sun.net.ssl.checkRevocation") must be("true") } // @see http://www.oracle.com/technetwork/java/javase/documentation/tlsreadme2-176330.html "allowLegacyHelloMessages is not set" in { val config = WSClientConfig(ssl = SSLConfig(loose = SSLLooseConfig(allowLegacyHelloMessages = None))) sp.configure(config) System.getProperty("sun.security.ssl.allowLegacyHelloMessages") must beNull } // @see http://www.oracle.com/technetwork/java/javase/documentation/tlsreadme2-176330.html "allowLegacyHelloMessages is set" in { val config = WSClientConfig(ssl = SSLConfig(loose = SSLLooseConfig(allowLegacyHelloMessages = Some(true)))) sp.configure(config) System.getProperty("sun.security.ssl.allowLegacyHelloMessages") must be("true") } // @see http://www.oracle.com/technetwork/java/javase/documentation/tlsreadme2-176330.html "allowUnsafeRenegotiation not set" in { val config = WSClientConfig(ssl = SSLConfig(loose = SSLLooseConfig(allowUnsafeRenegotiation = None))) sp.configure(config) System.getProperty("sun.security.ssl.allowUnsafeRenegotiation") must beNull } // @see http://www.oracle.com/technetwork/java/javase/documentation/tlsreadme2-176330.html "allowUnsafeRenegotiation is set" in { val config = WSClientConfig(ssl = SSLConfig(loose = SSLLooseConfig(allowUnsafeRenegotiation = Some(true)))) sp.configure(config) System.getProperty("sun.security.ssl.allowUnsafeRenegotiation") must be("true") } } }
nelsonblaha/playframework
framework/src/play/src/main/scala/play/api/routing/sird/macroimpl/QueryStringParameterMacros.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ // This is in its own package so that the UrlContext.q interpolator in the sird package doesn't make the // Quasiquote.q interpolator ambiguous. package play.api.routing.sird.macroimpl import scala.reflect.macros.blackbox.Context import scala.language.experimental.macros /** * The macros are used to parse and validate the query string parameters at compile time. * * They generate AST that constructs the extractors directly with the parsed parameter name, instead of having to parse * the string context parameters at runtime. */ private[sird] object QueryStringParameterMacros { val paramEquals = "([^&=]+)=".r def required(c: Context) = { macroImpl(c, "q", "required") } def optional(c: Context) = { macroImpl(c, "q_?", "optional") } def seq(c: Context) = { macroImpl(c, "q_*", "seq") } def macroImpl(c: Context, name: String, extractorName: String) = { import c.universe._ // Inspect the prefix, this is call that constructs the StringContext, containing the StringContext parts c.prefix.tree match { case Apply(_, List(Apply(_, rawParts))) => // extract the part literals val parts = rawParts map { case Literal(Constant(const: String)) => const } // Extract paramName, and validate val startOfString = c.enclosingPosition.point + name.length + 1 val paramName = parts.head match { case paramEquals(param) => param case _ => c.abort(c.enclosingPosition.withPoint(startOfString), "Invalid start of string for query string extractor '" + parts.head + "', extractor string must have format " + name + "\"param=$extracted\"") } if (parts.length == 1) { c.abort(c.enclosingPosition.withPoint(startOfString + paramName.length), "Unexpected end of String, expected parameter extractor, eg $extracted") } if (parts.length > 2) { c.abort(c.enclosingPosition, "Query string extractor can only extract one parameter, extract multiple parameters using the & extractor, eg: " + name + "\"param1=$param1\" & " + name + "\"param2=$param2\"") } if (parts(1).nonEmpty) { c.abort(c.enclosingPosition, s"Unexpected text at end of query string extractor: '${parts(1)}'") } // Return AST that invokes the desired method to create the extractor on QueryStringParameterExtractor, passing // the parameter name to it val call = TermName(extractorName) c.Expr( q"_root_.play.api.routing.sird.QueryStringParameterExtractor.$call($paramName)" ) case _ => c.abort(c.enclosingPosition, "Invalid use of query string extractor") } } }
nelsonblaha/playframework
framework/src/play-akka-http-server/src/main/scala/akka/http/play/WebSocketHandler.scala
<filename>framework/src/play-akka-http-server/src/main/scala/akka/http/play/WebSocketHandler.scala package akka.http.play import akka.http.scaladsl.model.HttpResponse import akka.http.scaladsl.model.ws.UpgradeToWebsocket import akka.http.impl.engine.ws._ import akka.stream.scaladsl._ import akka.stream.stage.{ Context, Stage, PushStage } import akka.util.ByteString import play.api.http.websocket._ import play.api.libs.streams.AkkaStreams import play.core.server.common.WebSocketFlowHandler object WebSocketHandler { /** * Handle a WebSocket */ def handleWebSocket(upgrade: UpgradeToWebsocket, flow: Flow[Message, Message, _], bufferLimit: Int): HttpResponse = upgrade match { case lowLevel: UpgradeToWebsocketLowLevel => lowLevel.handleFrames(messageFlowToFrameFlow(flow, bufferLimit)) case other => throw new IllegalArgumentException("UpgradeToWebsocket is not an Akka HTTP UpgradeToWebsocketLowLevel") } /** * Convert a flow of messages to a flow of frame events. * * This implements the WebSocket control logic, including handling ping frames and closing the connection in a spec * compliant manner. */ def messageFlowToFrameFlow(flow: Flow[Message, Message, _], bufferLimit: Int): Flow[FrameEvent, FrameEvent, _] = { // Each of the stages here transforms frames to an Either[Message, ?], where Message is a close message indicating // some sort of protocol failure. The handleProtocolFailures function then ensures that these messages skip the // flow that we are wrapping, are sent to the client and the close procedure is implemented. Flow[FrameEvent] .transform(() => aggregateFrames(bufferLimit)) .transform(() => aggregateMessages(bufferLimit)) .transform(() => framesToMessages()) .via(handleProtocolFailures(WebSocketFlowHandler.webSocketProtocol(flow))) .map(messageToFrameEvent) } /** * Akka HTTP potentially splits frames into multiple frame events. * * This stage aggregates them so each frame is a full frame. * * @param bufferLimit The maximum size of frame data that should be buffered. */ private def aggregateFrames(bufferLimit: Int): Stage[FrameEvent, Either[Message, Frame]] = { new PushStage[FrameEvent, Either[Message, Frame]] { var currentFrameData: ByteString = null var currentFrameHeader: FrameHeader = null def onPush(elem: FrameEvent, ctx: Context[Either[Message, Frame]]) = elem match { // FrameData error handling first case unexpectedData: FrameData if currentFrameHeader == null => // Technically impossible, this indicates a bug in Akka HTTP, // since it has sent the start of a frame before finishing // the previous frame. ctx.push(close(Protocol.CloseCodes.UnexpectedCondition, "Server error")) case FrameData(data, _) if currentFrameData.size + data.size > bufferLimit => ctx.push(close(Protocol.CloseCodes.TooBig)) // FrameData handling case FrameData(data, false) => currentFrameData ++= data ctx.pull() case FrameData(data, true) => val frame = Frame(currentFrameHeader, currentFrameData ++ data) currentFrameHeader = null currentFrameData = null ctx.push(Right(frame)) // Frame start error handling case FrameStart(header, data) if currentFrameHeader != null => // Technically impossible, this indicates a bug in Akka HTTP, // since it has sent the start of a frame before finishing // the previous frame. ctx.push(close(Protocol.CloseCodes.UnexpectedCondition, "Server error")) // Frame start case fs @ FrameStart(header, data) if fs.lastPart => ctx.push(Right(Frame(header, data))) case FrameStart(header, data) => currentFrameHeader = header currentFrameData = data ctx.pull() } } } /** * The WebSocket protocol allows messages to be fragmented across multiple frames. * * This stage aggregates them so each frame is a full message. It also unmasks frames. * * @param bufferLimit The maximum size of frame data that should be buffered. */ private def aggregateMessages(bufferLimit: Int): Stage[Either[Message, Frame], Either[Message, Frame]] = { new PushStage[Either[Message, Frame], Either[Message, Frame]] { var currentMessageData: ByteString = null var currentMessageHeader: FrameHeader = null def onPush(elem: Either[Message, Frame], ctx: Context[Either[Message, Frame]]) = elem match { case close @ Left(_) => ctx.push(close) case Right(frame) => // Protocol checks if (frame.header.mask.isEmpty) { ctx.push(close(Protocol.CloseCodes.ProtocolError, "Unmasked client frame")) } else if (frame.header.opcode == Protocol.Opcode.Continuation) { if (currentMessageHeader == null) { ctx.push(close(Protocol.CloseCodes.ProtocolError, "Unexpected continuation frame")) } else if (currentMessageData.size + frame.data.size > bufferLimit) { ctx.push(close(Protocol.CloseCodes.TooBig)) } else if (frame.header.fin) { val currentFrame = Frame(currentMessageHeader, currentMessageData ++ frame.unmaskedData) currentMessageHeader = null currentMessageData = null ctx.push(Right(currentFrame)) } else { currentMessageData ++= frame.unmaskedData ctx.pull() } } else if (currentMessageHeader != null) { ctx.push(close(Protocol.CloseCodes.ProtocolError, "Received non continuation frame when previous message wasn't finished")) } else if (frame.header.fin) { ctx.push(Right(Frame(frame.header, frame.unmaskedData))) } else { currentMessageHeader = frame.header currentMessageData = frame.unmaskedData ctx.pull() } } } } /** * Converts frames to Play messages. */ private def framesToMessages(): Stage[Either[Message, Frame], Either[Message, Message]] = new PushStage[Either[Message, Frame], Either[Message, Message]] { def onPush(elem: Either[Message, Frame], ctx: Context[Either[Message, Message]]) = elem match { case Left(close) => ctx.push(Left(close)) case Right(frame) => frame.header.opcode match { case Protocol.Opcode.Binary => ctx.push(Right(BinaryMessage(frame.data))) case Protocol.Opcode.Text => ctx.push(Right(TextMessage(frame.data.utf8String))) case Protocol.Opcode.Close => val statusCode = FrameEventParser.parseCloseCode(frame.data) val reason = frame.data.drop(2).utf8String ctx.push(Right(CloseMessage(statusCode, reason))) case Protocol.Opcode.Ping => ctx.push(Right(PingMessage(frame.data))) case Protocol.Opcode.Pong => ctx.push(Right(PongMessage(frame.data))) case other => ctx.push(close(Protocol.CloseCodes.PolicyViolated)) } } } /** * Converts Play messages to Akka HTTP frame events. */ private def messageToFrameEvent(message: Message): FrameEvent = { def frameEvent(opcode: Protocol.Opcode, data: ByteString) = FrameEvent.fullFrame(opcode, None, data, fin = true) message match { case TextMessage(data) => frameEvent(Protocol.Opcode.Text, ByteString(data)) case BinaryMessage(data) => frameEvent(Protocol.Opcode.Binary, data) case PingMessage(data) => frameEvent(Protocol.Opcode.Ping, data) case PongMessage(data) => frameEvent(Protocol.Opcode.Pong, data) case CloseMessage(Some(statusCode), reason) => FrameEvent.closeFrame(statusCode, reason) case CloseMessage(None, _) => frameEvent(Protocol.Opcode.Close, ByteString.empty) } } /** * Handles the protocol failures by gracefully closing the connection. */ private def handleProtocolFailures: Flow[Message, Message, _] => Flow[Either[Message, Message], Message, _] = { AkkaStreams.bypassWith(Flow[Either[Message, Message]].transform(() => new PushStage[Either[Message, Message], Either[Message, Message]] { var closing = false def onPush(elem: Either[Message, Message], ctx: Context[Either[Message, Message]]) = elem match { case _ if closing => ctx.finish() case Right(message) => ctx.push(Left(message)) case Left(close) => closing = true ctx.push(Right(close)) } }), AkkaStreams.EagerFinishMerge(2)) } private case class Frame(header: FrameHeader, data: ByteString) { def unmaskedData = FrameEventParser.mask(data, header.mask) } private def close(status: Int, message: String = "") = { Left(new CloseMessage(Some(status), message)) } }
nelsonblaha/playframework
framework/src/play-streams/src/main/scala/play/api/libs/streams/impl/PublisherEnumerator.scala
package play.api.libs.streams.impl import org.reactivestreams._ import play.api.libs.iteratee._ import scala.concurrent.{ ExecutionContext, Future, Promise } /** * Adapts a Publisher to an Enumerator. * * When an Iteratee is applied to the Enumerator, we adapt the Iteratee into * a Subscriber, then subscribe it to the Publisher. */ final class PublisherEnumerator[T](pubr: Publisher[T]) extends Enumerator[T] { def apply[A](i: Iteratee[T, A]): Future[Iteratee[T, A]] = { val subr = new IterateeSubscriber(i) pubr.subscribe(subr) Future.successful(subr.result) } }
nelsonblaha/playframework
framework/src/play/src/main/scala/play/core/j/HttpExecutionContext.scala
<gh_stars>0 /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.core.j import java.util.concurrent.Executor import play.mvc.Http import scala.compat.java8.FutureConverters import scala.concurrent.{ ExecutionContext, ExecutionContextExecutor } object HttpExecutionContext { /** * Create an HttpExecutionContext with values from the current thread. */ def fromThread(delegate: ExecutionContext): ExecutionContextExecutor = new HttpExecutionContext(Thread.currentThread().getContextClassLoader(), Http.Context.current.get(), delegate) /** * Create an HttpExecutionContext with values from the current thread. * * This method is necessary to prevent ambiguous method compile errors since ExecutionContextExecutor */ def fromThread(delegate: ExecutionContextExecutor): ExecutionContextExecutor = fromThread(delegate: ExecutionContext) /** * Create an HttpExecutionContext with values from the current thread. */ def fromThread(delegate: Executor): ExecutionContextExecutor = new HttpExecutionContext(Thread.currentThread().getContextClassLoader(), Http.Context.current.get(), FutureConverters.fromExecutor(delegate)) /** * Create an ExecutionContext that will, when prepared, be created with values from that thread. */ def unprepared(delegate: ExecutionContext) = new ExecutionContext { def execute(runnable: Runnable) = delegate.execute(runnable) // FIXME: Make calling this an error once SI-7383 is fixed def reportFailure(t: Throwable) = delegate.reportFailure(t) override def prepare(): ExecutionContext = fromThread(delegate) } } /** * Manages execution to ensure that the given context ClassLoader and Http.Context are set correctly * in the current thread. Actual execution is performed by a delegate ExecutionContext. */ class HttpExecutionContext(contextClassLoader: ClassLoader, httpContext: Http.Context, delegate: ExecutionContext) extends ExecutionContextExecutor { override def execute(runnable: Runnable) = delegate.execute(new Runnable { def run() { val thread = Thread.currentThread() val oldContextClassLoader = thread.getContextClassLoader() val oldHttpContext = Http.Context.current.get() thread.setContextClassLoader(contextClassLoader) Http.Context.current.set(httpContext) try { runnable.run() } finally { thread.setContextClassLoader(oldContextClassLoader) Http.Context.current.set(oldHttpContext) } } }) override def reportFailure(t: Throwable) = delegate.reportFailure(t) override def prepare(): ExecutionContext = { val delegatePrepared = delegate.prepare() if (delegatePrepared eq delegate) { this } else { new HttpExecutionContext(contextClassLoader, httpContext, delegatePrepared) } } }
nelsonblaha/playframework
framework/src/play-streams/src/test/scala/play/api/libs/streams/impl/SubscriberEvents.scala
<reponame>nelsonblaha/playframework package play.api.libs.streams.impl import org.reactivestreams.{ Subscriber, Subscription } object SubscriberEvents { case object OnComplete case class OnError(t: Throwable) case class OnSubscribe(s: Subscription) case class OnNext(t: Int) } trait SubscriberEvents { self: EventRecorder => import SubscriberEvents._ object subscriber extends Subscriber[Int] { def onError(t: Throwable) = record(OnError(t)) def onSubscribe(s: Subscription) = record(OnSubscribe(s)) def onComplete() = record(OnComplete) def onNext(t: Int) = record(OnNext(t)) } }
nelsonblaha/playframework
framework/src/play/src/main/scala/play/api/Exceptions.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api /** * Generic exception for unexpected error cases. */ case class UnexpectedException(message: Option[String] = None, unexpected: Option[Throwable] = None) extends PlayException( "Unexpected exception", message.getOrElse { unexpected.map(t => "%s: %s".format(t.getClass.getSimpleName, t.getMessage)).getOrElse("") }, unexpected.orNull )
nelsonblaha/playframework
framework/src/play-ws/src/main/scala/play/api/libs/ws/package.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api.libs /** * Asynchronous API to to query web services, as an http client. */ package object ws { @deprecated("Use WSRequest", "2.4.0") type WSRequestHolder = WSRequest }
nelsonblaha/playframework
framework/src/iteratees/src/main/scala/play/api/libs/iteratee/Parsing.scala
<reponame>nelsonblaha/playframework /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api.libs.iteratee import scala.concurrent.Future import play.api.libs.iteratee.Execution.Implicits.{ defaultExecutionContext => dec } object Parsing { sealed trait MatchInfo[A] { def content: A def isMatch = this match { case Matched(_) => true case Unmatched(_) => false } } case class Matched[A](val content: A) extends MatchInfo[A] case class Unmatched[A](val content: A) extends MatchInfo[A] def search(needle: Array[Byte]): Enumeratee[Array[Byte], MatchInfo[Array[Byte]]] = new Enumeratee[Array[Byte], MatchInfo[Array[Byte]]] { val needleSize = needle.size val fullJump = needleSize val jumpBadCharecter: (Byte => Int) = { val map = Map(needle.dropRight(1).reverse.zipWithIndex.reverse: _*) //remove the last byte => map.get(byte).map(_ + 1).getOrElse(fullJump) } def applyOn[A](inner: Iteratee[MatchInfo[Array[Byte]], A]): Iteratee[Array[Byte], Iteratee[MatchInfo[Array[Byte]], A]] = { Iteratee.flatten(inner.fold1((a, e) => Future.successful(Done(Done(a, e), Input.Empty: Input[Array[Byte]])), k => Future.successful(Cont(step(Array[Byte](), Cont(k)))), (err, r) => throw new Exception())(dec)) } def scan(previousMatches: List[MatchInfo[Array[Byte]]], piece: Array[Byte], startScan: Int): (List[MatchInfo[Array[Byte]]], Array[Byte]) = { if (piece.length < needleSize) { (previousMatches, piece) } else { val fullMatch = Range(needleSize - 1, -1, -1).forall(scan => needle(scan) == piece(scan + startScan)) if (fullMatch) { val (prefix, suffix) = piece.splitAt(startScan) val (matched, left) = suffix.splitAt(needleSize) val newResults = previousMatches ++ List(Unmatched(prefix), Matched(matched)) filter (!_.content.isEmpty) if (left.length < needleSize) (newResults, left) else scan(newResults, left, 0) } else { val jump = jumpBadCharecter(piece(startScan + needleSize - 1)) val isFullJump = jump == fullJump val newScan = startScan + jump if (newScan + needleSize > piece.length) { val (prefix, suffix) = (piece.splitAt(startScan)) (previousMatches ++ List(Unmatched(prefix)), suffix) } else scan(previousMatches, piece, newScan) } } } def step[A](rest: Array[Byte], inner: Iteratee[MatchInfo[Array[Byte]], A])(in: Input[Array[Byte]]): Iteratee[Array[Byte], Iteratee[MatchInfo[Array[Byte]], A]] = { in match { case Input.Empty => Cont(step(rest, inner)) //here should rather pass Input.Empty along case Input.EOF => Done(inner, Input.El(rest)) case Input.El(chunk) => val all = rest ++ chunk def inputOrEmpty(a: Array[Byte]) = if (a.isEmpty) Input.Empty else Input.El(a) Iteratee.flatten(inner.fold1((a, e) => Future.successful(Done(Done(a, e), inputOrEmpty(rest))), k => { val (result, suffix) = scan(Nil, all, 0) val fed = result.filter(!_.content.isEmpty).foldLeft(Future.successful(Array[Byte]() -> Cont(k))) { (p, m) => p.flatMap(i => i._2.fold1((a, e) => Future.successful((i._1 ++ m.content, Done(a, e))), k => Future.successful((i._1, k(Input.El(m)))), (err, e) => throw new Exception())(dec) )(dec) } fed.flatMap { case (ss, i) => i.fold1((a, e) => Future.successful(Done(Done(a, e), inputOrEmpty(ss ++ suffix))), k => Future.successful(Cont[Array[Byte], Iteratee[MatchInfo[Array[Byte]], A]]((in: Input[Array[Byte]]) => in match { case Input.EOF => Done(k(Input.El(Unmatched(suffix))), Input.EOF) //suffix maybe empty case other => step(ss ++ suffix, Cont(k))(other) })), (err, e) => throw new Exception())(dec) }(dec) }, (err, e) => throw new Exception())(dec) ) } } } }
nelsonblaha/playframework
framework/src/play-docs-sbt-plugin/src/main/scala/com/typesafe/play/docs/sbtplugin/PlayDocsValidation.scala
<reponame>nelsonblaha/playframework /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package com.typesafe.play.docs.sbtplugin import java.io.{ Closeable, BufferedReader, InputStreamReader, InputStream } import java.net.HttpURLConnection import java.util.concurrent.Executors import java.util.jar.JarFile import org.pegdown.ast._ import org.pegdown.ast.Node import org.pegdown.plugins.{ ToHtmlSerializerPlugin, PegDownPlugins } import org.pegdown._ import play.sbt.Colors import play.doc._ import sbt.{ FileRepository => _, _ } import sbt.Keys._ import scala.collection.mutable import scala.collection.mutable.ListBuffer import scala.concurrent.duration.Duration import scala.concurrent.{ Await, Future, ExecutionContext } import scala.util.control.NonFatal import Imports.PlayDocsKeys._ // Test that all the docs are renderable and valid object PlayDocsValidation { /** * A report of all references from all markdown files. * * This is the main markdown report for validating markdown docs. */ case class MarkdownRefReport(markdownFiles: Seq[File], wikiLinks: Seq[LinkRef], resourceLinks: Seq[LinkRef], codeSamples: Seq[CodeSampleRef], relativeLinks: Seq[LinkRef], externalLinks: Seq[LinkRef]) case class LinkRef(link: String, file: File, position: Int) case class CodeSampleRef(source: String, segment: String, file: File, sourcePosition: Int, segmentPosition: Int) /** * A report of just code samples in all markdown files. * * This is used to compare translations to the originals, checking that all files exist and all code samples exist. */ case class CodeSamplesReport(files: Seq[FileWithCodeSamples]) { lazy val byFile = files.map(f => f.name -> f).toMap lazy val byName = files.filterNot(_.name.endsWith("_Sidebar.md")).map { file => val filename = file.name val name = filename.takeRight(filename.length - filename.lastIndexOf('/')) name -> file }.toMap } case class FileWithCodeSamples(name: String, source: String, codeSamples: Seq[CodeSample]) case class CodeSample(source: String, segment: String, sourcePosition: Int, segmentPosition: Int) case class TranslationReport(missingFiles: Seq[String], introducedFiles: Seq[String], changedPathFiles: Seq[(String, String)], codeSampleIssues: Seq[TranslationCodeSamples], okFiles: Seq[String], total: Int) case class TranslationCodeSamples(name: String, missingCodeSamples: Seq[CodeSample], introducedCodeSamples: Seq[CodeSample], totalCodeSamples: Int) /** * Configuration for validation. * * @param downstreamWikiPages Wiki pages from downstream projects - so that the documentation can link to them. * @param downstreamApiPaths The downstream API paths */ case class ValidationConfig(downstreamWikiPages: Set[String] = Set.empty[String], downstreamApiPaths: Seq[String] = Nil) val generateMarkdownRefReportTask = Def.task { val base = manualPath.value val markdownFiles = (base / "manual" ** "*.md").get val wikiLinks = mutable.ListBuffer[LinkRef]() val resourceLinks = mutable.ListBuffer[LinkRef]() val codeSamples = mutable.ListBuffer[CodeSampleRef]() val relativeLinks = mutable.ListBuffer[LinkRef]() val externalLinks = mutable.ListBuffer[LinkRef]() def stripFragment(path: String) = if (path.contains("#")) { path.dropRight(path.length - path.indexOf('#')) } else { path } def parseMarkdownFile(markdownFile: File): String = { val processor = new PegDownProcessor(Extensions.ALL, PegDownPlugins.builder() .withPlugin(classOf[CodeReferenceParser]).build) // Link renderer will also verify that all wiki links exist val linkRenderer = new LinkRenderer { override def render(node: WikiLinkNode) = { node.getText match { case link if link.contains("|") => val parts = link.split('|') val desc = parts.head val page = stripFragment(parts.tail.head.trim) wikiLinks += LinkRef(page, markdownFile, node.getStartIndex + desc.length + 3) case image if image.endsWith(".png") => image match { case full if full.startsWith("http://") => externalLinks += LinkRef(full, markdownFile, node.getStartIndex + 2) case absolute if absolute.startsWith("/") => resourceLinks += LinkRef("manual" + absolute, markdownFile, node.getStartIndex + 2) case relative => val link = markdownFile.getParentFile.getCanonicalPath.stripPrefix(base.getCanonicalPath).stripPrefix("/") + "/" + relative resourceLinks += LinkRef(link, markdownFile, node.getStartIndex + 2) } case link => wikiLinks += LinkRef(link.trim, markdownFile, node.getStartIndex + 2) } new LinkRenderer.Rendering("foo", "bar") } override def render(node: AutoLinkNode) = addLink(node.getText, node, 1) override def render(node: ExpLinkNode, text: String) = addLink(node.url, node, text.length + 3) private def addLink(url: String, node: Node, offset: Int) = { url match { case full if full.startsWith("http://") || full.startsWith("https://") => externalLinks += LinkRef(full, markdownFile, node.getStartIndex + offset) case fragment if fragment.startsWith("#") => // ignore fragments, no validation of them for now case relative => relativeLinks += LinkRef(relative, markdownFile, node.getStartIndex + offset) } new LinkRenderer.Rendering("foo", "bar") } } val codeReferenceSerializer = new ToHtmlSerializerPlugin() { def visit(node: Node, visitor: Visitor, printer: Printer) = node match { case code: CodeReferenceNode => { // Label is after the #, or if no #, then is the link label val (source, label) = code.getSource.split("#", 2) match { case Array(source, label) => (source, label) case Array(source) => (source, code.getLabel) } // The file is either relative to current page page or absolute, under the root val sourceFile = if (source.startsWith("/")) { source.drop(1) } else { markdownFile.getParentFile.getCanonicalPath.stripPrefix(base.getCanonicalPath).stripPrefix("/") + "/" + source } val sourcePos = code.getStartIndex + code.getLabel.length + 4 val labelPos = if (code.getSource.contains("#")) { sourcePos + source.length + 1 } else { code.getStartIndex + 2 } codeSamples += CodeSampleRef(sourceFile, label, markdownFile, sourcePos, labelPos) true } case _ => false } } val astRoot = processor.parseMarkdown(IO.read(markdownFile).toCharArray) new ToHtmlSerializer(linkRenderer, java.util.Arrays.asList[ToHtmlSerializerPlugin](codeReferenceSerializer)) .toHtml(astRoot) } markdownFiles.foreach(parseMarkdownFile) MarkdownRefReport(markdownFiles, wikiLinks.toSeq, resourceLinks.toSeq, codeSamples.toSeq, relativeLinks.toSeq, externalLinks.toSeq) } private def extractCodeSamples(filename: String, markdownSource: String): FileWithCodeSamples = { val codeSamples = ListBuffer.empty[CodeSample] val processor = new PegDownProcessor(Extensions.ALL, PegDownPlugins.builder() .withPlugin(classOf[CodeReferenceParser]).build) val codeReferenceSerializer = new ToHtmlSerializerPlugin() { def visit(node: Node, visitor: Visitor, printer: Printer) = node match { case code: CodeReferenceNode => { // Label is after the #, or if no #, then is the link label val (source, label) = code.getSource.split("#", 2) match { case Array(source, label) => (source, label) case Array(source) => (source, code.getLabel) } // The file is either relative to current page page or absolute, under the root val sourceFile = if (source.startsWith("/")) { source.drop(1) } else { filename.dropRight(filename.length - filename.lastIndexOf('/') + 1) + source } val sourcePos = code.getStartIndex + code.getLabel.length + 4 val labelPos = if (code.getSource.contains("#")) { sourcePos + source.length + 1 } else { code.getStartIndex + 2 } codeSamples += CodeSample(sourceFile, label, sourcePos, labelPos) true } case _ => false } } val astRoot = processor.parseMarkdown(markdownSource.toCharArray) new ToHtmlSerializer(new LinkRenderer(), java.util.Arrays.asList[ToHtmlSerializerPlugin](codeReferenceSerializer)) .toHtml(astRoot) FileWithCodeSamples(filename, markdownSource, codeSamples.toList) } val generateUpstreamCodeSamplesTask = Def.task { docsJarFile.value match { case Some(jarFile) => import scala.collection.JavaConversions._ val jar = new JarFile(jarFile) val parsedFiles = jar.entries().toIterator.collect { case entry if entry.getName.endsWith(".md") && entry.getName.startsWith("play/docs/content/manual") => val fileName = entry.getName.stripPrefix("play/docs/content") val contents = IO.readStream(jar.getInputStream(entry)) extractCodeSamples(fileName, contents) }.toList jar.close() CodeSamplesReport(parsedFiles) case None => CodeSamplesReport(Seq.empty) } } val generateMarkdownCodeSamplesTask = Def.task { val base = manualPath.value val markdownFiles = (base / "manual" ** "*.md").get.pair(relativeTo(base)) CodeSamplesReport(markdownFiles.map { case (file, name) => extractCodeSamples("/" + name, IO.read(file)) }) } val translationCodeSamplesReportTask = Def.task { val report = generateMarkdownCodeSamplesReport.value val upstream = generateUpstreamCodeSamplesReport.value val file = translationCodeSamplesReportFile.value val version = docsVersion.value def sameCodeSample(cs1: CodeSample)(cs2: CodeSample) = { cs1.source == cs2.source && cs1.segment == cs2.segment } def hasCodeSample(samples: Seq[CodeSample])(sample: CodeSample) = samples.exists(sameCodeSample(sample)) val untranslatedFiles = (upstream.byFile.keySet -- report.byFile.keySet).toList.sorted val introducedFiles = (report.byFile.keySet -- upstream.byFile.keySet).toList.sorted val matchingFilesByName = (report.byName.keySet & upstream.byName.keySet).map { name => report.byName(name) -> upstream.byName(name) } val (matchingFiles, changedPathFiles) = matchingFilesByName.partition(f => f._1.name == f._2.name) val (codeSampleIssues, okFiles) = matchingFiles.map { case (actualFile, upstreamFile) => val missingCodeSamples = upstreamFile.codeSamples.filterNot(hasCodeSample(actualFile.codeSamples)) val introducedCodeSamples = actualFile.codeSamples.filterNot(hasCodeSample(actualFile.codeSamples)) TranslationCodeSamples(actualFile.name, missingCodeSamples, introducedCodeSamples, upstreamFile.codeSamples.size) }.partition(c => c.missingCodeSamples.nonEmpty || c.introducedCodeSamples.nonEmpty) val result = TranslationReport( untranslatedFiles, introducedFiles, changedPathFiles.map(f => f._1.name -> f._2.name).toList.sorted, codeSampleIssues.toList.sortBy(_.name), okFiles.map(_.name).toList.sorted, report.files.size ) IO.write(file, html.translationReport(result, version).body) file } val cachedTranslationCodeSamplesReportTask = Def.task { val file = translationCodeSamplesReportFile.value if (!file.exists) { println("Generating report...") Project.runTask(translationCodeSamplesReport, state.value).get._2.toEither.fold({ incomplete => throw incomplete.directCause.get }, result => result) } else { file } } val validateDocsTask = Def.task { val report = generateMarkdownRefReport.value val log = streams.value.log val base = manualPath.value val validationConfig = playDocsValidationConfig.value val docsJarRepo: play.doc.FileRepository with Closeable = if (docsJarFile.value.isDefined) { val jar = new JarFile(docsJarFile.value.get) new JarRepository(jar, Some("play/docs/content")) with Closeable } else { new play.doc.FileRepository with Closeable { def loadFile[A](path: String)(loader: (InputStream) => A) = None def handleFile[A](path: String)(handler: (FileHandle) => A) = None def findFileWithName(name: String) = None def close(): Unit = () } } val fileRepo = new FilesystemRepository(base / "manual") val combinedRepo = new AggregateFileRepository(Seq(docsJarRepo, fileRepo)) val pageIndex = PageIndex.parseFrom(combinedRepo, "", None) val pages = report.markdownFiles.map(f => f.getName.dropRight(3) -> f).toMap var failed = false def doAssertion(desc: String, errors: Seq[_])(onFail: => Unit): Unit = { if (errors.isEmpty) { log.info("[" + Colors.green("pass") + "] " + desc) } else { failed = true onFail log.info("[" + Colors.red("fail") + "] " + desc + " (" + errors.size + " errors)") } } def fileExists(path: String): Boolean = { new File(base, path).isFile || docsJarRepo.loadFile(path)(_ => ()).nonEmpty } def assertLinksNotMissing(desc: String, links: Seq[LinkRef], errorMessage: String): Unit = { doAssertion(desc, links) { links.foreach { link => logErrorAtLocation(log, link.file, link.position, errorMessage + " " + link.link) } } } val duplicates = report.markdownFiles .filterNot(_.getName.startsWith("_")) .groupBy(s => s.getName) .filter(v => v._2.size > 1) doAssertion("Duplicate markdown file name test", duplicates.toSeq) { duplicates.foreach { d => log.error(d._1 + ":\n" + d._2.mkString("\n ")) } } assertLinksNotMissing("Missing wiki links test", report.wikiLinks.filterNot { link => pages.contains(link.link) || validationConfig.downstreamWikiPages(link.link) || docsJarRepo.findFileWithName(link.link + ".md").nonEmpty }, "Could not find link") def relativeLinkOk(link: LinkRef) = { link match { case badScalaApi if badScalaApi.link.startsWith("api/scala/index.html#") => println("Don't use segment links from the index.html page to scaladocs, use path links, ie:") println(" api/scala/index.html#play.api.Application@requestHandler") println("should become:") println(" api/scala/play/api/Application.html#requestHandler") false case scalaApi if scalaApi.link.startsWith("api/scala/") => fileExists(scalaApi.link.split('#').head) case javaApi if javaApi.link.startsWith("api/java/") => fileExists(javaApi.link.split('#').head) case resource if resource.link.startsWith("resources/") => fileExists(resource.link.stripPrefix("resources/")) case bad => false } } assertLinksNotMissing("Relative link test", report.relativeLinks.collect { case link if !relativeLinkOk(link) => link }, "Bad relative link") assertLinksNotMissing("Missing wiki resources test", report.resourceLinks.collect { case link if !fileExists(link.link) => link }, "Could not find resource") val (existing, nonExisting) = report.codeSamples.partition(sample => fileExists(sample.source)) assertLinksNotMissing("Missing source files test", nonExisting.map(sample => LinkRef(sample.source, sample.file, sample.sourcePosition)), "Could not find source file") def segmentExists(sample: CodeSampleRef) = { if (sample.segment.nonEmpty) { // Find the code segment val sourceCode = { val file = new File(base, sample.source) if (file.exists()) { IO.readLines(new File(base, sample.source)) } else { docsJarRepo.loadFile(sample.source)(is => IO.readLines(new BufferedReader(new InputStreamReader(is)))).get } } val notLabel = (s: String) => !s.contains("#" + sample.segment) val segment = sourceCode dropWhile (notLabel) drop (1) takeWhile (notLabel) !segment.isEmpty } else { true } } assertLinksNotMissing("Missing source segments test", existing.collect { case sample if !segmentExists(sample) => LinkRef(sample.segment, sample.file, sample.segmentPosition) }, "Could not find source segment") val allLinks = report.wikiLinks.map(_.link).toSet pageIndex.foreach { idx => // Make sure all pages are in the page index val orphanPages = pages.filterNot(p => idx.get(p._1).isDefined) doAssertion("Orphan pages test", orphanPages.toSeq) { orphanPages.foreach { page => log.error("Page " + page._2 + " is not referenced by the index") } } } docsJarRepo.close() if (failed) { throw new RuntimeException("Documentation validation failed") } } val validateExternalLinksTask = Def.task { val log = streams.value.log val report = generateMarkdownRefReport.value val grouped = report.externalLinks .groupBy { _.link } .filterNot { e => e._1.startsWith("http://localhost:") || e._1.contains("example.com") } .toSeq.sortBy { _._1 } implicit val ec = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(50)) val futures = grouped.map { entry => Future { val (url, refs) = entry val connection = new URL(url).openConnection().asInstanceOf[HttpURLConnection] try { connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:37.0) Gecko/20100101 Firefox/37.0") connection.connect() connection.getResponseCode match { // A few people use GitHub.com repositories, which will return 403 errors for directory listings case 403 if "GitHub.com".equals(connection.getHeaderField("Server")) => Nil case bad if bad >= 300 => { refs.foreach { link => logErrorAtLocation(log, link.file, link.position, connection.getResponseCode + " response for external link " + link.link) } refs } case ok => Nil } } catch { case NonFatal(e) => refs.foreach { link => logErrorAtLocation(log, link.file, link.position, e.getClass.getName + ": " + e.getMessage + " for external link " + link.link) } refs } finally { connection.disconnect() } } } val invalidRefs = Await.result(Future.sequence(futures), Duration.Inf).flatten ec.shutdownNow() if (invalidRefs.isEmpty) { log.info("[" + Colors.green("pass") + "] External links test") } else { log.info("[" + Colors.red("fail") + "] External links test (" + invalidRefs.size + " errors)") throw new RuntimeException("External links validation failed") } grouped.map(_._1) } private def logErrorAtLocation(log: Logger, file: File, position: Int, errorMessage: String) = synchronized { // Load the source val lines = IO.readLines(file) // Calculate the line and col // Tuple is (total chars seen, line no, col no, Option[line]) val (_, lineNo, colNo, line) = lines.foldLeft((0, 0, 0, None: Option[String])) { (state, line) => state match { case (_, _, _, Some(_)) => state case (total, l, c, None) => { if (total + line.length < position) { (total + line.length + 1, l + 1, c, None) } else { (0, l + 1, position - total + 1, Some(line)) } } } } log.error(errorMessage + " at " + file.getAbsolutePath + ":" + lineNo) line.foreach { l => log.error(l) log.error(l.take(colNo - 1).map { case '\t' => '\t'; case _ => ' ' } + "^") } } } class AggregateFileRepository(repos: Seq[FileRepository]) extends FileRepository { def this(repos: Array[FileRepository]) = this(repos.toSeq) private def fromFirstRepo[A](load: FileRepository => Option[A]) = repos.collectFirst(Function.unlift(load)) def loadFile[A](path: String)(loader: (InputStream) => A) = fromFirstRepo(_.loadFile(path)(loader)) def handleFile[A](path: String)(handler: (FileHandle) => A) = fromFirstRepo(_.handleFile(path)(handler)) def findFileWithName(name: String) = fromFirstRepo(_.findFileWithName(name)) }
nelsonblaha/playframework
documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaErrorHandling.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package javaguide.http import play.api.mvc.Action import play.api.test._ import scala.reflect.ClassTag object JavaErrorHandling extends PlaySpecification with WsTestClient { def fakeApp[A](implicit ct: ClassTag[A]) = { FakeApplication( additionalConfiguration = Map("play.http.errorHandler" -> ct.runtimeClass.getName), withRoutes = { case (_, "/error") => Action(_ => throw new RuntimeException("foo")) } ) } "java error handling" should { "allow providing a custom error handler" in new WithServer(fakeApp[root.ErrorHandler]) { await(wsUrl("/error").get()).body must startWith("A server error occurred: ") } "allow providing a custom error handler" in new WithServer(fakeApp[`def`.ErrorHandler]) { await(wsUrl("/error").get()).body must not startWith("A server error occurred: ") } } }
nelsonblaha/playframework
framework/src/play/src/main/scala/play/api/libs/concurrent/Promise.scala
<filename>framework/src/play/src/main/scala/play/api/libs/concurrent/Promise.scala<gh_stars>1-10 /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api.libs.concurrent import scala.language.higherKinds import play.core._ import play.api._ import scala.concurrent.duration.{ FiniteDuration, Duration } import java.util.concurrent.{ TimeUnit } import scala.concurrent.{ Future, ExecutionContext, Promise => SPromise } import scala.collection.mutable.Builder import scala.collection._ import scala.collection.generic.CanBuildFrom import play.core.Execution.internalContext import scala.util.Try import scala.util.control.NonFatal /** * useful helper methods to create and compose Promises */ object Promise { /** * Constructs a Future which will contain value "message" after the given duration elapses. * This is useful only when used in conjunction with other Promises * @param message message to be displayed * @param duration duration for the scheduled promise * @return a scheduled promise */ @deprecated("Use akka.pattern.after(duration, actorSystem.scheduler)(Future(message)) instead", since = "2.5.0") def timeout[A](message: => A, duration: scala.concurrent.duration.Duration)(implicit ec: ExecutionContext): Future[A] = { timeout(message, duration.toMillis) } /** * Constructs a Future which will contain value "message" after the given duration elapses. * This is useful only when used in conjunction with other Promises * @param message message to be displayed * @param duration duration for the scheduled promise * @return a scheduled promise */ @deprecated("Use akka.pattern.after(duration, actorSystem.scheduler)(Future(message)) instead", since = "2.5.0") def timeout[A](message: => A, duration: Long, unit: TimeUnit = TimeUnit.MILLISECONDS)(implicit ec: ExecutionContext): Future[A] = { val p = SPromise[A]() import play.api.Play.current Akka.system.scheduler.scheduleOnce(FiniteDuration(duration, unit)) { p.complete(Try(message)) } p.future } }
nelsonblaha/playframework
framework/src/play-server/src/main/scala/play/core/server/ServerConfig.scala
<gh_stars>1-10 /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.core.server import com.typesafe.config._ import java.io.File import java.util.Properties import play.api.{ Configuration, Mode } /** * Common configuration for servers such as NettyServer. * * @param rootDir The root directory of the server. Used to find default locations of * files, log directories, etc. * @param port The HTTP port to use. * @param sslPort The HTTPS port to use. * @param address The socket address to bind to. * @param mode The run mode: dev, test or prod. * @param configuration: The configuration to use for loading the server. This is not * the same as application configuration. This configuration is usually loaded from a * server.conf file, whereas the application configuration is usually loaded from an * application.conf file. */ case class ServerConfig( rootDir: File, port: Option[Int], sslPort: Option[Int], address: String, mode: Mode.Mode, properties: Properties, configuration: Configuration) { // Some basic validation of config if (!port.isDefined && !sslPort.isDefined) throw new IllegalArgumentException("Must provide either an HTTP port or an HTTPS port") } object ServerConfig { def apply( classLoader: ClassLoader = this.getClass.getClassLoader, rootDir: File = new File("."), port: Option[Int] = Some(9000), sslPort: Option[Int] = None, address: String = "0.0.0.0", mode: Mode.Mode = Mode.Prod, properties: Properties = System.getProperties): ServerConfig = { ServerConfig( rootDir = rootDir, port = port, sslPort = sslPort, address = address, mode = mode, properties = properties, configuration = Configuration.load(classLoader, properties, rootDirConfig(rootDir), mode == Mode.Test) ) } /** * Gets the configuration for the given root directory. Used to construct * the server Configuration. */ def rootDirConfig(rootDir: File): Map[String, String] = Map("play.server.dir" -> rootDir.getAbsolutePath) }
nelsonblaha/playframework
framework/src/play/src/main/scala/play/api/LoggerConfigurator.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api import java.io.File import java.net.URL import java.util.Properties import play.api.Mode.Mode /** * Runs through underlying logger configuration. */ trait LoggerConfigurator { /** * Initialize the Logger when there's no application ClassLoader available. */ def init(rootPath: java.io.File, mode: Mode.Mode): Unit /** * Reconfigures the underlying logger infrastructure. */ def configure(env: Environment): Unit /** * Reconfigures the underlying loggerinfrastructure. */ def configure(properties: Map[String, String], config: Option[URL]): Unit /** * Shutdown the logger infrastructure. */ def shutdown() } object LoggerConfigurator { def apply(classLoader: ClassLoader): Option[LoggerConfigurator] = { findFromResources(classLoader).flatMap { className => apply(className, this.getClass.getClassLoader) } } def apply(loggerConfiguratorClassName: String, classLoader: ClassLoader): Option[LoggerConfigurator] = { try { val loggerConfiguratorClass: Class[_] = classLoader.loadClass(loggerConfiguratorClassName) Some(loggerConfiguratorClass.newInstance().asInstanceOf[LoggerConfigurator]) } catch { case ex: Exception => val msg = s""" |Play cannot load "$loggerConfiguratorClassName". Please make sure you have logback (or another module |that implements play.api.LoggerConfigurator) in your classpath. """.stripMargin System.err.println(msg) ex.printStackTrace() None } } private def findFromResources(classLoader: ClassLoader): Option[String] = { val in = classLoader.getResourceAsStream("logger-configurator.properties") if (in != null) { try { val props = new Properties() props.load(in) Option(props.getProperty("play.logger.configurator")) } catch { case ex: Exception => ex.printStackTrace() None } finally { in.close() } } else { None } } }
nelsonblaha/playframework
documentation/manual/working/scalaGuide/advanced/dependencyinjection/code/injected.sbt
//#content routesGenerator := InjectedRoutesGenerator //#content
nelsonblaha/playframework
framework/src/play/src/main/scala/play/core/j/JavaResults.scala
<filename>framework/src/play/src/main/scala/play/core/j/JavaResults.scala /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.core.j import akka.stream.Materializer import akka.stream.scaladsl.Source import akka.util.ByteString import play.api.libs.streams.Streams import scala.annotation.varargs import scala.compat.java8.FutureConverters import scala.language.reflectiveCalls import play.api.mvc._ import play.api.http._ import play.api.libs.iteratee._ import play.api.libs.iteratee.Concurrent._ import play.core.Execution.internalContext import play.mvc.Http.{ Cookies => JCookies, Cookie => JCookie, Session => JSession, Flash => JFlash } import play.mvc.{ Result => JResult } import play.twirl.api.Content import scala.collection.JavaConverters._ import scala.concurrent.Await import scala.concurrent.duration._ import java.util.function.Consumer /** * Java compatible Results */ object JavaResults extends Results with DefaultWriteables with DefaultContentTypeOfs { def writeContent(mimeType: String)(implicit codec: Codec): Writeable[Content] = Writeable((content: Content) => codec.encode(contentBody(content)), Some(ContentTypes.withCharset(mimeType))) def contentBody(content: Content): String = content match { case xml: play.twirl.api.Xml => xml.body.trim; case c => c.body } def writeString(mimeType: String)(implicit codec: Codec): Writeable[String] = Writeable((s: String) => codec.encode(s), Some(ContentTypes.withCharset(mimeType))) def writeString(implicit codec: Codec): Writeable[String] = writeString(MimeTypes.TEXT) def writeBytes: Writeable[Array[Byte]] = Writeable.wByteArray def writeBytes(contentType: String): Writeable[ByteString] = Writeable((bs: ByteString) => bs)(contentTypeOfBytes(contentType)) def writeEmptyContent: Writeable[Results.EmptyContent] = writeableOf_EmptyContent def contentTypeOfBytes(mimeType: String): ContentTypeOf[ByteString] = ContentTypeOf(Option(mimeType).orElse(Some("application/octet-stream"))) def emptyHeaders = Map.empty[String, String] def empty = Results.EmptyContent() def chunked[A](onConnected: Consumer[Channel[A]], onDisconnected: Runnable): Enumerator[A] = { Concurrent.unicast[A]( onStart = (channel: Channel[A]) => onConnected.accept(channel), onComplete = onDisconnected.run(), onError = (_: String, _: Input[A]) => onDisconnected.run() )(internalContext) } //play.api.libs.iteratee.Enumerator.imperative[A](onComplete = onDisconnected) def chunked(stream: java.io.InputStream, chunkSize: Int): Source[ByteString, _] = enumToSource(Enumerator.fromStream(stream, chunkSize)(internalContext)) def chunked(file: java.io.File, chunkSize: Int) = enumToSource(Enumerator.fromFile(file, chunkSize)(internalContext)) def chunked(file: java.nio.file.Path, chunkSize: Int) = enumToSource(Enumerator.fromPath(file, chunkSize)(internalContext)) def sendFile(status: play.api.mvc.Results.Status, file: java.io.File, inline: Boolean, filename: String) = status.sendFile(file, inline, _ => filename) def sendPath(status: play.api.mvc.Results.Status, path: java.nio.file.Path, inline: Boolean, filename: String) = status.sendPath(path, inline, _ => filename) private def enumToSource(enumerator: Enumerator[Array[Byte]]): Source[ByteString, _] = Source(Streams.enumeratorToPublisher(enumerator)).map(ByteString.apply) } object JavaResultExtractor { def getCookies(responseHeader: ResponseHeader): JCookies = new JCookies { private val cookies = Cookies.fromSetCookieHeader(responseHeader.headers.get(HeaderNames.SET_COOKIE)) def get(name: String): JCookie = { cookies.get(name).map(makeJavaCookie).orNull } private def makeJavaCookie(cookie: Cookie): JCookie = { new JCookie(cookie.name, cookie.value, cookie.maxAge.map(i => new Integer(i)).orNull, cookie.path, cookie.domain.orNull, cookie.secure, cookie.httpOnly) } def iterator: java.util.Iterator[JCookie] = { cookies.toIterator.map(makeJavaCookie).asJava } } def getSession(responseHeader: ResponseHeader): JSession = new JSession(Session.decodeFromCookie( Cookies.fromSetCookieHeader(responseHeader.headers.get(HeaderNames.SET_COOKIE)).get(Session.COOKIE_NAME) ).data.asJava) def getFlash(responseHeader: ResponseHeader): JFlash = new JFlash(Flash.decodeFromCookie( Cookies.fromSetCookieHeader(responseHeader.headers.get(HeaderNames.SET_COOKIE)).get(Flash.COOKIE_NAME) ).data.asJava) def withHeader(responseHeader: ResponseHeader, name: String, value: String): ResponseHeader = responseHeader.copy(headers = responseHeader.headers + (name -> value)) @varargs def withHeader(responseHeader: ResponseHeader, nameValues: String*): ResponseHeader = { if (nameValues.length % 2 != 0) { throw new IllegalArgumentException("Unmatched name - withHeaders must be invoked with an even number of string arguments") } val toAdd = nameValues.grouped(2).map(pair => pair(0) -> pair(1)) responseHeader.copy(headers = responseHeader.headers ++ toAdd) } def getBody(result: JResult, timeout: Long, materializer: Materializer): ByteString = Await.result(FutureConverters.toScala(result.body.consumeData(materializer)), timeout.millis) }
nelsonblaha/playframework
framework/src/play-server/src/test/scala/play/core/server/common/NodeIdentifierParserSpec.scala
package play.core.server.common import java.net.InetAddress.getByName import org.specs2.mutable.Specification import play.core.server.common.NodeIdentifierParser._ class NodeIdentifierParserSpec extends Specification { "NodeIdentifierParser" should { "parse an ip v6 address with port" in { parseNode("[8fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b]:9000").right.get mustEqual Ip(getByName("fc00:db20:35b:7399::5")) -> Some(PortNumber(9000)) } "parse an ip v6 address with obfuscated port" in { parseNode("[::FF]:_obf").right.get mustEqual Ip(getByName("::FF")) -> Some(ObfuscatedPort("_obf")) } "parse an ip v4 address with port" in { parseNode("127.0.0.1:8080").right.get mustEqual Ip(getByName("127.0.0.1")) -> Some(PortNumber(8080)) } "parse an ip v4 address without port" in { parseNode("192.168.0.1").right.get mustEqual Ip(getByName("192.168.0.1")) -> None } "parse an unknown ip address without port" in { parseNode("unknown").right.get mustEqual UnknownIp -> None } "parse an obfuscated ip address without port" in { parseNode("_harry").right.get mustEqual ObfuscatedIp("_harry") -> None } } }
nelsonblaha/playframework
framework/src/sbt-plugin/src/sbt-test/routes-compiler-plugin/aggregate-reverse-routes/a/app/controllers/a/A.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package controllers.a import play.api.mvc._ class A extends Controller { def index = Action { controllers.a.routes.A.index controllers.b.routes.B.index controllers.c.routes.C.index Ok } }
nelsonblaha/playframework
framework/version.sbt
version in ThisBuild := "2.5.0-SNAPSHOT"
nelsonblaha/playframework
framework/src/play-netty-server/src/main/scala/play/core/server/netty/WebSocketHandler.scala
<filename>framework/src/play-netty-server/src/main/scala/play/core/server/netty/WebSocketHandler.scala /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.core.server.netty import akka.stream.scaladsl.Flow import akka.stream.stage.{ Stage, PushStage, Context } import akka.util.ByteString import io.netty.buffer.{ Unpooled, ByteBuf, ByteBufHolder } import io.netty.handler.codec.http.websocketx._ import io.netty.util.ReferenceCountUtil import play.api.http.websocket.Message import play.api.libs.streams.AkkaStreams import play.core.server.common.WebSocketFlowHandler import play.api.http.websocket._ private[server] object WebSocketHandler { /** * Convert a flow of messages to a flow of frame events. * * This implements the WebSocket control logic, including handling ping frames and closing the connection in a spec * compliant manner. */ def messageFlowToFrameFlow(flow: Flow[Message, Message, _], bufferLimit: Int): Flow[WebSocketFrame, WebSocketFrame, _] = { // Each of the stages here transforms frames to an Either[Message, ?], where Message is a close message indicating // some sort of protocol failure. The handleProtocolFailures function then ensures that these messages skip the // flow that we are wrapping, are sent to the client and the close procedure is implemented. Flow[WebSocketFrame] .transform(() => framesToMessages(bufferLimit)) .via(handleProtocolFailures(WebSocketFlowHandler.webSocketProtocol(flow))) .map(messageToFrame) } /** * The WebSocket protocol allows messages to be fragmented across multiple frames. * * This stage aggregates them so each frame is a full message. * * @param bufferLimit The maximum size of frame data that should be buffered. */ private def framesToMessages(bufferLimit: Int): Stage[WebSocketFrame, Either[Message, Message]] = { new PushStage[WebSocketFrame, Either[Message, Message]] { var currentMessageData: ByteString = null var currentMessageHeader: WebSocketFrame = null def toMessage(frame: WebSocketFrame, data: ByteString) = frame match { case _: TextWebSocketFrame => TextMessage(data.utf8String) case _: BinaryWebSocketFrame => BinaryMessage(data) case close: CloseWebSocketFrame => CloseMessage(Some(close.statusCode()), close.reasonText()) case _: PingWebSocketFrame => PingMessage(data) case _: PongWebSocketFrame => PongMessage(data) } def toByteString(data: ByteBufHolder) = { val builder = ByteString.newBuilder data.content().readBytes(builder.asOutputStream, data.content().readableBytes()) val bytes = builder.result() bytes } def onPush(elem: WebSocketFrame, ctx: Context[Either[Message, Message]]) = { val directive = elem match { case _: ContinuationWebSocketFrame if currentMessageHeader == null => ctx.push(close(CloseCodes.ProtocolError, "Unexpected continuation frame")) case cont: ContinuationWebSocketFrame if currentMessageData.size + cont.content().readableBytes() > bufferLimit => ctx.push(close(CloseCodes.TooBig)) case cont: ContinuationWebSocketFrame if cont.isFinalFragment => val message = toMessage(currentMessageHeader, currentMessageData ++ toByteString(cont)) currentMessageHeader = null currentMessageData = null ctx.push(Right(message)) case cont: ContinuationWebSocketFrame => currentMessageData ++= toByteString(cont) ctx.pull() case _ if currentMessageData != null => ctx.push(close(CloseCodes.ProtocolError, "Received non continuation frame when previous message wasn't finished")) case full if full.isFinalFragment => ctx.push(Right(toMessage(full, toByteString(full)))) case start => currentMessageHeader = start currentMessageData = toByteString(start) ctx.pull() } ReferenceCountUtil.release(elem) directive } } } /** * Converts Play messages to Netty frames. */ private def messageToFrame(message: Message): WebSocketFrame = { def byteStringToByteBuf(bytes: ByteString): ByteBuf = { if (bytes.isEmpty) { Unpooled.EMPTY_BUFFER } else { Unpooled.wrappedBuffer(bytes.asByteBuffer) } } message match { case TextMessage(data) => new TextWebSocketFrame(data) case BinaryMessage(data) => new BinaryWebSocketFrame(byteStringToByteBuf(data)) case PingMessage(data) => new PingWebSocketFrame(byteStringToByteBuf(data)) case PongMessage(data) => new PongWebSocketFrame(byteStringToByteBuf(data)) case CloseMessage(Some(statusCode), reason) => new CloseWebSocketFrame(statusCode, reason) case CloseMessage(None, _) => new CloseWebSocketFrame() } } /** * Handles the protocol failures by gracefully closing the connection. */ private def handleProtocolFailures: Flow[Message, Message, _] => Flow[Either[Message, Message], Message, _] = { AkkaStreams.bypassWith(Flow[Either[Message, Message]].transform(() => new PushStage[Either[Message, Message], Either[Message, Message]] { var closing = false def onPush(elem: Either[Message, Message], ctx: Context[Either[Message, Message]]) = elem match { case _ if closing => ctx.finish() case Right(message) => ctx.push(Left(message)) case Left(close) => closing = true ctx.push(Right(close)) } }), AkkaStreams.EagerFinishMerge(2)) } private def close(status: Int, message: String = "") = { Left(new CloseMessage(Some(status), message)) } }
nelsonblaha/playframework
framework/src/play-filters-helpers/src/main/scala/play/filters/gzip/Gzip.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.filters.gzip import play.api.libs.iteratee._ import play.api.libs.iteratee.Enumeratee.CheckDone import java.util.zip._ import play.api.libs.concurrent.Execution.Implicits._ /** * Enumeratees for dealing with gzip streams */ object Gzip { private type Bytes = Array[Byte] private type CheckDoneBytes = CheckDone[Bytes, Bytes] private val GzipMagic = 0x8b1f // Gzip flags private val HeaderCrc = 2 private val ExtraField = 4 private val FileName = 8 private val FileComment = 16 /** * Create a gzip enumeratee. * * This enumeratee is not purely functional, it uses the high performance native deflate implementation provided by * Java, which is stateful. However, this state is created each time the enumeratee is applied, so it is fine to * reuse the enumeratee returned by this function. * * @param bufferSize The size of the output buffer */ def gzip(bufferSize: Int = 512): Enumeratee[Array[Byte], Array[Byte]] = { /* * State consists of 4 parts, a deflater (high performance native zlib implementation), a crc32 calculator, required * by gzip to be at the end of the stream, a buffer in which we accumulate the compressed bytes, and the current * position of that buffer. */ class State { val deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true) val crc = new CRC32 @volatile var buffer = new Bytes(bufferSize) @volatile var pos = 0 def reset() { pos = 0 buffer = new Bytes(bufferSize) } } new CheckDoneBytes { def step[A](state: State, k: K[Bytes, A]): K[Bytes, Iteratee[Bytes, A]] = { case Input.EOF => { state.deflater.finish() deflateUntilFinished(state, k) } case Input.El(bytes) => { state.crc.update(bytes) state.deflater.setInput(bytes) deflateUntilNeedsInput(state, k) } case in @ Input.Empty => feedEmpty(state, k) } def continue[A](k: K[Bytes, A]) = { feedHeader(k).pureFlatFold { case Step.Cont(k2) => Cont(step(new State, k2)) case step => Done(step.it, Input.Empty) } } def deflateUntilNeedsInput[A](state: State, k: K[Bytes, A]): Iteratee[Bytes, Iteratee[Bytes, A]] = { // Deflate some bytes val numBytes = state.deflater.deflate(state.buffer, state.pos, bufferSize - state.pos) if (numBytes == 0) { if (state.deflater.needsInput()) { // Deflater needs more input, so continue Cont(step(state, k)) } else { deflateUntilNeedsInput(state, k) } } else { state.pos += numBytes if (state.pos < bufferSize) { deflateUntilNeedsInput(state, k) } else { // We've filled our buffer, feed it into the k function val buffer = state.buffer state.reset() new CheckDoneBytes { def continue[B](k: K[Bytes, B]) = deflateUntilNeedsInput(state, k) } &> k(Input.El(buffer)) } } } def deflateUntilFinished[A](state: State, k: K[Bytes, A]): Iteratee[Bytes, Iteratee[Bytes, A]] = { val numBytes = state.deflater.deflate(state.buffer, state.pos, bufferSize - state.pos) if (numBytes == 0) { if (state.deflater.finished()) { // Deflater is finished, send the trailer feedTrailer(state, k) } else { deflateUntilFinished(state, k) } } else { state.pos += numBytes if (state.pos < bufferSize) { deflateUntilFinished(state, k) } else { val buffer = state.buffer state.reset() new CheckDoneBytes { def continue[B](k: K[Bytes, B]) = deflateUntilFinished(state, k) } &> k(Input.El(buffer)) } } } def feedEmpty[A](state: State, k: K[Bytes, A]) = new CheckDoneBytes { def continue[B](k: K[Bytes, B]) = Cont(step(state, k)) } &> k(Input.Empty) def feedHeader[A](k: K[Bytes, A]) = { // First need to write the Gzip header val zero = 0.asInstanceOf[Byte] val header = Array( GzipMagic.asInstanceOf[Byte], // Magic number (2 bytes) (GzipMagic >> 8).asInstanceOf[Byte], Deflater.DEFLATED.asInstanceOf[Byte], // Compression method zero, // Flags zero, // Modification time (4 bytes) zero, zero, zero, zero, // Extra flags zero // Operating system ) k(Input.El(header)) } def feedTrailer[A](state: State, k: K[Bytes, A]): Iteratee[Bytes, Iteratee[Bytes, A]] = { def writeTrailer(buffer: Bytes, pos: Int) { val crc = state.crc.getValue val length = state.deflater.getTotalIn state.deflater.end() // CRC followed by length, little endian intToLittleEndian(crc.asInstanceOf[Int], buffer, pos) intToLittleEndian(length, buffer, pos + 4) } // Try to just append to the existing buffer if there's enough room val finalIn = if (state.pos + 8 <= bufferSize) { writeTrailer(state.buffer, state.pos) state.pos = state.pos + 8 val buffer = if (state.pos == bufferSize) state.buffer else state.buffer.take(state.pos) Seq(buffer) } else { // Create a new buffer for the trailer val buffer = if (state.pos == bufferSize) state.buffer else state.buffer.take(state.pos) val trailer = new Bytes(8) writeTrailer(trailer, 0) Seq(buffer, trailer) } Iteratee.flatten(Enumerator.enumerate(finalIn) >>> Enumerator.eof |>> Cont(k)).map(it => Done(it, Input.EOF)) } } } /** * Create a gunzip enumeratee. * * This enumeratee is not purely functional, it uses the high performance native deflate implementation provided by * Java, which is stateful. However, this state is created each time the enumeratee is applied, so it is fine to * reuse the enumeratee returned by this function. * * @param bufferSize The size of the output buffer */ def gunzip(bufferSize: Int = 512): Enumeratee[Array[Byte], Array[Byte]] = { /* * State consists of 4 parts, an inflater (high performance native zlib implementation), a crc32 calculator, required * by gzip to be at the end of the stream, a buffer in which we accumulate the compressed bytes, and the current * position of that buffer. */ class State { val inflater = new Inflater(true) val crc = new CRC32 @volatile var buffer = new Bytes(bufferSize) @volatile var pos = 0 def reset() { pos = 0 buffer = new Bytes(bufferSize) } } case class Header(magic: Short, compressionMethod: Byte, flags: Byte) { def hasCrc = (flags & HeaderCrc) == HeaderCrc def hasExtraField = (flags & ExtraField) == ExtraField def hasFilename = (flags & FileName) == FileName def hasComment = (flags & FileComment) == FileComment } new CheckDoneBytes { def step[A](state: State, k: K[Bytes, A]): K[Bytes, Iteratee[Bytes, A]] = { case Input.EOF => { Error("Premature end of gzip stream", Input.EOF) } case Input.El(bytes) => { state.inflater.setInput(bytes) inflateUntilNeedsInput(state, k, bytes) } case in @ Input.Empty => feedEmpty(state, k) } def continue[A](k: K[Bytes, A]) = { for { state <- readHeader step <- Cont(step(state, k)) } yield step } def maybeEmpty(bytes: Bytes) = if (bytes.isEmpty) Input.Empty else Input.El(bytes) def inflateUntilNeedsInput[A](state: State, k: K[Bytes, A], input: Bytes): Iteratee[Bytes, Iteratee[Bytes, A]] = { // Inflate some bytes val numBytes = state.inflater.inflate(state.buffer, state.pos, bufferSize - state.pos) if (numBytes == 0) { if (state.inflater.finished()) { // Feed the current buffer val buffer = if (state.buffer.length > state.pos) { state.buffer.take(state.pos) } else { state.buffer } state.crc.update(buffer) new CheckDoneBytes { def continue[B](k: K[Bytes, B]) = finish(state, k, input) } &> k(Input.El(buffer)) } else if (state.inflater.needsInput()) { // Inflater needs more input, so continue Cont(step(state, k)) } else { inflateUntilNeedsInput(state, k, input) } } else { state.pos += numBytes if (state.pos < bufferSize) { inflateUntilNeedsInput(state, k, input) } else { // We've filled our buffer, feed it into the k function val buffer = state.buffer state.crc.update(buffer) state.reset() new CheckDoneBytes { def continue[B](k: K[Bytes, B]) = inflateUntilNeedsInput(state, k, input) } &> k(Input.El(buffer)) } } } def feedEmpty[A](state: State, k: K[Bytes, A]) = new CheckDoneBytes { def continue[B](k: K[Bytes, B]) = Cont(step(state, k)) } &> k(Input.Empty) def done[A](a: A = Unit): Iteratee[Bytes, A] = Done[Bytes, A](a) def finish[A](state: State, k: K[Bytes, A], input: Bytes): Iteratee[Bytes, Iteratee[Bytes, A]] = { // Get the left over bytes from the inflater val leftOver = if (input.length > state.inflater.getRemaining) { Done(Unit, Input.El(input.takeRight(state.inflater.getRemaining))) } else { done() } // Read the trailer, before sending an EOF for { _ <- leftOver _ <- readTrailer(state) done <- Done(k(Input.EOF), Input.EOF) } yield done } def readHeader: Iteratee[Bytes, State] = { // Parse header val crc = new CRC32 for { headerBytes <- take(10, "Not enough bytes for gzip file", crc) header <- done(Header(littleEndianToShort(headerBytes), headerBytes(2), headerBytes(3))) _ <- if (header.magic != GzipMagic.asInstanceOf[Short]) Error("Not a gzip file, found header" + headerBytes.take(2).map(b => "%02X".format(b)).mkString("(", ", ", ")"), Input.El(headerBytes)) else done() _ <- if (header.compressionMethod != Deflater.DEFLATED) Error("Unsupported compression method", Input.El(headerBytes)) else done() efLength <- if (header.hasExtraField) readShort(crc) else done(0) _ <- if (header.hasExtraField) drop(efLength, "Not enough bytes for extra field", crc) else done() _ <- if (header.hasFilename) dropWhileIncluding(_ != 0x00, "EOF found in middle of file name", crc) else done() _ <- if (header.hasComment) dropWhileIncluding(_ != 0x00, "EOF found in middle of comment", crc) else done() headerCrc <- if (header.hasCrc) readShort(new CRC32) else done(0) _ <- if (header.hasCrc && (crc.getValue & 0xffff) != headerCrc) Error[Bytes]("Header CRC failed", Input.Empty) else done() } yield new State() } /** * Read and validate the trailer. Returns a done iteratee if the trailer is valid, or error if not. */ def readTrailer(state: State): Iteratee[Bytes, Unit] = { val dummy = new CRC32 for { crc <- readInt("Premature EOF before gzip CRC", dummy) _ <- if (crc != state.crc.getValue.asInstanceOf[Int]) Error("CRC failed, was %X, expected %X".format(state.crc.getValue.asInstanceOf[Int], crc), Input.El(intToLittleEndian(crc))) else done() length <- readInt("Premature EOF before gzip total length", dummy) _ <- if (length != state.inflater.getTotalOut) Error("Length check failed", Input.El(intToLittleEndian(length))) else done() } yield { state.inflater.end() done() } } def readShort(crc: CRC32): Iteratee[Bytes, Int] = for { bytes <- take(2, "Not enough bytes for extra field length", crc) } yield { littleEndianToShort(bytes) } def readInt(error: String, crc: CRC32): Iteratee[Bytes, Int] = for { bytes <- take(4, error, crc) } yield { littleEndianToInt(bytes) } def take(n: Int, error: String, crc: CRC32, bytes: Bytes = new Bytes(0)): Iteratee[Bytes, Bytes] = Cont { case Input.EOF => Error(error, Input.EOF) case Input.Empty => take(n, error, crc, bytes) case Input.El(b) => { val splitted = b.splitAt(n) crc.update(splitted._1) splitted match { case (needed, left) if needed.length == n => Done(bytes ++ needed, maybeEmpty(left)) case (partial, _) => take(n - partial.length, error, crc, bytes ++ partial) } } } def drop(n: Int, error: String, crc: CRC32): Iteratee[Bytes, Unit] = Cont { case Input.EOF => Error(error, Input.EOF) case Input.Empty => drop(n, error, crc) case Input.El(b) => if (b.length >= n) { val splitted = b.splitAt(n) crc.update(splitted._1) Done(Unit, maybeEmpty(splitted._2)) } else { crc.update(b) drop(b.length - n, error, crc) } } def dropWhileIncluding(p: Byte => Boolean, error: String, crc: CRC32): Iteratee[Bytes, Unit] = Cont { case Input.EOF => Error(error, Input.EOF) case Input.Empty => dropWhileIncluding(p, error, crc) case Input.El(b) => val left = b.dropWhile(p) crc.update(b, 0, b.length - left.length) left match { case none if none.isEmpty => dropWhileIncluding(p, error, crc) case some => Done(Unit, maybeEmpty(some.drop(1))) } } } } private def intToLittleEndian(i: Int, out: Bytes = new Bytes(4), offset: Int = 0): Bytes = { out(offset) = (i & 0xff).asInstanceOf[Byte] out(offset + 1) = (i >> 8 & 0xff).asInstanceOf[Byte] out(offset + 2) = (i >> 16 & 0xff).asInstanceOf[Byte] out(offset + 3) = (i >> 24 & 0xff).asInstanceOf[Byte] out } private def littleEndianToShort(bytes: Bytes, offset: Int = 0): Short = { ((bytes(offset + 1) & 0xff) << 8 | bytes(offset) & 0xff).asInstanceOf[Short] } private def littleEndianToInt(bytes: Bytes, offset: Int = 0): Int = { (bytes(offset + 3) & 0xff) << 24 | (bytes(offset + 2) & 0xff) << 16 | (bytes(offset + 1) & 0xff) << 8 | (bytes(offset) & 0xff) } }
nelsonblaha/playframework
templates/play-java/project/plugins.sbt
// The Play plugin addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "%PLAY_VERSION%") // Web plugins addSbtPlugin("com.typesafe.sbt" % "sbt-coffeescript" % "%COFFEESCRIPT_VERSION%") addSbtPlugin("com.typesafe.sbt" % "sbt-less" % "%LESS_VERSION%") addSbtPlugin("com.typesafe.sbt" % "sbt-jshint" % "%JSHINT_VERSION%") addSbtPlugin("com.typesafe.sbt" % "sbt-rjs" % "%RJS_VERSION%") addSbtPlugin("com.typesafe.sbt" % "sbt-digest" % "%DIGEST_VERSION%") addSbtPlugin("com.typesafe.sbt" % "sbt-mocha" % "%MOCHA_VERSION%") // Play enhancer - this automatically generates getters/setters for public fields // and rewrites accessors of these fields to use the getters/setters. Remove this // plugin if you prefer not to have this feature, or disable on a per project // basis using disablePlugins(PlayEnhancer) in your build.sbt addSbtPlugin("com.typesafe.sbt" % "sbt-play-enhancer" % "%ENHANCER_VERSION%") // Play Ebean support, to enable, uncomment this line, and enable in your build.sbt using // enablePlugins(PlayEbean). // addSbtPlugin("com.typesafe.sbt" % "sbt-play-ebean" % "%EBEAN_VERSION%")
nelsonblaha/playframework
framework/src/play/src/test/scala/play/api/mvc/BindersSpec.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api.mvc import java.util.UUID import org.specs2.mutable._ object BindersSpec extends Specification { val uuid = UUID.randomUUID "UUID path binder" should { val subject = implicitly[PathBindable[UUID]] "Unbind UUID as string" in { subject.unbind("key", uuid) must be_==(uuid.toString) } "Bind parameter to UUID" in { subject.bind("key", uuid.toString) must be_==(Right(uuid)) } "Fail on unparseable UUID" in { subject.bind("key", "bad-uuid") must be_==(Left("Cannot parse parameter key as UUID: Invalid UUID string: bad-uuid")) } } "UUID query string binder" should { val subject = implicitly[QueryStringBindable[UUID]] "Unbind UUID as string" in { subject.unbind("key", uuid) must be_==("key=" + uuid.toString) } "Bind parameter to UUID" in { subject.bind("key", Map("key" -> Seq(uuid.toString))) must be_==(Some(Right(uuid))) } "Fail on unparseable UUID" in { subject.bind("key", Map("key" -> Seq("bad-uuid"))) must be_==(Some(Left("Cannot parse parameter key as UUID: Invalid UUID string: bad-uuid"))) } } "URL Path string binder" should { val subject = implicitly[PathBindable[String]] val pathString = "/path/to/some%20file" val pathStringBinded = "/path/to/some file" "Unbind Path string as string" in { subject.unbind("key", pathString) must equalTo(pathString) } "Bind Path string as string without any decoding" in { subject.bind("key", pathString) must equalTo(Right(pathString)) } } "QueryStringBindable.bindableString" should { "unbind with null values" in { import QueryStringBindable._ val boundValue = bindableString.unbind("key", null) boundValue must beEqualTo("key=") } } "QueryStringBindable.bindableSeq" should { val seqBinder = implicitly[QueryStringBindable[Seq[String]]] val values = Seq("i", "once", "knew", "a", "man", "from", "nantucket") val params = Map("q" -> values) "propagate errors that occur during bind" in { implicit val brokenBinder: QueryStringBindable[String] = { new QueryStringBindable.Parsing[String]( { x => if (x == "i" || x == "nantucket") x else sys.error(s"failed: ${x}") }, identity, (key, ex) => s"failed to parse ${key}: ${ex.getMessage}" ) } val brokenSeqBinder = implicitly[QueryStringBindable[Seq[String]]] val err = s"""failed to parse q: failed: once |failed to parse q: failed: knew |failed to parse q: failed: a |failed to parse q: failed: man |failed to parse q: failed: from""".stripMargin brokenSeqBinder.bind("q", params) must equalTo(Some(Left(err))) } "preserve the order of bound parameters" in { seqBinder.bind("q", params) must equalTo(Some(Right(values))) } "return the empty list when the key is not found" in { seqBinder.bind("q", Map.empty) must equalTo(Some(Right(Nil))) } } "URL QueryStringBindable Char" should { val subject = implicitly[QueryStringBindable[Char]] val char = 'X' val string = "X" "Unbind query string char as string" in { subject.unbind("key", char) must equalTo("key=" + char.toString) } "Bind query string as char" in { subject.bind("key", Map("key" -> Seq(string))) must equalTo(Some(Right(char))) } "Fail on length > 1" in { subject.bind("key", Map("key" -> Seq("foo"))) must be_==(Some(Left("Cannot parse parameter key with value 'foo' as Char: key must be exactly one digit in length."))) } "Fail on empty" in { subject.bind("key", Map("key" -> Seq(""))) must be_==(Some(Left("Cannot parse parameter key with value '' as Char: key must be exactly one digit in length."))) } } "URL PathBindable Char" should { val subject = implicitly[PathBindable[Char]] val char = 'X' val string = "X" "Unbind Path char as string" in { subject.unbind("key", char) must equalTo(char.toString) } "Bind Path string as char" in { subject.bind("key", string) must equalTo(Right(char)) } "Fail on length > 1" in { subject.bind("key", "foo") must be_==(Left("Cannot parse parameter key with value 'foo' as Char: key must be exactly one digit in length.")) } "Fail on empty" in { subject.bind("key", "") must be_==(Left("Cannot parse parameter key with value '' as Char: key must be exactly one digit in length.")) } } }
nelsonblaha/playframework
framework/src/play-streams/src/test/scala/play/api/libs/streams/impl/SubscriberIterateeSpec.scala
package play.api.libs.streams.impl import org.specs2.mutable.Specification import org.specs2.specification.Scope import play.api.libs.iteratee.{ Step, Iteratee, Enumerator } import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent._ import scala.concurrent.duration._ object SubscriberIterateeSpec extends Specification { import SubscriberEvents._ def await[T](f: Future[T]) = Await.result(f, 5.seconds) trait TestEnv extends EventRecorder with SubscriberEvents with Scope { val iteratee = new SubscriberIteratee(subscriber) } "a subscriber iteratee" should { "not subscribe until fold is invoked" in new TestEnv { isEmptyAfterDelay() must beTrue } "not consume anything from the enumerator while there is no demand" in new TestEnv { iteratee.fold { folder => // Record if the folder was invoked record(folder) Future.successful(()) } next() must beAnInstanceOf[OnSubscribe] isEmptyAfterDelay() must beTrue } "not enter cont state until demand is requested" in new TestEnv { val step = iteratee.unflatten next() must beLike { case OnSubscribe(sub) => isEmptyAfterDelay() must beTrue step.isCompleted must beFalse sub.request(1) await(step) must beAnInstanceOf[Step.Cont[_, _]] } } "publish events one at a time in response to demand" in new TestEnv { val result = Enumerator(10, 20, 30) |>>> iteratee next() must beLike { case OnSubscribe(sub) => isEmptyAfterDelay() must beTrue sub.request(1) next() must_== OnNext(10) isEmptyAfterDelay() must beTrue sub.request(1) next() must_== OnNext(20) isEmptyAfterDelay() must beTrue sub.request(1) next() must_== OnNext(30) isEmptyAfterDelay() must beTrue sub.request(1) next() must_== OnComplete } await(result) must_== () } "publish events in batches in response to demand" in new TestEnv { val result = Enumerator(10, 20, 30) |>>> iteratee next() must beLike { case OnSubscribe(sub) => isEmptyAfterDelay() must beTrue sub.request(2) next() must_== OnNext(10) next() must_== OnNext(20) isEmptyAfterDelay() must beTrue sub.request(2) next() must_== OnNext(30) next() must_== OnComplete } await(result) must_== () } "publish events all at once in response to demand" in new TestEnv { val result = Enumerator(10, 20, 30) |>>> iteratee next() must beLike { case OnSubscribe(sub) => isEmptyAfterDelay() must beTrue sub.request(10) next() must_== OnNext(10) next() must_== OnNext(20) next() must_== OnNext(30) next() must_== OnComplete } await(result) must_== () } "become done when the stream is cancelled" in new TestEnv { val result = Enumerator(10, 20, 30) |>>> iteratee.flatMap(_ => Iteratee.getChunks[Int]) next() must beLike { case OnSubscribe(sub) => sub.request(1) next() must_== OnNext(10) sub.cancel() isEmptyAfterDelay() must beTrue } await(result) must_== Seq(20, 30) } } }
nelsonblaha/playframework
framework/src/play/src/test/scala/play/api/libs/EventSourceSpec.scala
<reponame>nelsonblaha/playframework<gh_stars>1-10 package play.api.libs import org.specs2.mutable.Specification import play.api.http.{ ContentTypes, HeaderNames } import play.api.libs.iteratee.Enumerator import play.api.mvc.Results object EventSourceSpec extends Specification { import EventSource.Event "EventSource event formatter" should { "format an event" in { Event("foo", None, None).formatted must equalTo("data: foo\n\n") } "format an event with an id" in { Event("foo", Some("42"), None).formatted must equalTo("id: 42\ndata: foo\n\n") } "format an event with a name" in { Event("foo", None, Some("message")).formatted must equalTo("event: message\ndata: foo\n\n") } "split data by lines" in { Event("a\nb").formatted must equalTo("data: a\ndata: b\n\n") } "support '\\r' as an end of line" in { Event("a\rb").formatted must equalTo("data: a\ndata: b\n\n") } "support '\\r\\n' as an end of line" in { Event("a\r\nb").formatted must equalTo("data: a\ndata: b\n\n") } } "EventSource.Event" should { "be writeable as a response body" in { val result = Results.Ok.chunked(Enumerator("foo", "bar", "baz") &> EventSource()) result.body.contentType must beSome(ContentTypes.EVENT_STREAM) } } }
nelsonblaha/playframework
documentation/manual/working/javaGuide/main/sql/code/jpa.sbt
PlayKeys.externalizeResources := false
nelsonblaha/playframework
templates/project/plugins.sbt
<gh_stars>1-10 addSbtPlugin("com.typesafe.sbt" % "sbt-s3" % "0.5") // Depend on hard coded play-ws version, since we don't need/want the latest, and the system // properties from this build interfere with the system properties from Play's build. This // can be updated to something else when needed, but doesn't need to be. libraryDependencies += "com.typesafe.play" %% "play-ws" % "2.4.0" // Add a resources directory, so that we can include a logback configuration, otherwise we // get debug logs for everything which is huge. resourceDirectories in Compile += baseDirectory.value / "resources" resources in Compile ++= (baseDirectory.value / "resources").***.get
harborx/play-di-example
play-macwire/test/com/harborx/api/device/DeviceServiceSpec.scala
package com.harborx.api.device import com.harborx.api.modules.DeviceModule import org.scalamock.scalatest.MockFactory import org.scalatest.GivenWhenThen import org.scalatestplus.play.PlaySpec /** * We shall use our custom Spec instead of PlaySpec in real life * Test for service layer logic here, so we stub DeviceRepository * TODO: Test for DeviceRepository */ class DeviceServiceSpec extends PlaySpec with GivenWhenThen with MockFactory with DeviceModule { override lazy val deviceRepository = stub[DeviceRepository] "DeviceService" must { "forward what DeviceRepository give" in { (deviceRepository.getDevice _).when(*).returns(Device(2)) deviceService.getDevice(10) mustBe Device(2) } } }
harborx/play-di-example
play-guice/app/com/harborx/api/system/SystemConfig.scala
<reponame>harborx/play-di-example package com.harborx.api.system import javax.inject.Inject import play.api.Configuration /** * An example config object. I can "inject" to anywhere I need */ class SystemConfig @Inject() (config: Configuration) { val EXAMPLE_CONFIG = config.getString("harborx.api.example").getOrElse("config DI fail!?") }
harborx/play-di-example
play-guice/app/com/harborx/api/system/SystemController.scala
package com.harborx.api.system import javax.inject._ import play.api.Environment import play.api.mvc.{Action, Controller} class SystemController @Inject() (config: SystemConfig, env: Environment) extends Controller { def configExample() = Action { Ok(config.EXAMPLE_CONFIG) } def envExample() = Action { Ok(s"current mode is:${env.mode.toString}") } }
harborx/play-di-example
play-macwire/app/com/harborx/api/system/SystemController.scala
package com.harborx.api.system import play.api.Environment import play.api.mvc.{Action, Controller} class SystemController(config: SystemConfig, environment: Environment) extends Controller { def configExample() = Action { Ok(config.EXAMPLE_CONFIG) } def envExample() = Action { Ok(s"current mode is:${environment.mode.toString}") } }
harborx/play-di-example
play-macwire/app/com/harborx/api/modules/SystemModule.scala
<reponame>harborx/play-di-example package com.harborx.api.modules import com.harborx.api.system._ trait SystemModule extends CoreModule { // it need to extends CoreModule to acquire the dependency on configuration and environment import com.softwaremill.macwire._ lazy val systemController: SystemController = wire[SystemController] lazy val systemConfig: SystemConfig = wire[SystemConfig] // act as a config object, I can "inject" to anywhere I need }
harborx/play-di-example
play-macwire/test/com/harborx/api/WithApplicationComponents.scala
<reponame>harborx/play-di-example<filename>play-macwire/test/com/harborx/api/WithApplicationComponents.scala package com.harborx.api import org.scalatest.{Suite, TestData} import org.scalatestplus.play.{OneAppPerSuite, OneAppPerTest, OneServerPerSuite, OneServerPerTest} import play.api.ApplicationLoader.Context import play.api.{BuiltInComponents, _} /** * A trait that provides a components in scope and creates new components when newApplication is called * * This class has several methods that can be used to customize the behavior in specific ways. * * @tparam C the type of the fully-built components class */ trait WithApplicationComponents[C <: BuiltInComponents] { private var _components: C = _ /** * @return The current components */ final def components: C = _components /** * @return the components to be used by the application */ def createComponents(context: Context): C /** * @return new application instance and set the components. This must be called for components to be properly set up. */ final def newApplication: Application = { _components = createComponents(context) initialize(_components) } /** * Initialize the application from the components. This can be used to do eager instantiation or otherwise * set up things. * * @return the application that will be used for testing */ def initialize(components: C): Application = _components.application /** * @return a context to use to create the application. */ def context: ApplicationLoader.Context = { val classLoader = ApplicationLoader.getClass.getClassLoader val env = new Environment(new java.io.File("."), classLoader, Mode.Test) ApplicationLoader.createContext(env) } } trait OneAppPerTestWithComponents[T <: BuiltInComponents] extends OneAppPerTest with WithApplicationComponents[T] { this: Suite => override def newAppForTest(testData: TestData): Application = newApplication } trait OneAppPerSuiteWithComponents[T <: BuiltInComponents] extends OneAppPerSuite with WithApplicationComponents[T] { this: Suite => override implicit lazy val app: Application = newApplication } trait OneServerPerTestWithComponents[T <: BuiltInComponents] extends OneServerPerTest with WithApplicationComponents[T] { this: Suite => override def newAppForTest(testData: TestData): Application = newApplication } trait OneServerPerSuiteWithComponents[T <: BuiltInComponents] extends OneServerPerSuite with WithApplicationComponents[T] { this: Suite => override implicit lazy val app: Application = newApplication }
harborx/play-di-example
play-macwire/app/com/harborx/api/modules/AppSingletonModule.scala
package com.harborx.api.modules import com.harborx.api.singleton.AppSingleton import play.api.inject.ApplicationLifecycle trait AppSingletonModule extends CoreModule { import com.softwaremill.macwire._ lazy val appSingleton: AppSingleton = wire[AppSingleton] def applicationLifecycle: ApplicationLifecycle }
harborx/play-di-example
play-macwire/test/com/harborx/api/system/SystemSpec.scala
package com.harborx.api.system import com.harborx.api.{HxAppComponents, OneAppPerTestWithComponents} import org.scalamock.scalatest.MockFactory import org.scalatest._ import org.scalatestplus.play.{PlaySpec, _} import play.api.ApplicationLoader.Context import play.api.mvc._ import play.api.test.FakeRequest import play.api.test.Helpers._ import scala.concurrent.Future class SystemSpec extends PlaySpec with OneAppPerTestWithComponents[HxAppComponents] with MustMatchers with MockFactory { override def createComponents(context: Context) = new HxAppComponents(context) "System controller" must { "return OK when call GET /example" in { val request = FakeRequest(GET, "/example") val response = route(app, request) response.isDefined mustEqual true val result: Future[Result] = response.get status(result) mustEqual OK contentAsString(result) mustEqual "If you can see this, it means DI of Configuration is success!" } "return Test when call GET /env" in { val request = FakeRequest(GET, "/env") val response = route(app, request) response.isDefined mustEqual true val result: Future[Result] = response.get status(result) mustEqual OK contentAsString(result) mustEqual "current mode is:Test" } } }
harborx/play-di-example
play-macwire/app/com/harborx/api/system/SystemConfig.scala
<gh_stars>1-10 package com.harborx.api.system import play.api.Configuration /** * an example config object */ class SystemConfig(configuration: Configuration) { val EXAMPLE_CONFIG = configuration.getString("harborx.api.example").getOrElse("config DI fail!?") }
harborx/play-di-example
play-guice/app/com/harborx/api/module/SingletonModule.scala
package com.harborx.api.module import com.google.inject.AbstractModule import com.harborx.api.singleton._ class SingletonModule extends AbstractModule { def configure() = { bind(classOf[AppSingleton]).to(classOf[AppSingletonImpl]).asEagerSingleton } }
harborx/play-di-example
play-guice/build.sbt
<reponame>harborx/play-di-example name := """play-guice""" version := "1.0.0" lazy val root = (project in file(".")).enablePlugins(PlayScala) scalaVersion := "2.11.8" scalacOptions := Seq( "-deprecation", "-encoding", "UTF-8", "-feature", "-unchecked", "-Xfatal-warnings", "-Ywarn-dead-code", "-Ywarn-numeric-widen", "-Ywarn-value-discard" ) libraryDependencies ++= Seq( "com.typesafe.play" %% "play-slick" % "2.0.2", "com.typesafe.play" %% "play-slick-evolutions" % "2.0.2", "org.scalamock" %% "scalamock-scalatest-support" % "3.2.2" % "test", "org.scalatestplus.play" %% "scalatestplus-play" % "1.5.0" % "test" ) // Play provides two styles of routers, one expects its actions to be injected, the // other, legacy style, accesses its actions statically. routesGenerator := InjectedRoutesGenerator
harborx/play-di-example
play-macwire/test/com/harborx/api/system/SystemControllerSpec.scala
<filename>play-macwire/test/com/harborx/api/system/SystemControllerSpec.scala package com.harborx.api.system import com.harborx.api.SimpleEnvConfigProvider import com.harborx.api.modules.SystemModule import org.scalamock.scalatest.MockFactory import org.scalatestplus.play.PlaySpec import play.api.mvc._ import play.api.test.FakeRequest import play.api.test.Helpers._ import scala.concurrent.Future /** * Test for controller logic * So we mock service here */ class SystemControllerSpec extends PlaySpec with Results with MockFactory with SystemModule with SimpleEnvConfigProvider { "System Controller" should { "return correct Mode" in { val result: Future[Result] = systemController.envExample()(FakeRequest()) val bodyText: String = contentAsString(result) bodyText mustBe "current mode is:Test" } "return correct config" in { val result: Future[Result] = systemController.configExample()(FakeRequest()) val bodyText: String = contentAsString(result) bodyText mustBe "If you can see this, it means DI of Configuration is success!" } } }
harborx/play-di-example
play-macwire/app/com/harborx/api/AppApplicationLoader.scala
package com.harborx.api import com.harborx.api.modules._ import play.api.ApplicationLoader.Context import play.api._ import play.api.routing.Router import router.Routes import com.softwaremill.macwire._ class AppApplicationLoader extends ApplicationLoader { def load(context: Context): Application = new HxAppComponents(context).application } class HxAppComponents(context: Context) extends BuiltInComponentsFromContext(context) with AppComponents { LoggerConfigurator(context.environment.classLoader).foreach { _.configure(context.environment) } appSingleton.init() } trait AppComponents extends BuiltInComponents with SystemModule with AppSingletonModule with DeviceModule { lazy val router: Router = { // add the prefix string in local scope for the Routes constructor val prefix: String = "/" wire[Routes] } }
harborx/play-di-example
play-guice/app/com/harborx/api/singleton/AppSingleton.scala
package com.harborx.api.singleton import javax.inject._ import com.google.inject.ImplementedBy import play.api.Logger import play.api.inject.ApplicationLifecycle import scala.concurrent.Future @ImplementedBy(classOf[AppSingletonImpl]) trait AppSingleton { } @Singleton class AppSingletonImpl @Inject() (lifecycle: ApplicationLifecycle) extends AppSingleton { protected val logger = Logger(getClass) logger.info("Application has started") lifecycle.addStopHook { () => Future.successful(logger.info("Application has stopped")) } }
harborx/play-di-example
play-macwire/app/com/harborx/api/device/DeviceRepositoryImpl.scala
package com.harborx.api.device trait DeviceRepository { def getDevice(id: Int): Device } class DeviceRepositoryImpl extends DeviceRepository { def getDevice(id: Int): Device = Device(id) }
harborx/play-di-example
play-macwire/test/com/harborx/api/SimpleEnvConfigProvider.scala
package com.harborx.api import com.harborx.api.modules.CoreModule import play.api.{Configuration, Environment} trait SimpleEnvConfigProvider { this: CoreModule => // dependence override def configuration: Configuration = Configuration.load(environment) override def environment: Environment = Environment.simple() }
harborx/play-di-example
play-macwire/app/com/harborx/api/device/DeviceController.scala
<reponame>harborx/play-di-example package com.harborx.api.device import play.api.mvc.{Action, Controller} class DeviceController(deviceService: DeviceService) extends Controller { def get() = Action { val d = deviceService.getDevice(1) Ok(d.toString) } }
harborx/play-di-example
play-guice/app/com/harborx/api/device/DeviceService.scala
package com.harborx.api.device import com.google.inject.ImplementedBy import javax.inject._ @ImplementedBy(classOf[DeviceServiceImpl]) trait DeviceService { def getDevice(id: Int): Device } /** * Impl with DeviceServiceImpl is not happy * If we forgot to extends, can compile, but run time error!! */ class DeviceServiceImpl @Inject() (deviceRepo: DeviceRepository) extends DeviceService { /** * simple proxy impl for testing */ def getDevice(id: Int): Device = { deviceRepo.getDevice(id) } }
harborx/play-di-example
play-macwire/app/com/harborx/api/singleton/AppSingleton.scala
<reponame>harborx/play-di-example<gh_stars>1-10 package com.harborx.api.singleton import play.api.{Configuration, Logger} import play.api.inject.ApplicationLifecycle import scala.concurrent.Future class AppSingleton(configuration: Configuration, applicationLifecycle: ApplicationLifecycle) { protected val logger = Logger(getClass) // shall call appSingleton.init() to perform App onStart() hook and addStopHook def init() = { logger.info("Application has started") applicationLifecycle.addStopHook { () => Future.successful(logger.info("Application has stopped")) } } }
harborx/play-di-example
play-guice/test/com/harborx/api/device/DeviceSpec.scala
<filename>play-guice/test/com/harborx/api/device/DeviceSpec.scala package com.harborx.api.device import org.scalatest._ import org.scalatestplus.play.{PlaySpec, _} import play.api.inject.bind import play.api.inject.guice.GuiceApplicationBuilder import play.api.mvc._ import play.api.test.FakeRequest import play.api.test.Helpers._ import scala.concurrent.Future /** * Guice way to mock and do integration test */ class DeviceSpec extends PlaySpec with OneServerPerSuite with MustMatchers with BeforeAndAfterAll { override lazy val app = new GuiceApplicationBuilder() .overrides(bind[DeviceRepository].to[MockDeviceRepository]) .build "Device controller" must { "return OK when call GET /device" in { val request = FakeRequest(GET, "/device") val response = route(app, request) response.isDefined mustEqual true val result: Future[Result] = response.get status(result) mustEqual OK contentAsString(result) mustEqual "Device(3)" } } } class MockDeviceRepository extends DeviceRepositoryImpl { override def getDevice(id: Int) = { Device(3) } }
harborx/play-di-example
play-guice/test/com/harborx/api/device/DeviceControllerSpec.scala
package com.harborx.api.device import org.scalamock.scalatest.MockFactory import org.scalatestplus.play.PlaySpec import play.api.mvc._ import play.api.test.FakeRequest import play.api.test.Helpers._ import scala.concurrent.Future /** * Test for controller logic * So we mock service here */ class DeviceControllerSpec extends PlaySpec with Results with MockFactory { "DeviceController" should { "should be valid" in { val deviceService = stub[DeviceService] (deviceService.getDevice _).when(*).returns(Device(5)) val controller: DeviceController = new DeviceController(deviceService) val result: Future[Result] = controller.get()(FakeRequest()) val bodyText: String = contentAsString(result) bodyText mustBe "Device(5)" } } }
harborx/play-di-example
play-guice/app/com/harborx/api/device/DeviceRepository.scala
<filename>play-guice/app/com/harborx/api/device/DeviceRepository.scala package com.harborx.api.device import com.google.inject.ImplementedBy /** * easy to forgot or make typo! */ @ImplementedBy(classOf[DeviceRepositoryImpl]) trait DeviceRepository { def getDevice(id: Int): Device } /** * Impl with DeviceRepositoryImpl is not happy! * If we forgot to extends, can compile, but run time error!! */ class DeviceRepositoryImpl extends DeviceRepository { def getDevice(id: Int) = Device(id) }
harborx/play-di-example
play-guice/app/com/harborx/api/device/DeviceController.scala
<filename>play-guice/app/com/harborx/api/device/DeviceController.scala package com.harborx.api.device import javax.inject._ import play.api.mvc.{Action, Controller} class DeviceController @Inject() (deviceService: DeviceService) extends Controller { def get() = Action { val d = deviceService.getDevice(1) Ok(d.toString) } }
harborx/play-di-example
play-macwire/app/com/harborx/api/modules/CoreModule.scala
package com.harborx.api.modules import play.api.{Configuration, Environment} trait CoreModule { // dependence // AppApplicationLoader and HxAppComponents will help to load(?) it. def configuration: Configuration def environment: Environment }
harborx/play-di-example
play-macwire/app/com/harborx/api/device/DeviceServiceImpl.scala
package com.harborx.api.device trait DeviceService { def getDevice(id: Int): Device } class DeviceServiceImpl(deviceRepository: DeviceRepository) extends DeviceService { /** * simple proxy impl for testing */ def getDevice(id: Int): Device = { deviceRepository.getDevice(id) } }
harborx/play-di-example
play-guice/test/com/harborx/api/device/DeviceServiceSpec.scala
package com.harborx.api.device import org.scalamock.scalatest.MockFactory import org.scalatest.GivenWhenThen import org.scalatestplus.play.PlaySpec /** * We shall use our custom Spec instead of PlaySpec in real life * Test for service layer logic here, so we stub DeviceRepository * TODO: Test for DeviceRepository */ class DeviceServiceSpec extends PlaySpec with GivenWhenThen with MockFactory { "DeviceService" must { "forward what DeviceRepository give" in { val deviceRepo = stub[DeviceRepository] (deviceRepo.getDevice _).when(*).returns(Device(2)) /** * any better way to not inject the params here? * Not a good way if we have tons of dependencies? */ val deviceService: DeviceService = new DeviceServiceImpl(deviceRepo) deviceService.getDevice(10) mustBe Device(2) } } }
harborx/play-di-example
play-macwire/test/com/harborx/api/device/DeviceControllerSpec.scala
<reponame>harborx/play-di-example package com.harborx.api.device import com.harborx.api.modules.DeviceModule import org.scalamock.scalatest.MockFactory import org.scalatestplus.play.PlaySpec import play.api.mvc._ import play.api.test.FakeRequest import play.api.test.Helpers._ import scala.concurrent.Future /** * Test for controller logic * So we mock service here */ class DeviceControllerSpec extends PlaySpec with Results with MockFactory with DeviceModule { override lazy val deviceService = stub[DeviceService] "Device Controller" should { "should get something" in { (deviceService.getDevice _).when(*).returns(Device(5)) val result: Future[Result] = deviceController.get()(FakeRequest()) val bodyText: String = contentAsString(result) bodyText mustBe "Device(5)" } } }
harborx/play-di-example
play-macwire/test/com/harborx/api/device/DeviceSpec.scala
<gh_stars>1-10 package com.harborx.api.device import com.harborx.api.{HxAppComponents, OneAppPerTestWithComponents} import org.scalamock.scalatest.MockFactory import org.scalatest._ import org.scalatestplus.play.PlaySpec import play.api.ApplicationLoader.Context import play.api.mvc._ import play.api.test.FakeRequest import play.api.test.Helpers._ import scala.concurrent.Future class DeviceSpec extends PlaySpec with OneAppPerTestWithComponents[HxAppComponents] with MustMatchers with MockFactory { lazy val stubDevice = stub[DeviceService] (stubDevice.getDevice _).when(*).returns(Device(5)) override def createComponents(context: Context) = new HxAppComponents(context) { override lazy val deviceService = stubDevice } "Device controller" must { "return OK when call GET /device" in { val request = FakeRequest(GET, "/device") val response = route(app, request) response.isDefined mustEqual true val result: Future[Result] = response.get status(result) mustEqual OK contentAsString(result) mustEqual "Device(5)" } } }
harborx/play-di-example
play-macwire/app/com/harborx/api/device/Device.scala
<reponame>harborx/play-di-example<gh_stars>1-10 package com.harborx.api.device case class Device(id: Int)
harborx/play-di-example
play-macwire/app/com/harborx/api/modules/DeviceModule.scala
package com.harborx.api.modules import com.harborx.api.device._ trait DeviceModule { import com.softwaremill.macwire._ lazy val deviceController: DeviceController = wire[DeviceController] lazy val deviceService: DeviceService = wire[DeviceServiceImpl] lazy val deviceRepository: DeviceRepository = wire[DeviceRepositoryImpl] }
jarredlim/effpi-error-detection
examples/src/main/scala/recovery/test.scala
package effpi.examples.recovery.test import scala.concurrent.duration.Duration import effpi.channel.{Channel => Chan, InChannel => IChan, OutChannel => OChan} import effpi.process._ import effpi.process.dsl._ import scala.util.Random package object types { case class Data() type T1 = OK | Req case class OK() case class Req() type P[C1 <: OChan[Data], C2 <: OChan[Data]] = Out[C1, Data] >>: Out[C2, Data] type Q1[C4 <: OChan[Data], Y <: T1] <: Process = Y match { case OK => PNil case Req => Out[C4, Data] } type Q[C1 <: IChan[Data], C3 <: IChan[T1], C4 <: OChan[Data]] = In[C1, Data, (x : Data) => In[C3, T1, (y : T1) => Q1[C4, y.type]]] type R[C2 <: IChan[Data], C3 <: OChan[T1], C4 <: IChan[Data]] = // In[C2, Data, (x : Data) => Out[C3, OK]] InErr[C2, Data, (x : Data) => Out[C3, OK], (err : Throwable) => (Out[C3, Req] >>: In[C4, Data, (y : Data) => PNil])] } package object implementation { import types._ implicit val timeout: Duration = Duration("100 seconds") val rng = new Random() def setupP(c1 : OChan[Data], c2 : OChan[Data]) : P[c1.type, c2.type] = { send(c1, Data()) >> { println(s"[P] Am I going to die?") if (rng.nextBoolean()) throw RuntimeException("[P] Yes.") println(s"[P] No.") send(c2, Data()) // could make it so that it errors here } } def setupQ(c1 : IChan[Data], c3 : IChan[T1], c4 : OChan[Data]) : Q[c1.type, c3.type, c4.type] = { receive(c1) { data => println(s"[Q] Received Data from P.") receive(c3) { t1 => println(s"[Q] Received msg from R: ${t1}") t1 match { case _ : OK => nil case _ : Req => send(c4, data) } } } } // def setupR(c2 : IChan[Data], c3 : OChan[T1], c4 : IChan[Data]) : R[c2.type, c3.type, c4.type] = { // receive(c2) { (data : Data) => // println(s"[R] Received Data from P.") // send(c3, OK()) // } // { (err : Throwable) => // println(s"[R] Timout waiting on P; assume it crashed.") // send(c3, Req()) >> // receive(c4) { (data : Data) => // println(s"[R] Received Data from Q.") // nil // } // } // } //** Intention (doesn't work) def setupR(c2 : IChan[Data], c3 : OChan[T1], c4 : IChan[Data]) : R[c2.type, c3.type, c4.type] = { receiveErr(c2) ({ (data : Data) => println(s"[R] Received Data from P.") send(c3, OK()) }, { (err : Throwable) => println(s"[R] Timout waiting on P; assume it crashed.") send(c3, Req()) >> receive(c4) { (data : Data) => println(s"[R] Received Data from Q.") nil } }, Duration("5 seconds")) } //*********************************************************************************************** //** Sanity check //** Works fine: type Test1[C1 <: IChan[Data], C2 <: OChan[T1]] = InErr[C1, Data, ((x : Data) => PNil), ((err : Throwable) => PNil)] def test1(c1 : IChan[Data], c2 : OChan[T1]) : Test1[c1.type, c2.type] = { receiveErr(c1)(((data : Data) => nil),((err : Throwable) => nil), Duration("5 seconds")) } //** Doesn't typecheck: type TestOK[C2 <: OChan[T1]] = Out[C2, T1] type Test2[C1 <: IChan[Data], C2 <: OChan[T1]] = InErr[C1, Data, ((x : Data) => TestOK[C2]), ((err : Throwable) => PNil)] def testOK(c2 : OChan[T1]) : TestOK[c2.type] = send(c2, OK()) // Typechecks def test2(c1 : IChan[Data], c2 : OChan[T1]) : Test2[c1.type, c2.type] = { // Doesn't receiveErr(c1)(((data : Data) => testOK(c2)),((err : Throwable) => nil), Duration("5 seconds")) } //** END //*********************************************************************************************** def setup(c1 : Chan[Data], c2 : Chan[Data], c3 : Chan[T1], c4 : Chan[Data]) : Par3[P[c1.type, c2.type], Q[c1.type, c3.type, c4.type], R[c2.type, c3.type, c4.type]] = { par(setupP(c1, c2), setupQ(c1, c3, c4), setupR(c2, c3, c4)); } } // To run this example, try: // sbt "examples/runMain effpi.examples.trying.test.Main" object Main { import types._ import implementation._ def main(): Unit = main(Array()) def main(args: Array[String]) = { val (c1, c2, c3, c4) = (Chan[Data](), // P -> Q Chan[Data](), // P -> R Chan[T1](), // R -> Q Chan[Data]()) // Q -> R eval(setup(c1, c2, c3, c4)) } }
hmrc/organisations-matching-api
test/unit/uk/gov/hmrc/organisationsmatchingapi/services/MatchingServiceSpec.scala
<gh_stars>0 /* * Copyright 2021 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package unit.uk.gov.hmrc.organisationsmatchingapi.services import java.util.UUID import org.mockito.ArgumentMatchers.any import org.mockito.BDDMockito.`given` import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec import org.scalatestplus.mockito.MockitoSugar import play.api.libs.json.JsString import play.api.mvc.AnyContentAsEmpty import play.api.test.FakeRequest import uk.gov.hmrc.http.{HeaderCarrier, NotFoundException} import uk.gov.hmrc.organisationsmatchingapi.cache.InsertResult import uk.gov.hmrc.organisationsmatchingapi.connectors.{IfConnector, OrganisationsMatchingConnector} import uk.gov.hmrc.organisationsmatchingapi.domain.integrationframework.{IfAddress, IfCorpTaxCompanyDetails, IfNameAndAddressDetails, IfNameDetails, IfSaTaxPayerNameAddress, IfSaTaxpayerDetails} import uk.gov.hmrc.organisationsmatchingapi.domain.ogd.{CtMatchingRequest, SaMatchingRequest} import uk.gov.hmrc.organisationsmatchingapi.services.{CacheService, MatchingService} import uk.gov.hmrc.play.http.HeaderCarrierConverter import util.SpecBase import scala.concurrent.{ExecutionContext, Future} class MatchingServiceSpec extends AnyWordSpec with SpecBase with Matchers with MockitoSugar { private implicit val ec: ExecutionContext = scala.concurrent.ExecutionContext.Implicits.global val mockIfConnector: IfConnector = mock[IfConnector] val mockMatchingConnector: OrganisationsMatchingConnector = mock[OrganisationsMatchingConnector] val mockCacheService: CacheService = mock[CacheService] val matchingService = new MatchingService( mockIfConnector, mockMatchingConnector, mockCacheService ) val utr = "0123456789" implicit val fakeRequest: FakeRequest[AnyContentAsEmpty.type] = FakeRequest("GET", "/") implicit val hc: HeaderCarrier = HeaderCarrierConverter.fromRequest(fakeRequest) "MatchCoTax" when { val corpTaxCompanyDetails = IfCorpTaxCompanyDetails( utr = Some(utr), crn = Some(utr), registeredDetails = Some(IfNameAndAddressDetails( name = Some(IfNameDetails(Some("name"), None)), address = Some(IfAddress( line1 = Some("line1"), line2 = None, line3 = None, line4 = None, postcode = Some("postcode"))))), communicationDetails = Some(IfNameAndAddressDetails( name = Some(IfNameDetails(Some("name"), None)), address = Some(IfAddress( line1 = Some("line1"), line2 = None, line3 = None, line4 = None, postcode = Some("postcode")))))) given(mockIfConnector.fetchCorporationTax(any(), any())(any(), any(), any())) .willReturn(Future.successful(corpTaxCompanyDetails)) given(mockCacheService.cacheCtUtr(any(), any())).willReturn(InsertResult.InsertSucceeded) "Matching connector returns a match" in { given(mockMatchingConnector.matchCycleCotax(any(), any(), any())(any(), any(), any())) .willReturn(Future.successful(JsString("match"))) val result = await(matchingService.matchCoTax( UUID.randomUUID(), UUID.randomUUID().toString, CtMatchingRequest("0123456789", "name", "addressLine1", "postcode"))) result.as[String] shouldBe "match" } "Matching connector returns a Not Found" in { given(mockMatchingConnector.matchCycleCotax(any(), any(), any())(any(), any(), any())) .willReturn(Future.failed(new NotFoundException("Not found"))) intercept[NotFoundException] { await(matchingService.matchCoTax( UUID.randomUUID(), UUID.randomUUID().toString, CtMatchingRequest("0123456789", "name", "addressLine1", "postcode"))) } } } "MatchSaTax" when { val saTaxpayerDetails = IfSaTaxpayerDetails( utr = Some(utr), taxpayerType = Some("Aa"), taxpayerDetails = Some(Seq(IfSaTaxPayerNameAddress( name = Some("name"), addressType = Some("type"), address = Some(IfAddress( line1 = Some("line1"), line2 = None, line3 = None, line4 = None, postcode = Some("postcode"))) ))) ) given(mockIfConnector.fetchSelfAssessment(any(), any())(any(), any(), any())) .willReturn(Future.successful(saTaxpayerDetails)) given(mockCacheService.cacheSaUtr(any(), any())).willReturn(InsertResult.InsertSucceeded) "Matching connector returns a match" in { given(mockMatchingConnector.matchCycleSelfAssessment(any(), any(), any())(any(), any(), any())) .willReturn(Future.successful(JsString("match"))) val result = await(matchingService.matchSaTax( UUID.randomUUID(), UUID.randomUUID().toString, SaMatchingRequest("0123456789", "", "name", "addressLine1", "postcode"))) result.as[String] shouldBe "match" } "Matching connector returns a Not Found" in { given(mockMatchingConnector.matchCycleSelfAssessment(any(), any(), any())(any(), any(), any())) .willReturn(Future.failed(new NotFoundException("Not found"))) intercept[NotFoundException] { await(matchingService.matchSaTax( UUID.randomUUID(), UUID.randomUUID().toString, SaMatchingRequest("0123456789", "", "name", "addressLine1", "postcode"))) } } } }
hmrc/organisations-matching-api
test/unit/uk/gov/hmrc/organisationsmatchingapi/domain/organisationsmatching/SaKnownFactsSpec.scala
<reponame>hmrc/organisations-matching-api /* * Copyright 2021 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package unit.uk.gov.hmrc.organisationsmatchingapi.domain.organisationsmatching import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec import play.api.libs.json.Json import uk.gov.hmrc.organisationsmatchingapi.domain.organisationsmatching.SaKnownFacts import util.IfHelpers class SaKnownFactsSpec extends AnyWordSpec with Matchers with IfHelpers { "SaKnownFacts" should { "Read and write" in { val knownFacts = SaKnownFacts("utr", "individual", "name", "line1", "postcode") val asJson = Json.toJson(knownFacts) asJson shouldBe Json.parse(""" |{ | "utr" : "utr", | "name" : "name", | "taxpayerType" : "individual", | "line1" : "line1", | "postcode" : "postcode" |} |""".stripMargin) } } }
hmrc/organisations-matching-api
app/uk/gov/hmrc/organisationsmatchingapi/domain/ogd/SaMatchingRequest.scala
/* * Copyright 2021 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.gov.hmrc.organisationsmatchingapi.domain.ogd import play.api.libs.json.{Format, JsPath} import play.api.libs.functional.syntax._ case class SaMatchingRequest(selfAssessmentUniqueTaxPayerRef: String, taxPayerType: String, taxPayerName: String, addressLine1: String, postcode: String) object SaMatchingRequest { implicit val saMatchingformat: Format[SaMatchingRequest] = Format( ( (JsPath \ "selfAssessmentUniqueTaxPayerRef").read[String] and (JsPath \ "taxPayerType").read[String] and (JsPath \ "taxPayerName").read[String] and (JsPath \ "address" \ "addressLine1").read[String] and (JsPath \ "address" \ "postcode").read[String] ) (SaMatchingRequest.apply _), ( (JsPath \ "selfAssessmentUniqueTaxPayerRef").write[String] and (JsPath \ "taxPayerType").write[String] and (JsPath \ "taxPayerName").write[String] and (JsPath \ "address" \ "addressLine1").write[String] and (JsPath \ "address" \ "postcode").write[String] )(unlift(SaMatchingRequest.unapply)) ) }