repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
lhfei/spark-in-action
spark-2.x/src/main/scala/org/apache/spark/examples/SparkALS.scala
<reponame>lhfei/spark-in-action /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ // scalastyle:off println package org.apache.spark.examples import org.apache.commons.math3.linear._ import org.apache.spark.sql.SparkSession /** * Alternating least squares matrix factorization. * * This is an example implementation for learning how to use Spark. For more conventional use, * please refer to org.apache.spark.ml.recommendation.ALS. */ object SparkALS { // Parameters set through command line arguments var M = 0 // Number of movies var U = 0 // Number of users var F = 0 // Number of features var ITERATIONS = 0 val LAMBDA = 0.01 // Regularization coefficient def generateR(): RealMatrix = { val mh = randomMatrix(M, F) val uh = randomMatrix(U, F) mh.multiply(uh.transpose()) } def rmse(targetR: RealMatrix, ms: Array[RealVector], us: Array[RealVector]): Double = { val r = new Array2DRowRealMatrix(M, U) for (i <- 0 until M; j <- 0 until U) { r.setEntry(i, j, ms(i).dotProduct(us(j))) } val diffs = r.subtract(targetR) var sumSqs = 0.0 for (i <- 0 until M; j <- 0 until U) { val diff = diffs.getEntry(i, j) sumSqs += diff * diff } math.sqrt(sumSqs / (M.toDouble * U.toDouble)) } def update(i: Int, m: RealVector, us: Array[RealVector], R: RealMatrix) : RealVector = { val U = us.length val F = us(0).getDimension var XtX: RealMatrix = new Array2DRowRealMatrix(F, F) var Xty: RealVector = new ArrayRealVector(F) // For each user that rated the movie for (j <- 0 until U) { val u = us(j) // Add u * u^t to XtX XtX = XtX.add(u.outerProduct(u)) // Add u * rating to Xty Xty = Xty.add(u.mapMultiply(R.getEntry(i, j))) } // Add regularization coefs to diagonal terms for (d <- 0 until F) { XtX.addToEntry(d, d, LAMBDA * U) } // Solve it with Cholesky new CholeskyDecomposition(XtX).getSolver.solve(Xty) } def showWarning() { System.err.println( """WARN: This is a naive implementation of ALS and is given as an example! |Please use org.apache.spark.ml.recommendation.ALS |for more conventional use. """.stripMargin) } def main(args: Array[String]) { var slices = 0 val options = (0 to 4).map(i => if (i < args.length) Some(args(i)) else None) options.toArray match { case Array(m, u, f, iters, slices_) => M = m.getOrElse("100").toInt U = u.getOrElse("500").toInt F = f.getOrElse("10").toInt ITERATIONS = iters.getOrElse("5").toInt slices = slices_.getOrElse("2").toInt case _ => System.err.println("Usage: SparkALS [M] [U] [F] [iters] [partitions]") System.exit(1) } showWarning() println(s"Running with M=$M, U=$U, F=$F, iters=$ITERATIONS") val spark = SparkSession .builder .appName("SparkALS") .getOrCreate() val sc = spark.sparkContext val R = generateR() // Initialize m and u randomly var ms = Array.fill(M)(randomVector(F)) var us = Array.fill(U)(randomVector(F)) // Iteratively update movies then users val Rc = sc.broadcast(R) var msb = sc.broadcast(ms) var usb = sc.broadcast(us) for (iter <- 1 to ITERATIONS) { println(s"Iteration $iter:") ms = sc.parallelize(0 until M, slices) .map(i => update(i, msb.value(i), usb.value, Rc.value)) .collect() msb = sc.broadcast(ms) // Re-broadcast ms because it was updated us = sc.parallelize(0 until U, slices) .map(i => update(i, usb.value(i), msb.value, Rc.value.transpose())) .collect() usb = sc.broadcast(us) // Re-broadcast us because it was updated println(s"RMSE = ${rmse(R, ms, us)}") } spark.stop() } private def randomVector(n: Int): RealVector = new ArrayRealVector(Array.fill(n)(math.random)) private def randomMatrix(rows: Int, cols: Int): RealMatrix = new Array2DRowRealMatrix(Array.fill(rows, cols)(math.random)) } // scalastyle:on println
lhfei/spark-in-action
spark-2.x/src/main/scala/cn/lhfei/spark/ml/KMeanApp.scala
package cn.lhfei.spark.ml import org.apache.spark.ml.clustering.KMeans import org.apache.spark.sql.SparkSession object KMeanApp { def main(args: Array[String]) { val spark = SparkSession.builder() .appName("KMeans Sample") .master("local[1]") .getOrCreate(); val dataset = spark.read.format("libsvm").load("hdfs://master1.cloud.cn:9000/spark-data/data/mllib/sample_kmeans_data.txt") // Trains a k-means model. val kmeans = new KMeans().setK(2).setSeed(1L) val model = kmeans.fit(dataset) // Evaluate clustering by computing Within Set Sum of Squared Errors. val WSSSE = model.computeCost(dataset) println(s"Within Set Sum of Squared Errors = $WSSSE") // Shows the result. println("Cluster Centers: ") model.clusterCenters.foreach(println) // $example off$ spark.stop() } }
lhfei/spark-in-action
spark-2.x/src/main/scala/cn/lhfei/spark/df/DataframePlay.scala
<gh_stars>1-10 package cn.lhfei.spark.df import org.apache.spark.sql.{Encoder, Row, SparkSession} import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder import org.apache.spark.sql.types.{StringType, StructField, StructType} object DataframePlay { case class Person(name: String, age: Long) def main(args: Array[String]) = { val spark = SparkSession.builder() .appName("Spark Dataframe example by Scala.") .getOrCreate(); extractJson(spark); convertJson(spark); runInferSchemaExample(spark); runProgrammaticSchemaExample(spark); } private def extractJson(spark: SparkSession): Unit = { val df = spark.read.json("/spark-data/people.json"); df.show(); // Print the schema in a tree format df.printSchema(); // Select only the "name" column df.select("name").show(); import spark.implicits._ // Select everybody, but increment the age by 1 df.select($"name", $"age" + 1).show(); // Select people older than 21 df.filter($"age" > 21).show() // Count people by age df.groupBy("age").count().show(); df.createOrReplaceTempView("People"); val sqlDF = spark.sql("SELECT * FROM People"); sqlDF.show(); } private def convertJson(spark: SparkSession): Unit = { import spark.implicits._ import scala.collection.Seq val caseClassDS = Seq(Person("Andy", 32)).toDS() caseClassDS.show() } private def runInferSchemaExample(spark: SparkSession): Unit = { // $example on:schema_inferring$ // For implicit conversions from RDDs to DataFrames import spark.implicits._ // Create an RDD of Person objects from a text file, convert it to a Dataframe val peopleDF = spark.sparkContext .textFile("/spark-data/people.txt") .map(_.split(",")) .map(attributes => Person(attributes(0), attributes(1).trim.toInt)) .toDF() // Register the DataFrame as a temporary view peopleDF.createOrReplaceTempView("people") // SQL statements can be run by using the sql methods provided by Spark val teenagersDF = spark.sql("SELECT name, age FROM people WHERE age BETWEEN 13 AND 19") // The columns of a row in the result can be accessed by field index teenagersDF.map(teenager => "Name: " + teenager(0)).show() // +------------+ // | value| // +------------+ // |Name: Justin| // +------------+ // or by field name teenagersDF.map(teenager => "Name: " + teenager.getAs[String]("name")).show() // +------------+ // | value| // +------------+ // |Name: Justin| // +------------+ // No pre-defined encoders for Dataset[Map[K,V]], define explicitly implicit val mapEncoder = org.apache.spark.sql.Encoders.kryo[Map[String, Any]] // Primitive types and case classes can be also defined as implicit val stringIntMapEncoder: Encoder[Map[String, Int]] = ExpressionEncoder() // row.getValuesMap[T] retrieves multiple columns at once into a Map[String, T] teenagersDF.map(teenager => teenager.getValuesMap[Any](List("name", "age"))).collect() // Array(Map("name" -> "Justin", "age" -> 19)) // $example off:schema_inferring$ } private def runProgrammaticSchemaExample(spark: SparkSession): Unit = { import spark.implicits._ // $example on:programmatic_schema$ // Create an RDD val peopleRDD = spark.sparkContext.textFile("/spark-data/people.txt") // The schema is encoded in a string val schemaString = "name age" // Generate the schema based on the string of schema val fields = schemaString.split(" ") .map(fieldName => StructField(fieldName, StringType, nullable = true)) val schema = StructType(fields) // Convert records of the RDD (people) to Rows val rowRDD = peopleRDD .map(_.split(",")) .map(attributes => Row(attributes(0), attributes(1).trim)) // Apply the schema to the RDD val peopleDF = spark.createDataFrame(rowRDD, schema) // Creates a temporary view using the DataFrame peopleDF.createOrReplaceTempView("people") // SQL can be run over a temporary view created using DataFrames val results = spark.sql("SELECT name FROM people") // The results of SQL queries are DataFrames and support all the normal RDD operations // The columns of a row in the result can be accessed by field index or by field name results.map(attributes => "Name: " + attributes(0)).show() // +-------------+ // | value| // +-------------+ // |Name: Michael| // | Name: Andy| // | Name: Justin| // +-------------+ // $example off:programmatic_schema$ } }
lhfei/spark-in-action
spark-2.x/src/main/scala/org/apache/spark/examples/mllib/DecisionTreeClassificationExample.scala
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ // scalastyle:off println package org.apache.spark.examples.mllib import org.apache.spark.{SparkConf, SparkContext} // $example on$ import org.apache.spark.mllib.tree.DecisionTree import org.apache.spark.mllib.tree.model.DecisionTreeModel import org.apache.spark.mllib.util.MLUtils // $example off$ object DecisionTreeClassificationExample { def main(args: Array[String]): Unit = { val conf = new SparkConf().setAppName("DecisionTreeClassificationExample") val sc = new SparkContext(conf) // $example on$ // Load and parse the data file. val data = MLUtils.loadLibSVMFile(sc, "data/mllib/sample_libsvm_data.txt") // Split the data into training and test sets (30% held out for testing) val splits = data.randomSplit(Array(0.7, 0.3)) val (trainingData, testData) = (splits(0), splits(1)) // Train a DecisionTree model. // Empty categoricalFeaturesInfo indicates all features are continuous. val numClasses = 2 val categoricalFeaturesInfo = Map[Int, Int]() val impurity = "gini" val maxDepth = 5 val maxBins = 32 val model = DecisionTree.trainClassifier(trainingData, numClasses, categoricalFeaturesInfo, impurity, maxDepth, maxBins) // Evaluate model on test instances and compute test error val labelAndPreds = testData.map { point => val prediction = model.predict(point.features) (point.label, prediction) } val testErr = labelAndPreds.filter(r => r._1 != r._2).count().toDouble / testData.count() println(s"Test Error = $testErr") println(s"Learned classification tree model:\n ${model.toDebugString}") // Save and load model model.save(sc, "target/tmp/myDecisionTreeClassificationModel") val sameModel = DecisionTreeModel.load(sc, "target/tmp/myDecisionTreeClassificationModel") // $example off$ sc.stop() } } // scalastyle:on println
lhfei/spark-in-action
spark-2.x/src/main/scala/cn/lhfei/spark/databricks/streaming/PlaylogApp.scala
<reponame>lhfei/spark-in-action<filename>spark-2.x/src/main/scala/cn/lhfei/spark/databricks/streaming/PlaylogApp.scala package cn.lhfei.spark.databricks.streaming import java.text.SimpleDateFormat object PlaylogApp { val SF: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); val NORMAL_DATE: String = "1976-01-01"; def main(args: Array[String]) { } }
lhfei/spark-in-action
spark-2.x/src/main/scala/cn/lhfei/spark/streaming/VLogApp.scala
<gh_stars>1-10 package cn.lhfei.spark.streaming import java.text.SimpleDateFormat import cn.lhfei.spark.df.streaming.vlog.VType import cn.lhfei.spark.df.streaming.vo.VLogger import org.apache.commons.net.ntp.TimeStamp import org.apache.spark.rdd.RDD import org.apache.spark.sql.SparkSession import org.apache.spark.sql.types.{StringType, StructField, StructType} object VLogApp { val SF: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); val NORMAL_DATE: String = "1976-01-01"; case class VideologPair(key: String, value: String); object vlog_schema { val err = StructField("err", StringType) val ip = StructField("ip", StringType) val ref = StructField("ref", StringType) val sid = StructField("sid", StringType) val uid = StructField("uid", StringType) val from = StructField("from", StringType) val loc = StructField("loc", StringType) val cat = StructField("cat", StringType) val tm = StructField("tm", StringType) val url = StructField("url", StringType) val dur = StructField("dur", StringType) val bt = StructField("bt", StringType) val bl = StructField("bl", StringType) val lt = StructField("lt", StringType) val vid = StructField("vid", StringType) val ptype = StructField("ptype", StringType) val cdnId = StructField("cdnId", StringType) val netname = StructField("netname", StringType) val tr = StructField("tr", StringType) val struct = StructType(Array(err, ip, ref, sid, uid, from, loc, cat, tm, url, dur, bt, bl, lt, vid, ptype, cdnId, netname, tr)) } def main(args: Array[String]) = { val spark = SparkSession.builder() .appName("Video Log Parser") .getOrCreate(); val records = filteLog(spark); System.out.println(records.count()); val vlDF = conver2Vo(spark); System.out.println("============" +vlDF.count()) //vlDF.foreach { x => System.out.println("++++++++CAT: " +x.getCat) } groupBy(vlDF); toDataframe(vlDF, spark) } def toDataframe(vlDF: RDD[VLogger], spark:SparkSession): Unit = { var df = spark.createDataFrame(vlDF, Class.forName("cn.lhfei.spark.df.streaming.vo.VLogger")) df.createOrReplaceTempView("VL"); df.show(); val catDF = spark.sql("select cat as CAT, count(*) as Total from VL group by cat order by Total desc") catDF.show(); } def groupBy(vlDF: RDD[VLogger]): Unit = { val keyMaps = vlDF.groupBy { x => x.getCat } keyMaps.foreach(f => System.out.println("Key: [" + f._1 + "], Total: [" + f._2.size + "]")) } def conver2Vo(spark: SparkSession): RDD[VLogger] = { val logFile = spark.sparkContext.textFile("/spark-data/vlogs/0001.txt"); def convert(items: Array[String]): VLogger = { var vlog: VLogger = new VLogger(); var err:String = items(15); if (err != null && err.startsWith("301030_")) { err = "301030_X"; } vlog.setErr(err); vlog.setIp(items(2)); vlog.setRef(items(3)); vlog.setSid(items(4)); vlog.setUid(items(5)); vlog.setLoc(items(8)); vlog.setCat(VType.getVType(items(21), items(7), items(20))); vlog.setTm(items(11)); vlog.setUrl(items(12)); vlog.setDur(items(14)); vlog.setBt(items(16)); vlog.setBl(items(17)); vlog.setLt(items(18)); vlog.setVid(items(20)); vlog.setPtype(items(21)); vlog.setCdnId(items(22)); vlog.setNetname(items(23)); //System.out.println(">>>>>>>>>>>>Cat: "+vlog.getCat); return vlog; } return logFile.map[Array[String]] { x => x.split(" ") }.map[VLogger] { items => convert(items) } } def filteLog(spark: SparkSession): RDD[Array[String]] = { var ts: TimeStamp = null; var vlog: VLogger = null; val logFile = spark.sparkContext.textFile("/spark-data/vlogs/mini.txt"); return logFile.map[Array[String]] { x => x.split(" ") } } }
lhfei/spark-in-action
spark-2.x/src/main/scala/org/apache/spark/examples/mllib/KMeansExample.scala
<reponame>lhfei/spark-in-action<gh_stars>1-10 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ // scalastyle:off println package org.apache.spark.examples.mllib import org.apache.spark.{SparkConf, SparkContext} // $example on$ import org.apache.spark.mllib.clustering.{KMeans, KMeansModel} import org.apache.spark.mllib.linalg.Vectors // $example off$ object KMeansExample { def main(args: Array[String]) { val conf = new SparkConf().setAppName("KMeansExample") val sc = new SparkContext(conf) // $example on$ // Load and parse the data val data = sc.textFile("data/mllib/kmeans_data.txt") val parsedData = data.map(s => Vectors.dense(s.split(' ').map(_.toDouble))).cache() // Cluster the data into two classes using KMeans val numClusters = 2 val numIterations = 20 val clusters = KMeans.train(parsedData, numClusters, numIterations) // Evaluate clustering by computing Within Set Sum of Squared Errors val WSSSE = clusters.computeCost(parsedData) println(s"Within Set Sum of Squared Errors = $WSSSE") // Save and load model clusters.save(sc, "target/org/apache/spark/KMeansExample/KMeansModel") val sameModel = KMeansModel.load(sc, "target/org/apache/spark/KMeansExample/KMeansModel") // $example off$ sc.stop() } } // scalastyle:on println
lhfei/spark-in-action
spark-2.x/src/main/scala/cn/lhfei/spark/df/ml/recommendation/recommendation.scala
<reponame>lhfei/spark-in-action package cn.lhfei.spark.df.ml.recommendation object recommendation extends App { }
lhfei/spark-in-action
spark-2.x/src/main/scala/org/apache/spark/examples/mllib/PCAExample.scala
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ // scalastyle:off println package org.apache.spark.examples.mllib import org.apache.spark.SparkConf import org.apache.spark.SparkContext // $example on$ import org.apache.spark.mllib.feature.PCA import org.apache.spark.mllib.linalg.Vectors import org.apache.spark.mllib.regression.{LabeledPoint, LinearRegressionWithSGD} // $example off$ @deprecated("Deprecated since LinearRegressionWithSGD is deprecated. Use ml.feature.PCA", "2.0.0") object PCAExample { def main(args: Array[String]): Unit = { val conf = new SparkConf().setAppName("PCAExample") val sc = new SparkContext(conf) // $example on$ val data = sc.textFile("data/mllib/ridge-data/lpsa.data").map { line => val parts = line.split(',') LabeledPoint(parts(0).toDouble, Vectors.dense(parts(1).split(' ').map(_.toDouble))) }.cache() val splits = data.randomSplit(Array(0.6, 0.4), seed = 11L) val training = splits(0).cache() val test = splits(1) val pca = new PCA(training.first().features.size / 2).fit(data.map(_.features)) val training_pca = training.map(p => p.copy(features = pca.transform(p.features))) val test_pca = test.map(p => p.copy(features = pca.transform(p.features))) val numIterations = 100 val model = LinearRegressionWithSGD.train(training, numIterations) val model_pca = LinearRegressionWithSGD.train(training_pca, numIterations) val valuesAndPreds = test.map { point => val score = model.predict(point.features) (score, point.label) } val valuesAndPreds_pca = test_pca.map { point => val score = model_pca.predict(point.features) (score, point.label) } val MSE = valuesAndPreds.map { case (v, p) => math.pow((v - p), 2) }.mean() val MSE_pca = valuesAndPreds_pca.map { case (v, p) => math.pow((v - p), 2) }.mean() println(s"Mean Squared Error = $MSE") println(s"PCA Mean Squared Error = $MSE_pca") // $example off$ sc.stop() } } // scalastyle:on println
lhfei/spark-in-action
spark-2.x/src/main/scala/org/apache/spark/examples/ml/FeatureHasherExample.scala
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.spark.examples.ml // $example on$ import org.apache.spark.ml.feature.FeatureHasher // $example off$ import org.apache.spark.sql.SparkSession object FeatureHasherExample { def main(args: Array[String]): Unit = { val spark = SparkSession .builder .appName("FeatureHasherExample") .getOrCreate() // $example on$ val dataset = spark.createDataFrame(Seq( (2.2, true, "1", "foo"), (3.3, false, "2", "bar"), (4.4, false, "3", "baz"), (5.5, false, "4", "foo") )).toDF("real", "bool", "stringNum", "string") val hasher = new FeatureHasher() .setInputCols("real", "bool", "stringNum", "string") .setOutputCol("features") val featurized = hasher.transform(dataset) featurized.show(false) // $example off$ spark.stop() } }
lhfei/spark-in-action
spark-2.x/src/main/scala/cn/lhfei/spark/streaming/HdfsWordcount.scala
<gh_stars>1-10 package cn.lhfei.spark.streaming import org.apache.spark.SparkConf import org.apache.spark.streaming.{Seconds, StreamingContext} /** * Created by <NAME> on 2/28/2017. */ object HdfsWordcount { def main(args: Array[String]): Unit = { if(args.length < 1){ System.err.println("Usage: HdfsWordCount <input file directory>") System.exit(1) } val sparkConf = new SparkConf().setAppName("HdfsWordCount") val ssc = new StreamingContext(sparkConf, Seconds(5)) val lines = ssc.textFileStream(args(0)) val words = lines.flatMap(_.split(" ")) val wordCounts = words.map(x => (x, 1)).reduceByKey(_ + _) wordCounts.print() ssc.start() ssc.awaitTermination() } }
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/service/ArticleService.scala
<gh_stars>10-100 package com.hhandoko.realworld.service import java.time.ZonedDateTime import cats.Applicative import com.hhandoko.realworld.core.{Article, Author, Username} import com.hhandoko.realworld.service.query.Pagination trait ArticleService[F[_]] { import ArticleService.ArticleCount def getAll(pg: Pagination): F[(Vector[Article], ArticleCount)] } object ArticleService { type ArticleCount = Int def apply[F[_]: Applicative]: ArticleService[F] = new ArticleService[F] { import cats.implicits._ override def getAll(pg: Pagination): F[(Vector[Article], ArticleCount)] = { for { arts <- { Vector("world", "you") .map(mockArticles) .pure[F] } count = arts.size } yield { val result = if (count < pg.offset) Vector.empty[Article] else if (count < pg.offset + pg.limit) arts.slice(pg.offset, pg.limit) else arts.slice(pg.offset, pg.offset + pg.limit) (result, count) } } } private[this] def mockArticles(title: String): Article = Article( slug = s"hello-${title.toLowerCase}", title = title, description = title, body = title, tagList = Set.empty, createdAt = ZonedDateTime.now(), updatedAt = ZonedDateTime.now(), favorited = false, favoritesCount = 0, author = Author( username = Username("test"), bio = None, image = None, following = false ) ) }
hhandoko/scala-http4s-realworld-example-app
src/test/scala/com/hhandoko/realworld/route/UserRoutesSpec.scala
<reponame>hhandoko/scala-http4s-realworld-example-app package com.hhandoko.realworld.route import scala.concurrent.ExecutionContext import cats.effect.{ContextShift, IO} import org.http4s._ import org.http4s.implicits._ import org.specs2.Specification import org.specs2.matcher.MatchResult import com.hhandoko.realworld.auth.RequestAuthenticator import com.hhandoko.realworld.core.{JwtToken, User, Username} import com.hhandoko.realworld.route import com.hhandoko.realworld.service.UserService class UserRoutesSpec extends Specification { def is = s2""" User routes when logged in should return 200 OK status $currentUserReturns200 should return user info $currentUserReturnsUserInfo when not logged in should return 401 Unauthorized status $unauthorisedReturns401 """ private[this] val nonExpiringToken = JwtToken("<KEY>") private[this] val invalidToken = "invalid.jwt.token" private[this] val retCurrentUser: Response[IO] = { implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global) val getCurrentUser = Request[IO]( Method.GET, uri"/user", headers = Headers.of(Header("Authorization", s"Token ${nonExpiringToken.value}")) ) UserRoutes[IO](new RequestAuthenticator[IO], FakeUserService) .orNotFound(getCurrentUser) .unsafeRunSync() } private[this] val retUnauthorized: Response[IO] = { implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global) val getCurrentUser = Request[IO]( Method.GET, uri"/user", headers = Headers.of(Header("Authorization", s"Token ${invalidToken}")) ) route.UserRoutes[IO](new RequestAuthenticator[IO], FakeUserService) .orNotFound(getCurrentUser) .unsafeRunSync() } private[this] def currentUserReturns200: MatchResult[Status] = retCurrentUser.status must beEqualTo(Status.Ok) private[this] def currentUserReturnsUserInfo: MatchResult[String] = retCurrentUser.as[String].unsafeRunSync() must beEqualTo(s"""{"user":{"email":"<EMAIL>","token":"${nonExpiringToken.value}","username":"famous","bio":null,"image":null}}""") private[this] def unauthorisedReturns401: MatchResult[Status] = retUnauthorized.status must beEqualTo(Status.Unauthorized) object FakeUserService extends UserService[IO] { def get(username: Username): IO[Option[User]] = IO.pure { Some(User(username, None, None, s"${<EMAIL>", nonExpiringToken)) } } }
hhandoko/scala-http4s-realworld-example-app
project/plugins.sbt
<reponame>hhandoko/scala-http4s-realworld-example-app<gh_stars>10-100 // Load environment variables for local development // See: https://github.com/mefellows/sbt-dotenv addSbtPlugin("au.com.onegeek" %% "sbt-dotenv" % "2.1.204") // Check Maven and Ivy repositories for dependency updates // See: https://github.com/rtimush/sbt-updates addSbtPlugin("com.timushev.sbt" % "sbt-updates" % "0.5.3") // Build application distribution packages in native formats // See: https://github.com/sbt/sbt-native-packager addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.8.1") // Pass recommended Scala compiler flags // See: https://github.com/DavidGregory084/sbt-tpolecat addSbtPlugin("io.github.davidgregory084" % "sbt-tpolecat" % "0.1.17") // Flyway migrations support in SBT // See: https://github.com/flyway/flyway-sbt addSbtPlugin("io.github.davidmweber" % "flyway-sbt" % "5.2.0") // Enable app restarts for better development experience // See: https://github.com/spray/sbt-revolver addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
hhandoko/scala-http4s-realworld-example-app
src/test/scala/com/hhandoko/realworld/repository/ArticleRepoSpec.scala
<reponame>hhandoko/scala-http4s-realworld-example-app package com.hhandoko.realworld.repository import cats.effect.IO import doobie.implicits._ import doobie.specs2.IOChecker import org.specs2.mutable.Specification import com.hhandoko.realworld.RepoSpecSupport import com.hhandoko.realworld.core.Article class ArticleRepoSpec extends Specification with RepoSpecSupport with IOChecker { override def is = sequential ^ s2""" Article repository select query should return empty when there is no record $selectEmptyResult """ import ArticleRepo.Reader._ val instance = "article" private[this] val retSingleNoClause: IO[Vector[Article]] = ArticleRepo.select.query[Article].to[Vector].transact(transactor) private[this] def selectEmptyResult = retSingleNoClause.unsafeRunSync() must be empty }
hhandoko/scala-http4s-realworld-example-app
src/test/scala/com/hhandoko/realworld/route/ArticleRoutesSpec.scala
<filename>src/test/scala/com/hhandoko/realworld/route/ArticleRoutesSpec.scala<gh_stars>10-100 package com.hhandoko.realworld.route import java.time.ZonedDateTime import scala.concurrent.ExecutionContext import cats.effect.{ContextShift, IO} import org.http4s._ import org.http4s.implicits._ import org.specs2.Specification import org.specs2.matcher.MatchResult import com.hhandoko.realworld.core.{Article, Author, Username} import com.hhandoko.realworld.route import com.hhandoko.realworld.service.ArticleService import com.hhandoko.realworld.service.ArticleService.ArticleCount import com.hhandoko.realworld.service.query.Pagination class ArticleRoutesSpec extends Specification { def is = s2""" Article routes when retrieving all articles without query params when articles exist should return 200 OK status $hasArticlesReturn200 should return a list of articles $hasArticlesReturnList when no articles exist should return 200 OK status $noArticlesReturn200 should return empty array $noArticlesReturnsEmpty with pagination query params when articles exist and results are within the page should return 200 OK status $hasArticlesInPageReturn200 should return a list of articles $hasArticlesInPageReturnList and results are paged should return 200 OK status $hasArticlesMultiPageReturn200 should return a list of articles $hasArticlesMultiPageReturnList and results are outside the page should return 200 OK status $hasArticlesOutsidePageReturn200 should return empty array $hasArticlesOutsidePageReturnsEmpty when no articles exist with default offset and limit should return 200 OK status $noArticlesWithPaginationReturns200 should return empty array $noArticlesWithPaginationReturnsEmpty """ private[this] final val EMPTY_RESPONSE = """{"articles":[],"articlesCount":0}""" private[this] val retHasArticles: Response[IO] = { implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global) val articles = Vector(mockArticle("Hello"), mockArticle("World")) val getArticles = Request[IO](Method.GET, uri"/articles") ArticleRoutes[IO](new FakeArticleService(articles, articles.size)) .orNotFound(getArticles) .unsafeRunSync() } private[this] val retNoArticles: Response[IO] = { implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global) val getArticles = Request[IO](Method.GET, uri"/articles") route.ArticleRoutes[IO](new FakeArticleService(Vector.empty, 0)) .orNotFound(getArticles) .unsafeRunSync() } private[this] val retHasArticlesInPage: Pagination => Response[IO] = { pg => implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global) val articles = Vector(mockArticle("Hello"), mockArticle("World")) val getArticles = Request[IO](Method.GET, uri"/articles".+?("offset", pg.offset).+?("limit", pg.limit)) ArticleRoutes[IO](new FakeArticleService(articles, articles.size)) .orNotFound(getArticles) .unsafeRunSync() } private[this] val retHasArticlesMultiPage: Pagination => Response[IO] = { pg => implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global) val articles = Vector(mockArticle("World")) val getArticles = Request[IO](Method.GET, uri"/articles".+?("offset", pg.offset).+?("limit", pg.limit)) ArticleRoutes[IO](new FakeArticleService(articles, 2)) .orNotFound(getArticles) .unsafeRunSync() } private[this] val retHasArticlesOutsidePage: Pagination => Response[IO] = { pg => implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global) val getArticles = Request[IO](Method.GET, uri"/articles".+?("offset", pg.offset).+?("limit", pg.limit)) ArticleRoutes[IO](new FakeArticleService(Vector.empty, 2)) .orNotFound(getArticles) .unsafeRunSync() } private[this] val retNoArticlesWithPagination: Pagination => Response[IO] = { pg => implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global) val getArticles = Request[IO](Method.GET, uri"/articles".+?("offset", pg.offset).+?("limit", pg.limit)) route.ArticleRoutes[IO](new FakeArticleService(Vector.empty, 0)) .orNotFound(getArticles) .unsafeRunSync() } private[this] def hasArticlesReturn200: MatchResult[Status] = retHasArticles.status must beEqualTo(Status.Ok) private[this] def hasArticlesReturnList: MatchResult[String] = retHasArticles.as[String].unsafeRunSync() must beEqualTo("""{"articles":[{"slug":"some-title-hello","title":"Some Title: Hello","description":"Some description","body":"some text","tagList":[],"createdAt":"2019-05-21T21:17:25.092+08:00","updatedAt":"2019-05-21T21:17:25.092+08:00","favorited":false,"favoritesCount":0,"author":{"username":"john-doe","bio":null,"image":null,"following":false}},{"slug":"some-title-world","title":"Some Title: World","description":"Some description","body":"some text","tagList":[],"createdAt":"2019-05-21T21:17:25.092+08:00","updatedAt":"2019-05-21T21:17:25.092+08:00","favorited":false,"favoritesCount":0,"author":{"username":"john-doe","bio":null,"image":null,"following":false}}],"articlesCount":2}""") private[this] def noArticlesReturn200: MatchResult[Status] = retNoArticles.status must beEqualTo(Status.Ok) private[this] def noArticlesReturnsEmpty: MatchResult[String] = retNoArticles.as[String].unsafeRunSync() must beEqualTo(EMPTY_RESPONSE) private[this] def hasArticlesInPageReturn200: MatchResult[Status] = retHasArticlesInPage(Pagination(limit = 2)).status must beEqualTo(Status.Ok) private[this] def hasArticlesInPageReturnList: MatchResult[String] = retHasArticlesInPage(Pagination(limit = 2)).as[String].unsafeRunSync() must beEqualTo("""{"articles":[{"slug":"some-title-hello","title":"Some Title: Hello","description":"Some description","body":"some text","tagList":[],"createdAt":"2019-05-21T21:17:25.092+08:00","updatedAt":"2019-05-21T21:17:25.092+08:00","favorited":false,"favoritesCount":0,"author":{"username":"john-doe","bio":null,"image":null,"following":false}},{"slug":"some-title-world","title":"Some Title: World","description":"Some description","body":"some text","tagList":[],"createdAt":"2019-05-21T21:17:25.092+08:00","updatedAt":"2019-05-21T21:17:25.092+08:00","favorited":false,"favoritesCount":0,"author":{"username":"john-doe","bio":null,"image":null,"following":false}}],"articlesCount":2}""") private[this] def hasArticlesMultiPageReturn200: MatchResult[Status] = retHasArticlesMultiPage(Pagination(limit = 1, offset = 1)).status must beEqualTo(Status.Ok) private[this] def hasArticlesMultiPageReturnList: MatchResult[String] = retHasArticlesMultiPage(Pagination(limit = 1, offset = 1)).as[String].unsafeRunSync() must beEqualTo("""{"articles":[{"slug":"some-title-world","title":"Some Title: World","description":"Some description","body":"some text","tagList":[],"createdAt":"2019-05-21T21:17:25.092+08:00","updatedAt":"2019-05-21T21:17:25.092+08:00","favorited":false,"favoritesCount":0,"author":{"username":"john-doe","bio":null,"image":null,"following":false}}],"articlesCount":2}""") private[this] def hasArticlesOutsidePageReturn200: MatchResult[Status] = retHasArticlesOutsidePage(Pagination(limit = 10, offset = 1)).status must beEqualTo(Status.Ok) private[this] def hasArticlesOutsidePageReturnsEmpty: MatchResult[String] = retHasArticlesOutsidePage(Pagination(limit = 10, offset = 1)).as[String].unsafeRunSync() must beEqualTo("""{"articles":[],"articlesCount":2}""") private[this] def noArticlesWithPaginationReturns200: MatchResult[Status] = retNoArticlesWithPagination(Pagination()).status must beEqualTo(Status.Ok) private[this] def noArticlesWithPaginationReturnsEmpty: MatchResult[String] = retNoArticlesWithPagination(Pagination()).as[String].unsafeRunSync() must beEqualTo(EMPTY_RESPONSE) private[this] def mockArticle(title: String): Article = Article( slug = s"some-title-${title.toLowerCase}", title = s"Some Title: $title", description = "Some description", body = "some text", tagList = Set.empty, createdAt = ZonedDateTime.parse("2019-05-21T21:17:25.092+08:00"), updatedAt = ZonedDateTime.parse("2019-05-21T21:17:25.092+08:00"), favorited = false, favoritesCount = 0L, author = Author( username = Username("john-doe"), bio = None, image = None, following = false ) ) class FakeArticleService(records: Vector[Article], count: ArticleCount) extends ArticleService[IO] { override def getAll(pg: Pagination): IO[(Vector[Article], ArticleCount)] = IO.pure((records, count)) } }
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/config/Config.scala
package com.hhandoko.realworld.config final case class Config(server: ServerConfig, db: DbConfig, log: LogConfig)
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/auth/RequestAuthenticator.scala
<gh_stars>10-100 package com.hhandoko.realworld.auth import cats.Monad import cats.data.{Kleisli, OptionT} import org.http4s.server.AuthMiddleware import org.http4s.util.CaseInsensitiveString import org.http4s.{AuthedRoutes, Header, HttpRoutes, Request} import com.hhandoko.realworld.core.{JwtToken, Username} class RequestAuthenticator[F[_]: Monad] extends JwtSupport { private final val HEADER_NAME = CaseInsensitiveString("Authorization") private final val HEADER_VALUE_PREFIX = "Token" private final val HEADER_VALUE_SEPARATOR = " " private final val HEADER_VALUE_START_INDEX = HEADER_VALUE_PREFIX.length + HEADER_VALUE_SEPARATOR.length private val authUser = Kleisli[OptionT[F, *], Request[F], Username] { req => OptionT.fromOption { req.headers .find(authorizationHeader) .map(getTokenValue) .flatMap(decodeToken) } } private val middleware = AuthMiddleware(authUser) def apply(authedService: AuthedRoutes[Username, F]): HttpRoutes[F] = middleware(authedService) private[this] def authorizationHeader(header: Header): Boolean = header.name == HEADER_NAME && header.value.startsWith(HEADER_VALUE_PREFIX + HEADER_VALUE_SEPARATOR) private[this] def getTokenValue(header: Header): JwtToken = JwtToken(header.value.substring(HEADER_VALUE_START_INDEX)) }
hhandoko/scala-http4s-realworld-example-app
src/test/scala/com/hhandoko/realworld/route/TagRoutesSpec.scala
<reponame>hhandoko/scala-http4s-realworld-example-app<gh_stars>10-100 package com.hhandoko.realworld.route import scala.concurrent.ExecutionContext import cats.effect.{ContextShift, IO} import org.http4s._ import org.http4s.implicits._ import org.specs2.Specification import org.specs2.matcher.MatchResult import com.hhandoko.realworld.core.Tag import com.hhandoko.realworld.service.TagService class TagRoutesSpec extends Specification { def is = s2""" Tag routes should return 200 OK status $returns200 should return an array of 'tags' $returnsTagArray """ private[this] val retAllTags: Response[IO] = { implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global) val tags = Vector(Tag("hello"), Tag("world")) val getAllTags = Request[IO](Method.GET, uri"/tags") TagRoutes[IO](new FakeTagService(tags)) .orNotFound(getAllTags) .unsafeRunSync() } private[this] def returns200: MatchResult[Status] = retAllTags.status must beEqualTo(Status.Ok) private[this] def returnsTagArray: MatchResult[String] = retAllTags.as[String].unsafeRunSync() must beEqualTo("""{"tags":["hello","world"]}""") class FakeTagService(tags: Vector[Tag]) extends TagService[IO] { override def getAll: IO[Vector[Tag]] = IO.pure(tags) } }
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/util/LazyInitRollingFileAppender.scala
package com.hhandoko.realworld.util import java.util.concurrent.atomic.AtomicBoolean import ch.qos.logback.core.rolling.RollingFileAppender import org.graalvm.nativeimage.ImageInfo /** * RollingFileAppender with lazy initialization on GraalVM native image. * * Logback's rolling file appended does not work with Graal native image out of * the box. Reflection config has been added on `reflect-config.json` as well * to make this work. * * See: * - https://github.com/oracle/graal/issues/1323 * - https://gist.github.com/begrossi/d807280f54d3378d407e9c9a95e5d905 * * @tparam T Event object type parameter. */ class LazyInitRollingFileAppender[T] extends RollingFileAppender[T] { private[this] val started: AtomicBoolean = new AtomicBoolean(false) override def start(): Unit = if (!ImageInfo.inImageBuildtimeCode()) { super.start() this.started.set(true) } override def doAppend(eventObject: T): Unit = if (!ImageInfo.inImageBuildtimeCode()) { if (!this.started.get()) maybeStart() super.doAppend(eventObject) } /** * Synchronised method to avoid double start from `doAppender()`. */ private[this] def maybeStart(): Unit = { lock.lock() try { if (!this.started.get()) this.start() } finally { lock.unlock() } } }
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/config/ServerConfig.scala
package com.hhandoko.realworld.config final case class ServerConfig(host: String, port: Int)
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/route/common/UserResponse.scala
package com.hhandoko.realworld.route.common import io.circe.{Encoder, Json} import org.http4s.circe.jsonEncoderOf import org.http4s.EntityEncoder final case class UserResponse( email: String, token: String, username: String, bio: Option[String], image: Option[String] ) object UserResponse { implicit val encoder: Encoder[UserResponse] = (r: UserResponse) => Json.obj( "user" -> Json.obj( "email" -> Json.fromString(r.email), "token" -> Json.fromString(r.token), "username" -> Json.fromString(r.username), "bio" -> r.bio.fold(Json.Null)(Json.fromString), "image" -> r.image.fold(Json.Null)(Json.fromString) ) ) implicit def entityEncoder[F[_]]: EntityEncoder[F, UserResponse] = jsonEncoderOf[F, UserResponse] }
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/core/Username.scala
<reponame>hhandoko/scala-http4s-realworld-example-app<filename>src/main/scala/com/hhandoko/realworld/core/Username.scala package com.hhandoko.realworld.core final case class Username(value: String) extends AnyVal
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/route/TagRoutes.scala
<gh_stars>10-100 package com.hhandoko.realworld.route import cats.effect.Sync import cats.implicits._ import io.circe.{Encoder, Json} import org.http4s.circe.jsonEncoderOf import org.http4s.dsl.Http4sDsl import org.http4s.{EntityEncoder, HttpRoutes} import com.hhandoko.realworld.core.Tag import com.hhandoko.realworld.service.TagService object TagRoutes { def apply[F[_]: Sync](tagService: TagService[F]): HttpRoutes[F] = { object dsl extends Http4sDsl[F]; import dsl._ HttpRoutes.of[F] { case GET -> Root / "tags" => for { tags <- tagService.getAll res <- Ok(AllTagsResponse(tags)) } yield res } } final case class AllTagsResponse(tags: Vector[Tag]) object AllTagsResponse { implicit val encoder: Encoder[AllTagsResponse] = (r: AllTagsResponse) => Json.obj( "tags" -> Json.fromValues(r.tags.map(_.value).map(Json.fromString)) ) implicit def entityEncoder[F[_]]: EntityEncoder[F, AllTagsResponse] = jsonEncoderOf[F, AllTagsResponse] } }
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/route/UserRoutes.scala
package com.hhandoko.realworld.route import cats.effect.Sync import cats.implicits._ import org.http4s.dsl.Http4sDsl import org.http4s.{AuthedRoutes, HttpRoutes} import com.hhandoko.realworld.auth.RequestAuthenticator import com.hhandoko.realworld.core.Username import com.hhandoko.realworld.route.common.UserResponse import com.hhandoko.realworld.service.UserService object UserRoutes { def apply[F[_]: Sync](authenticated: RequestAuthenticator[F], userService: UserService[F]): HttpRoutes[F] = { object dsl extends Http4sDsl[F]; import dsl._ authenticated { AuthedRoutes.of[Username, F] { case GET -> Root / "user" as username => for { usrOpt <- userService.get(username) res <- usrOpt.fold(NotFound()) { usr => Ok(UserResponse(usr.email, usr.token.value, usr.username.value, usr.bio, usr.image)) } } yield res } } } }
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/auth/JwtSupport.scala
<reponame>hhandoko/scala-http4s-realworld-example-app package com.hhandoko.realworld.auth import scala.util.Try import com.auth0.jwt.JWT import com.auth0.jwt.algorithms.Algorithm import com.hhandoko.realworld.core.{JwtToken, Username} trait JwtSupport { final val CLAIM_USERNAME = "username" // TODO: Move to configuration final val ISSUER = "realworld" final val SECRET = "S3cret!" final val VALIDITY_DURATION = 3600 final val ALGO = Algorithm.HMAC256(SECRET) final lazy val verifier = JWT.require(ALGO).withIssuer(ISSUER).build() def encodeToken(username: Username): JwtToken = JwtToken(generateToken(username)) // FIXME: Token decoding failed on Graal native image distribution def decodeToken(token: JwtToken): Option[Username] = { // TODO: Log exception // Throws JWTVerificationException Try(verifier.verify(token.value)) .map(_.getClaim(CLAIM_USERNAME).asString()) .map(Username) .toOption } private[this] def generateToken(username: Username): String = // `realworld` requirements does not mention JWT expiry, thus this token is valid forever // TODO: Use Either.catchNonFatal // Throws IllegalArgumentException and JWTCreationException JWT.create() .withIssuer(ISSUER) // Private claims .withClaim(CLAIM_USERNAME, username.value) .sign(ALGO) }
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/service/ProfileService.scala
package com.hhandoko.realworld.service import cats.Applicative import com.hhandoko.realworld.core.{Profile, Username} trait ProfileService[F[_]] { def get(username: Username): F[Option[Profile]] } object ProfileService { def apply[F[_]: Applicative]: ProfileService[F] = new ProfileService[F] { import cats.implicits._ def get(username: Username): F[Option[Profile]] = { val result = if (username.value.startsWith("celeb_")) Some(Profile(username, None, None)) else None result.pure[F] } } }
hhandoko/scala-http4s-realworld-example-app
src/test/scala/com/hhandoko/realworld/route/ProfileRoutesSpec.scala
package com.hhandoko.realworld.route import scala.concurrent.ExecutionContext import cats.effect.{ContextShift, IO} import org.http4s._ import org.http4s.implicits._ import org.specs2.Specification import org.specs2.matcher.MatchResult import com.hhandoko.realworld.core.{Profile, Username} import com.hhandoko.realworld.route import com.hhandoko.realworld.service.ProfileService class ProfileRoutesSpec extends Specification { def is = s2""" Profile routes when record exists should return 200 OK status $foundReturns200 should return profile $foundReturnsProfile when record does not exists should return 404 Not Found $notFoundReturns404 """ private[this] val retFoundProfile: Response[IO] = { implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global) val getProfile = Request[IO](Method.GET, uri"/profiles/celeb_1") ProfileRoutes[IO](FakeProfileService) .orNotFound(getProfile) .unsafeRunSync() } private[this] val retNotFoundProfile: Response[IO] = { implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global) val getProfile = Request[IO](Method.GET, uri"/profile/abc") route.ProfileRoutes[IO](FakeProfileService) .orNotFound(getProfile) .unsafeRunSync() } private[this] def foundReturns200: MatchResult[Status] = retFoundProfile.status must beEqualTo(Status.Ok) private[this] def foundReturnsProfile: MatchResult[String] = retFoundProfile.as[String].unsafeRunSync() must beEqualTo("""{"profile":{"username":"celeb_1","bio":null,"image":null,"following":false}}""") private[this] def notFoundReturns404: MatchResult[Status] = retNotFoundProfile.status must beEqualTo(Status.NotFound) object FakeProfileService extends ProfileService[IO] { override def get(username: Username): IO[Option[Profile]] = IO.pure { if (username.value.startsWith("celeb_")) Some(Profile(username, None, None)) else None } } }
hhandoko/scala-http4s-realworld-example-app
src/test/scala/com/hhandoko/realworld/RepoSpecSupport.scala
package com.hhandoko.realworld import java.util.UUID import javax.sql.DataSource import cats.effect.{ContextShift, IO, Resource} import doobie.implicits._ import doobie.util.ExecutionContexts import doobie.util.fragment.Fragment import doobie.util.transactor.Transactor import org.flywaydb.core.Flyway import org.h2.jdbcx.JdbcDataSource import org.specs2.specification.{BeforeAll, BeforeEach} trait RepoSpecSupport extends BeforeAll with BeforeEach { def instance: String private[this] final val TABLES = Seq("profile", "auth", "article") private[this] final val SCHEMA_LOCATION = "filesystem:db/migration/h2" private[this] final val DRIVER_CLASS_NAME = "org.h2.Driver" private[this] final val USERNAME = "sa" private[this] final val PASSWORD = "" implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContexts.synchronous) lazy final val url: String = s"jdbc:h2:mem:${instance}_test_${UUID.randomUUID().toString};MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1" lazy final val ds: DataSource = new JdbcDataSource { this.setUrl(url) this.setUser(USERNAME) this.setPassword(PASSWORD) } lazy final val transactor = Transactor.fromDriverManager[IO](DRIVER_CLASS_NAME, url, USERNAME, PASSWORD) def beforeAll(): Unit = { Flyway.configure() .dataSource(ds) .locations(SCHEMA_LOCATION) .load() .migrate() () } def before: Unit = Resource.fromAutoCloseable(IO(ds.getConnection())).use { conn => IO { TABLES .reverse .foreach { tableName => conn.nativeSQL(s"TRUNCATE TABLE ${tableName} RESTART IDENTITY") conn.commit() } } }.unsafeRunSync() protected def execute(fr: Fragment): Unit = { fr.update.run.transact(transactor).unsafeRunSync() () } }
hhandoko/scala-http4s-realworld-example-app
build.sbt
<filename>build.sbt enablePlugins(FlywayPlugin) enablePlugins(JavaAppPackaging) lazy val realworld = (project in file(".")) .settings(Common.settings: _*)
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/config/DbConfig.scala
<filename>src/main/scala/com/hhandoko/realworld/config/DbConfig.scala package com.hhandoko.realworld.config final case class DbConfig( driver: String, url: String, user: String, password: String, pool: Int )
hhandoko/scala-http4s-realworld-example-app
src/test/scala/com/hhandoko/realworld/route/query/PaginationSpec.scala
package com.hhandoko.realworld.route.query import org.specs2.Specification import org.specs2.matcher.MatchResult import com.hhandoko.realworld.service.query.Pagination class PaginationSpec extends Specification { def is = s2""" Pagination query params object when limit and offset is not defined should use default limit $paginationUseDefaultLimit should use default offset $paginationUseDefaultOffset when either limit or offset is defined should use provided limit $paginationUseLimit should use provided offset $paginationUseOffset when both limit and offset is defined should use provided limit $paginationUseLimitFromLimitAndOffset should use provided offset $paginationUseOffsetFromLimitAndOffset when either invalid limit or offset is defined should use default limit $paginationInvalidLimitUseDefault should use default offset $paginationInvalidOffsetUseDefault when both invalid limit or offset is defined should use default limit $paginationInvalidLimitAndOffsetUseDefaultLimit should use default offset $paginationInvalidLimitAndOffsetUseDefaultOffset """ val limit = 100 val offset = 100 private[this] val paginationUseDefault: Pagination = Pagination(None, None) private[this] val paginationUseProvided: Pagination = Pagination(limit = Some(limit), offset = Some(offset)) private[this] val paginationUseProvidedInvalid: Pagination = Pagination(limit = Some(-100), offset = Some(-100)) private[this] def paginationUseDefaultLimit: MatchResult[Int] = paginationUseDefault.limit must beEqualTo(Pagination.DEFAULT_LIMIT) private[this] def paginationUseDefaultOffset: MatchResult[Int] = paginationUseDefault.offset must beEqualTo(Pagination.DEFAULT_OFFSET) private[this] def paginationUseLimit: MatchResult[Int] = Pagination(limit = Some(limit), offset = None).limit must beEqualTo(limit) private[this] def paginationUseOffset: MatchResult[Int] = Pagination(limit = None, offset = Some(offset)).offset must beEqualTo(offset) private[this] def paginationUseLimitFromLimitAndOffset: MatchResult[Int] = paginationUseProvided.limit must beEqualTo(limit) private[this] def paginationUseOffsetFromLimitAndOffset: MatchResult[Int] = paginationUseProvided.offset must beEqualTo(offset) private[this] def paginationInvalidLimitUseDefault: MatchResult[Int] = Pagination(limit = Some(-100), offset = None).limit must beEqualTo(Pagination.DEFAULT_LIMIT) private[this] def paginationInvalidOffsetUseDefault: MatchResult[Int] = Pagination(limit = None, offset = Some(-100)).offset must beEqualTo(Pagination.DEFAULT_OFFSET) private[this] def paginationInvalidLimitAndOffsetUseDefaultLimit: MatchResult[Int] = paginationUseProvidedInvalid.limit must beEqualTo(Pagination.DEFAULT_LIMIT) private[this] def paginationInvalidLimitAndOffsetUseDefaultOffset: MatchResult[Int] = paginationUseProvidedInvalid.offset must beEqualTo(Pagination.DEFAULT_OFFSET) }
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/route/AuthRoutes.scala
<filename>src/main/scala/com/hhandoko/realworld/route/AuthRoutes.scala package com.hhandoko.realworld.route import cats.effect.Sync import cats.implicits._ import io.circe.generic.auto._ import org.http4s.circe.{jsonEncoderOf, jsonOf} import org.http4s.dsl.Http4sDsl import org.http4s.{EntityEncoder, HttpRoutes} import com.hhandoko.realworld.auth.UnauthorizedResponseSupport import com.hhandoko.realworld.route.common.UserResponse import com.hhandoko.realworld.service.AuthService object AuthRoutes extends UnauthorizedResponseSupport { def apply[F[_]: Sync](authService: AuthService[F]): HttpRoutes[F] = { object dsl extends Http4sDsl[F]; import dsl._ implicit val loginPostDecoder = jsonOf[F, LoginPost] HttpRoutes.of[F] { // TODO: Implement login form data validation case req @ POST -> Root / "users" / "login" => for { data <- req.as[LoginPost] authed <- authService.verify(data.user.email, data.user.password) res <- authed.fold( err => Unauthorized(withChallenge(err)), usr => Ok(UserResponse(usr.email, usr.token.value, usr.username.value, usr.bio, usr.image)) ) } yield res } } final case class LoginPost(user: LoginPostPayload) object LoginPost { implicit def entityEncoder[F[_]]: EntityEncoder[F, LoginPost] = jsonEncoderOf[F, LoginPost] } final case class LoginPostPayload(email: String, password: String) }
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/service/UserService.scala
package com.hhandoko.realworld.service import cats.Applicative import com.hhandoko.realworld.auth.JwtSupport import com.hhandoko.realworld.core.{User, Username} trait UserService[F[_]] { def get(username: Username): F[Option[User]] } object UserService extends JwtSupport { def apply[F[_]: Applicative]: UserService[F] = new UserService[F] { import cats.implicits._ def get(username: Username): F[Option[User]] = { Option( User( email = s"<EMAIL>", token = encodeToken(username), username = username, bio = None, image = None ) ).pure[F] } } }
hhandoko/scala-http4s-realworld-example-app
src/test/scala/com/hhandoko/realworld/repository/UserRepoSpec.scala
package com.hhandoko.realworld.repository import cats.effect.IO import doobie.implicits._ import doobie.specs2.IOChecker import org.specs2.mutable.Specification import com.hhandoko.realworld.RepoSpecSupport import com.hhandoko.realworld.core.{Profile, Username} class UserRepoSpec extends Specification with RepoSpecSupport with IOChecker { override def is = sequential ^ s2""" User repository select query should return empty when there is no record $selectEmptyResult return a record if exists $selectSingleResult find query should return empty when no matching username is found $foundNoUsername return User info if found $foundUsername """ val instance = "user" private[this] val retSingleNoClause: IO[Option[Profile]] = UserRepo.select.query[Profile].option.transact(transactor) private[this] val retSingleByUsername: IO[Option[Profile]] = UserRepo(transactor).find(Username("test2")) private[this] def selectEmptyResult = retSingleNoClause.unsafeRunSync() must beNone private[this] def selectSingleResult = { execute(sql"""INSERT INTO profile (username, email) VALUES ('test', '<EMAIL>')""") retSingleNoClause.unsafeRunSync() must not beNone } private[this] def foundNoUsername = retSingleByUsername.unsafeRunSync() must beNone private[this] def foundUsername = { execute(sql"""INSERT INTO profile (username, email) VALUES ('test2', '<EMAIL>')""") val Some(result) = retSingleByUsername.unsafeRunSync() result.username must_== Username("test2") //result.email must_== "<EMAIL>" } }
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/service/query/Pagination.scala
package com.hhandoko.realworld.service.query import com.hhandoko.realworld.service.query.Pagination.{DEFAULT_LIMIT, DEFAULT_OFFSET} /** See: https://github.com/gothinkster/realworld/tree/master/api#list-articles */ final case class Pagination(limit: Int = DEFAULT_LIMIT, offset: Int = DEFAULT_OFFSET) object Pagination { final val DEFAULT_LIMIT = 20 final val DEFAULT_OFFSET = 0 def apply(limit: Option[Int], offset: Option[Int]): Pagination = { def sanitise(valueOpt: Option[Int], default: Int): Int = valueOpt match { case Some(value) if value >= 0 => value case _ => default } val sanitisedLimit = sanitise(limit, DEFAULT_LIMIT) val sanitisedOffset = sanitise(offset, DEFAULT_OFFSET) new Pagination(sanitisedLimit, sanitisedOffset) } }
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/core/Tag.scala
package com.hhandoko.realworld.core final case class Tag(value: String) extends AnyVal
hhandoko/scala-http4s-realworld-example-app
src/test/scala/com/hhandoko/realworld/auth/JwtSupportSpec.scala
<reponame>hhandoko/scala-http4s-realworld-example-app<gh_stars>10-100 package com.hhandoko.realworld.auth import scala.util.Random import org.specs2.Specification import org.specs2.matcher.MatchResult import com.hhandoko.realworld.core.{JwtToken, Username} class JwtSupportSpec extends Specification { def is = s2""" JWT support trait should generate token with valid username $tokenHasValidUsername """ object JwtTokenTester extends JwtSupport private val username = (1 to 10).map(_ => Random.alphanumeric).mkString private[this] val tokenToTest: JwtToken = JwtTokenTester.encodeToken(Username(username)) private[this] def tokenHasValidUsername: MatchResult[Option[Username]] = JwtTokenTester.decodeToken(tokenToTest) must beSome(Username(username)) }
hhandoko/scala-http4s-realworld-example-app
src/test/scala/com/hhandoko/realworld/route/AuthRoutesSpec.scala
<gh_stars>10-100 package com.hhandoko.realworld.route import scala.concurrent.ExecutionContext import cats.effect.{ContextShift, IO} import cats.implicits._ import org.http4s.implicits._ import org.http4s.{Method, Request, Response, Status} import org.specs2.Specification import org.specs2.matcher.MatchResult import com.hhandoko.realworld.core.{JwtToken, User, Username} import com.hhandoko.realworld.route import com.hhandoko.realworld.route.AuthRoutes.{LoginPost, LoginPostPayload} import com.hhandoko.realworld.service.AuthService class AuthRoutesSpec extends Specification { def is = s2""" Auth routes on successful login should return 200 OK status $successReturns200 should return user info $successReturnsUserInfo on failed login should return 401 Unauthorized status $failedReturns401 """ private[this] val retSuccessLogin: Response[IO] = { implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global) val email = "<EMAIL>" val payload = LoginPost(LoginPostPayload(email, "ABC123")) val postLogin = Request[IO](Method.POST, uri"/users/login").withEntity(payload) AuthRoutes[IO](new FakeAuthService(email)) .orNotFound(postLogin) .unsafeRunSync() } private[this] val retFailedLogin: Response[IO] = { implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global) val email = "<EMAIL>" val payload = LoginPost(LoginPostPayload("<EMAIL>", "ABC123")) val postLogin = Request[IO](Method.POST, uri"/users/login").withEntity(payload) route.AuthRoutes[IO](new FakeAuthService(email)) .orNotFound(postLogin) .unsafeRunSync() } private[this] def successReturns200: MatchResult[Status] = retSuccessLogin.status must beEqualTo(Status.Ok) private[this] def successReturnsUserInfo: MatchResult[String] = { val expected = """{"user":{"email":"<EMAIL>","token":"<PASSWORD>.token","username":"me","bio":null,"image":null}}""" retSuccessLogin.as[String].unsafeRunSync() must beEqualTo(expected) } private[this] def failedReturns401: MatchResult[Status] = retFailedLogin.status must beEqualTo(Status.Unauthorized) class FakeAuthService(savedEmail: String) extends AuthService[IO] { override def verify(email: Email, password: Password): IO[Either[String, User]] = { val successResponse = User(Username("me"), None, None, savedEmail, JwtToken("this.jwt.token")) val failedResponse = "Invalid username and password combination" if (email == savedEmail) IO.pure(Either.right(successResponse)) else IO.pure(Either.left(failedResponse)) } } }
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/route/ProfileRoutes.scala
<reponame>hhandoko/scala-http4s-realworld-example-app package com.hhandoko.realworld.route import cats.effect.Sync import cats.implicits._ import io.circe.{Encoder, Json} import org.http4s.circe.jsonEncoderOf import org.http4s.dsl.Http4sDsl import org.http4s.{EntityEncoder, HttpRoutes} import com.hhandoko.realworld.core.Username import com.hhandoko.realworld.service.ProfileService object ProfileRoutes { def apply[F[_]: Sync](profileService: ProfileService[F]): HttpRoutes[F] = { object dsl extends Http4sDsl[F]; import dsl._ HttpRoutes.of[F] { case GET -> Root / "profiles" / username => for { prfOpt <- profileService.get(Username(username)) res <- prfOpt.fold(NotFound()) { prf => Ok(ProfileResponse(prf.username.value, prf.bio, prf.image, following = false)) } } yield res } } final case class ProfileResponse(username: String, bio: Option[String], image: Option[String], following: Boolean) object ProfileResponse { implicit val encoder: Encoder[ProfileResponse] = (r: ProfileResponse) => Json.obj( "profile" -> Json.obj( "username" -> Json.fromString(r.username), "bio" -> r.bio.fold(Json.Null)(Json.fromString), "image" -> r.image.fold(Json.Null)(Json.fromString), "following" -> Json.fromBoolean(r.following) ) ) implicit def entityEncoder[F[_]]: EntityEncoder[F, ProfileResponse] = jsonEncoderOf[F, ProfileResponse] } }
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/service/TagService.scala
package com.hhandoko.realworld.service import cats.Applicative import com.hhandoko.realworld.core.Tag trait TagService[F[_]] { def getAll: F[Vector[Tag]] } object TagService { def apply[F[_]: Applicative]: TagService[F] = new TagService[F] { import cats.implicits._ def getAll: F[Vector[Tag]] = Vector("hello", "world") .map(Tag) .pure[F] } }
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/service/AuthService.scala
package com.hhandoko.realworld.service import cats.Applicative import com.hhandoko.realworld.auth.JwtSupport import com.hhandoko.realworld.core.{User, Username} trait AuthService[F[_]] { type Email = String type Password = String def verify(email: Email, password: Password): F[Either[String, User]] } object AuthService extends JwtSupport { def apply[F[_]: Applicative]: AuthService[F] = new AuthService[F] { import cats.implicits._ override def verify(email: Email, password: Password): F[Either[String, User]] = { // TODO: Consolidate with UserService email.split('@').toVector match { case localPart +: _ => { val username = Username(localPart) Either.right(User(username, bio = None, image = None, email, encodeToken(username))) } case _ => // TODO: Create User authentication error ADTs Either.left("Invalid email format") } }.pure[F] } }
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/core/Profile.scala
package com.hhandoko.realworld.core sealed trait ProfileAttributes { def username: Username def bio: Option[String] def image: Option[String] } final case class Profile( username: Username, bio: Option[String], image: Option[String] ) extends ProfileAttributes final case class User( username: Username, bio: Option[String], image: Option[String], email: String, token: JwtToken, ) extends ProfileAttributes final case class Author( username: Username, bio: Option[String], image: Option[String], following: Boolean ) extends ProfileAttributes
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/Server.scala
<reponame>hhandoko/scala-http4s-realworld-example-app<filename>src/main/scala/com/hhandoko/realworld/Server.scala package com.hhandoko.realworld import scala.concurrent.ExecutionContext import cats.effect.{Async, Blocker, ConcurrentEffect, ContextShift, Resource, Sync, Timer} import cats.implicits._ import doobie.hikari.HikariTransactor import doobie.util.ExecutionContexts import org.http4s.HttpRoutes import org.http4s.server.blaze.BlazeServerBuilder import org.http4s.server.middleware.Logger import org.http4s.server.{Router, Server => BlazeServer} import pureconfig.module.catseffect.loadConfigF import com.hhandoko.realworld.auth.RequestAuthenticator import com.hhandoko.realworld.config.{Config, DbConfig, LogConfig, ServerConfig} import com.hhandoko.realworld.route.{ArticleRoutes, AuthRoutes, ProfileRoutes, TagRoutes, UserRoutes} import com.hhandoko.realworld.service.{ArticleService, AuthService, ProfileService, TagService, UserService} object Server { def run[F[_]: ConcurrentEffect: ContextShift: Timer]: Resource[F, BlazeServer[F]] = { val articleService = ArticleService[F] val authService = AuthService[F] val profileService = ProfileService[F] val tagService = TagService[F] val userService = UserService[F] val authenticator = new RequestAuthenticator[F]() val routes = ArticleRoutes[F](articleService) <+> AuthRoutes[F](authService) <+> ProfileRoutes[F](profileService) <+> TagRoutes[F](tagService) <+> UserRoutes[F](authenticator, userService) for { conf <- config[F] _ <- transactor[F](conf.db) rts = Router("api" -> loggedRoutes(conf.log, routes)) svr <- server[F](conf.server, rts) } yield svr } private[this] def config[F[_]: ContextShift: Sync]: Resource[F, Config] = { import pureconfig.generic.auto._ for { blocker <- Blocker[F] config <- Resource.eval(loadConfigF[F, Config](blocker)) } yield config } private[this] def loggedRoutes[F[_]: ConcurrentEffect](config: LogConfig, routes: HttpRoutes[F]): HttpRoutes[F] = Logger.httpRoutes(config.httpHeader, config.httpBody) { routes } private[this] def server[F[_]: ConcurrentEffect: Timer]( config: ServerConfig, routes: HttpRoutes[F] ): Resource[F, BlazeServer[F]] = { import org.http4s.implicits._ BlazeServerBuilder[F](ExecutionContext.global) .bindHttp(config.port, config.host) .withHttpApp(routes.orNotFound) .resource } private[this] def transactor[F[_]: Async: ContextShift](config: DbConfig): Resource[F, HikariTransactor[F]] = for { ce <- ExecutionContexts.fixedThreadPool(config.pool) be <- Blocker[F] tx <- HikariTransactor.newHikariTransactor( config.driver, config.url, config.user, config.password, ce, be) } yield tx }
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/Application.scala
<filename>src/main/scala/com/hhandoko/realworld/Application.scala package com.hhandoko.realworld import cats.effect.{ExitCode, IO, IOApp} object Application extends IOApp { override def run(args: List[String]): IO[ExitCode] = Server.run[IO] .use(_ => IO.never) .as(ExitCode.Success) }
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/route/ArticleRoutes.scala
package com.hhandoko.realworld.route import java.time.format.DateTimeFormatter import cats.effect.Sync import cats.implicits._ import io.circe.{Encoder, Json} import org.http4s.circe.jsonEncoderOf import org.http4s.dsl.Http4sDsl import org.http4s.dsl.impl.OptionalQueryParamDecoderMatcher import org.http4s.{EntityEncoder, HttpRoutes} import com.hhandoko.realworld.core.Article import com.hhandoko.realworld.service.ArticleService import com.hhandoko.realworld.service.ArticleService.ArticleCount import com.hhandoko.realworld.service.query.Pagination object ArticleRoutes { def apply[F[_]: Sync](articleService: ArticleService[F]): HttpRoutes[F] = { object dsl extends Http4sDsl[F]; import dsl._ HttpRoutes.of[F] { case GET -> Root / "articles" :? LimitQuery(limitOpt) +& OffsetQuery(offsetOpt) => for { artsWithCount <- articleService.getAll(Pagination(limitOpt, offsetOpt)) res <- Ok(ArticlesResponse(artsWithCount._1, artsWithCount._2)) } yield res } } object LimitQuery extends OptionalQueryParamDecoderMatcher[Int]("limit") object OffsetQuery extends OptionalQueryParamDecoderMatcher[Int]("offset") final case class ArticlesResponse(articles: Vector[Article], count: ArticleCount) object ArticlesResponse { implicit val encoder: Encoder[ArticlesResponse] = (r: ArticlesResponse) => Json.obj( "articles" -> Json.fromValues( r.articles.map { a => Json.obj( "slug" -> Json.fromString(a.slug), "title" -> Json.fromString(a.title), "description" -> Json.fromString(a.description), "body" -> Json.fromString(a.body), "tagList" -> Json.fromValues(a.tagList.map(Json.fromString)), "createdAt" -> Json.fromString(a.createdAt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)), "updatedAt" -> Json.fromString(a.updatedAt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)), "favorited" -> Json.fromBoolean(a.favorited), "favoritesCount" -> Json.fromLong(a.favoritesCount), "author" -> Json.obj( "username" -> Json.fromString(a.author.username.value), "bio" -> a.author.bio.fold(Json.Null)(Json.fromString), "image" -> a.author.image.fold(Json.Null)(Json.fromString), "following" -> Json.fromBoolean(a.author.following) ) ) } ), "articlesCount" -> Json.fromInt(r.count) ) implicit def entityEncoder[F[_]]: EntityEncoder[F, ArticlesResponse] = jsonEncoderOf[F, ArticlesResponse] } }
hhandoko/scala-http4s-realworld-example-app
project/Common.scala
<reponame>hhandoko/scala-http4s-realworld-example-app import java.io.Closeable import scala.io.Source import io.github.davidmweber.FlywayPlugin.autoImport._ import sbt.Keys._ import sbt._ object Common { // Scala version private val scalaLibVersion = "2.13.5" // Dependency versions private val doobieVersion = "0.12.1" private val flywayVersion = "7.8.1" private val http4sVersion = "0.21.22" private val jansiVersion = "2.3.2" private val oauthJwtVersion = "3.15.0" private val pureConfigVersion = "0.14.1" // Transient dependency versions // ~ doobie private val h2Version = "1.4.200" private val postgresVersion = "42.2.19" // ~ http4s private val circeVersion = "0.13.0" private val logbackVersion = "1.2.3" private val specs2Version = "4.10.6" // Compiler plugin dependency versions private val betterMonadicForVersion = "0.3.1" private val kindProjectorVersion = "0.11.3" // Graal native-image compiler dependency versions private val graalVmVersion = "192.168.127.12" private val jnaVersion = "5.8.0" final val settings: Seq[Setting[_]] = projectSettings ++ dependencySettings ++ flywaySettings ++ compilerPlugins private[this] def projectSettings = Seq( organization := "com.hhandoko", name := "realworld", version := using(Source.fromFile("VERSION.txt")) { _.mkString }, scalaVersion := scalaLibVersion, mainClass in Compile := Some("com.hhandoko.realworld.Application") ) private[this] def dependencySettings = Seq( libraryDependencies ++= Seq( "ch.qos.logback" % "logback-classic" % logbackVersion, "com.auth0" % "java-jwt" % oauthJwtVersion, "com.github.pureconfig" %% "pureconfig" % pureConfigVersion, "com.github.pureconfig" %% "pureconfig-cats-effect" % pureConfigVersion, "com.h2database" % "h2" % h2Version % Test, "io.circe" %% "circe-generic" % circeVersion, "net.java.dev.jna" % "jna-platform" % jnaVersion, "org.fusesource.jansi" % "jansi" % jansiVersion, "org.flywaydb" % "flyway-core" % flywayVersion % Test, "org.graalvm.nativeimage" % "svm" % graalVmVersion % Provided, "org.http4s" %% "http4s-blaze-server" % http4sVersion, "org.http4s" %% "http4s-circe" % http4sVersion, "org.http4s" %% "http4s-dsl" % http4sVersion, "org.postgresql" % "postgresql" % postgresVersion, "org.specs2" %% "specs2-core" % specs2Version % Test, "org.tpolecat" %% "doobie-core" % doobieVersion, "org.tpolecat" %% "doobie-h2" % doobieVersion % Test, "org.tpolecat" %% "doobie-hikari" % doobieVersion, "org.tpolecat" %% "doobie-postgres" % doobieVersion, "org.tpolecat" %% "doobie-specs2" % doobieVersion % Test ) ) private[this] def compilerPlugins = Seq( // Add syntax for type lambdas // See: https://github.com/non/kind-projector addCompilerPlugin("org.typelevel" %% "kind-projector" % kindProjectorVersion cross CrossVersion.full), // Desugaring scala `for` without implicit `withFilter`s // See: https://github.com/oleg-py/better-monadic-for addCompilerPlugin("com.olegpy" %% "better-monadic-for" % betterMonadicForVersion) ) private[this] def flywaySettings = Seq( // Flyway database schema migrations flywayUrl := "jdbc:postgresql://0.0.0.0:5432/postgres", flywayUser := "postgres", flywayPassword := "<PASSWORD>!", // Separate the schema and seed, as unit tests does not require seed test data flywayLocations := Seq("filesystem:db/migration/postgresql", "filesystem:db/seed") ) /** * Basic auto-closing implementation for closeable resource. * * Required as sbt 1.4.x is still on Scala 2.12. * * @param res Closeable resource. * @param fn Lambda function performing resource operations. * @tparam T Resource type parameters. * @tparam U Lambda function result type parameters. * @return Lambda function result. */ private[this] def using[T <: Closeable, U](res: T)(fn: T => U): U = try { fn(res) } finally { res.close() } }
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/repository/UserRepo.scala
<reponame>hhandoko/scala-http4s-realworld-example-app package com.hhandoko.realworld.repository import cats.effect.Sync import doobie.implicits._ import doobie.util.fragment.Fragment import doobie.util.transactor.Transactor import com.hhandoko.realworld.core.{Profile, Username} trait UserRepo[F[_]] { def find(username: Username): F[Option[Profile]] } object UserRepo { def apply[F[_]: Sync](xa: Transactor[F]): UserRepo[F] = new UserRepo[F] { override def find(username: Username): F[Option[Profile]] = (select ++ withUsername(username) ++ withLimit) .query[Profile] .option .transact(xa) } private[repository] final val select = Fragment.const { """SELECT username | , bio | , image | FROM profile |""".stripMargin } private[repository] final val withLimit = Fragment.const("LIMIT 1") private[this] def withUsername(username: Username): Fragment = fr"WHERE lower(username) = lower(${username.value})" }
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/core/JwtToken.scala
package com.hhandoko.realworld.core final case class JwtToken(value: String) extends AnyVal
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/auth/UnauthorizedResponseSupport.scala
package com.hhandoko.realworld.auth import org.http4s.Challenge import org.http4s.headers.`WWW-Authenticate` trait UnauthorizedResponseSupport { private final val SCHEME = "Token" private final val REALM = "realworld" // TODO: Split to invalid_request and invalid_token // Refer to: // - https://tools.ietf.org/html/rfc6750#section-3 // - http://self-issued.info/docs/draft-ietf-oauth-v2-bearer.html#rfc.section.3 protected def withChallenge(err: String): `WWW-Authenticate` = { val params = Map( "error" -> "invalid_token", "error_description" -> err ) `WWW-Authenticate`(Challenge(SCHEME, REALM, params)) } }
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/config/LogConfig.scala
<reponame>hhandoko/scala-http4s-realworld-example-app<filename>src/main/scala/com/hhandoko/realworld/config/LogConfig.scala package com.hhandoko.realworld.config final case class LogConfig(httpHeader: Boolean, httpBody: Boolean)
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/core/Article.scala
<reponame>hhandoko/scala-http4s-realworld-example-app package com.hhandoko.realworld.core import java.time.ZonedDateTime final case class Article( slug: String, title: String, description: String, body: String, tagList: Set[String], createdAt: ZonedDateTime, updatedAt: ZonedDateTime, favorited: Boolean, favoritesCount: Long, author: Author )
hhandoko/scala-http4s-realworld-example-app
src/main/scala/com/hhandoko/realworld/repository/ArticleRepo.scala
package com.hhandoko.realworld.repository import java.time.ZonedDateTime import cats.syntax.functor._ import doobie.Read import com.hhandoko.realworld.core.{Author, Username} import cats.effect.Effect import doobie.Fragment import doobie.implicits._ import doobie.util.transactor.Transactor import com.hhandoko.realworld.core.Article import com.hhandoko.realworld.service.query.Pagination trait ArticleRepo[F[_]] { def findFiltered(pg: Pagination): F[Vector[Article]] } object ArticleRepo { def apply[F[_]: Effect](xa: Transactor[F]): ArticleRepo[F] = new ArticleRepo[F] { import Reader._ override def findFiltered(pg: Pagination): F[Vector[Article]] = for { arts <- findArticles(pg) } yield arts def findArticles(pg: Pagination): F[Vector[Article]] = (select ++ withPagination(pg)) .query[Article] .to[Vector] .transact(xa) } private[repository] final val select = Fragment.const { """ SELECT a.slug | , a.title | , a.description | , a.body | , a.created_at | , a.updated_at | , p.username | FROM article a |INNER JOIN profile p ON a.author_id = p.id |""".stripMargin } private[this] def withPagination(pg: Pagination) = fr" LIMIT ${pg.limit} OFFSET ${pg.offset}" object Reader { import doobie.implicits.javatimedrivernative._ implicit val readArticle: Read[Article] = Read[(String, String, String, String, ZonedDateTime, ZonedDateTime, String)] .map { case (slug, title, description, body, created_at, updated_at, username) => Article( slug, title, description, body, Set.empty[String], created_at, updated_at, favorited = false, favoritesCount = 0, Author( Username(username), None, None, following = false, ) ) } } }
ivoson/delta
project/MimaExcludes.scala
<gh_stars>1-10 /* * Copyright 2019 Databricks, Inc. * * 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. */ import com.typesafe.tools.mima.core._ import com.typesafe.tools.mima.core.ProblemFilters._ /** * The list of Mima errors to exclude. */ object MimaExcludes { val ignoredABIProblems = Seq( ProblemFilters.exclude[Problem]("org.*"), ProblemFilters.exclude[Problem]("io.delta.sql.parser.*"), ProblemFilters.exclude[Problem]("io.delta.tables.execution.*"), ProblemFilters.exclude[DirectMissingMethodProblem]("io.delta.tables.DeltaTable.apply"), ProblemFilters.exclude[DirectMissingMethodProblem]("io.delta.tables.DeltaTable.executeHistory"), ProblemFilters.exclude[DirectMissingMethodProblem]("io.delta.tables.DeltaTable.this"), ProblemFilters.exclude[DirectMissingMethodProblem]("io.delta.tables.DeltaTable.deltaLog")) }
ivoson/delta
src/main/scala/org/apache/spark/sql/delta/Snapshot.scala
/* * Copyright 2019 Databricks, Inc. * * 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 org.apache.spark.sql.delta // scalastyle:off import.ordering.noEmptyLine import java.net.URI import org.apache.spark.sql.delta.actions._ import org.apache.spark.sql.delta.actions.Action.logSchema import org.apache.spark.sql.delta.metering.DeltaLogging import org.apache.spark.sql.delta.sources.DeltaSQLConf import org.apache.spark.sql.delta.util.StateCache import org.apache.hadoop.conf.Configuration import org.apache.hadoop.fs.{FileSystem, Path} import org.apache.spark.sql._ import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder import org.apache.spark.sql.catalyst.plans.logical.Union import org.apache.spark.sql.execution.datasources.{HadoopFsRelation, LogicalRelation} import org.apache.spark.sql.expressions.UserDefinedFunction import org.apache.spark.sql.functions._ import org.apache.spark.sql.types.StructType import org.apache.spark.util.{SerializableConfiguration, Utils} /** * An immutable snapshot of the state of the log at some delta version. Internally * this class manages the replay of actions stored in checkpoint or delta files, * given an optional starting snapshot. * * After resolving any new actions, it caches the result and collects the * following basic information to the driver: * - Protocol Version * - Metadata * - Transaction state * * @param timestamp The timestamp of the latest commit in milliseconds. Can also be set to -1 if the * timestamp of the commit is unknown or the table has not been initialized, i.e. * `version = -1`. */ class Snapshot( val path: Path, val version: Long, previousSnapshot: Option[Dataset[SingleAction]], files: Seq[DeltaLogFileIndex], val minFileRetentionTimestamp: Long, val deltaLog: DeltaLog, val timestamp: Long, val lineageLength: Int = 1) extends StateCache with PartitionFiltering with DeltaFileFormat with DeltaLogging { import Snapshot._ // For implicits which re-use Encoder: import SingleAction._ protected def spark = SparkSession.active // Reconstruct the state by applying deltas in order to the checkpoint. // We partition by path as it is likely the bulk of the data is add/remove. // Non-path based actions will be collocated to a single partition. private val stateReconstruction = { val implicits = spark.implicits import implicits._ val numPartitions = spark.sessionState.conf.getConf(DeltaSQLConf.DELTA_SNAPSHOT_PARTITIONS) val checkpointData = previousSnapshot.getOrElse(emptyActions) val deltaData = load(files) val allActions = checkpointData.union(deltaData) val time = minFileRetentionTimestamp val hadoopConf = new SerializableConfiguration(spark.sessionState.newHadoopConf()) val logPath = path.toUri // for serializability allActions.as[SingleAction] .mapPartitions { actions => val hdpConf = hadoopConf.value actions.flatMap { _.unwrap match { case add: AddFile => Some(add.copy(path = canonicalizePath(add.path, hdpConf)).wrap) case rm: RemoveFile => Some(rm.copy(path = canonicalizePath(rm.path, hdpConf)).wrap) case other if other == null => None case other => Some(other.wrap) } } } .withColumn("file", assertLogBelongsToTable(logPath)(input_file_name())) .repartition(numPartitions, coalesce($"add.path", $"remove.path")) .sortWithinPartitions("file") .as[SingleAction] .mapPartitions { iter => val state = new InMemoryLogReplay(time) state.append(0, iter.map(_.unwrap)) state.checkpoint.map(_.wrap) } } def redactedPath: String = Utils.redact(spark.sessionState.conf.stringRedactionPattern, path.toUri.toString) private val cachedState = cacheDS(stateReconstruction, s"Delta Table State #$version - $redactedPath") /** The current set of actions in this [[Snapshot]]. */ def state: Dataset[SingleAction] = cachedState.getDS // Force materialization of the cache and collect the basics to the driver for fast access. // Here we need to bypass the ACL checks for SELECT anonymous function permissions. val State(protocol, metadata, setTransactions, sizeInBytes, numOfFiles, numOfMetadata, numOfProtocol, numOfRemoves, numOfSetTransactions) = { val implicits = spark.implicits import implicits._ state.select( coalesce(last($"protocol", ignoreNulls = true), defaultProtocol()) as "protocol", coalesce(last($"metaData", ignoreNulls = true), emptyMetadata()) as "metadata", collect_set($"txn") as "setTransactions", // sum may return null for empty data set. coalesce(sum($"add.size"), lit(0L)) as "sizeInBytes", count($"add") as "numOfFiles", count($"metaData") as "numOfMetadata", count($"protocol") as "numOfProtocol", count($"remove") as "numOfRemoves", count($"txn") as "numOfSetTransactions") .as[State](stateEncoder)} .first deltaLog.protocolRead(protocol) /** A map to look up transaction version by appId. */ lazy val transactions = setTransactions.map(t => t.appId -> t.version).toMap // Here we need to bypass the ACL checks for SELECT anonymous function permissions. /** All of the files present in this [[Snapshot]]. */ def allFiles: Dataset[AddFile] = { val implicits = spark.implicits import implicits._ state.where("add IS NOT NULL").select($"add".as[AddFile]) } /** All unexpired tombstones. */ def tombstones: Dataset[RemoveFile] = { val implicits = spark.implicits import implicits._ state.where("remove IS NOT NULL").select($"remove".as[RemoveFile]) } /** Returns the schema of the table. */ def schema: StructType = metadata.schema /** Returns the data schema of the table, the schema of the columns written out to file. */ def dataSchema: StructType = metadata.dataSchema /** Number of columns to collect stats on for data skipping */ val numIndexedCols: Int = DeltaConfigs.DATA_SKIPPING_NUM_INDEXED_COLS.fromMetaData(metadata) /** * Load the transaction logs from file indices. The files here may have different file formats * and the file format can be extracted from the file extensions. */ private def load( files: Seq[DeltaLogFileIndex]): Dataset[SingleAction] = { val relations = files.map { index: DeltaLogFileIndex => val fsRelation = HadoopFsRelation( index, index.partitionSchema, logSchema, None, index.format, Map.empty[String, String])(spark) LogicalRelation(fsRelation) } if (relations.length == 1) { Dataset[SingleAction](spark, relations.head) } else if (relations.nonEmpty) { Dataset[SingleAction](spark, Union(relations)) } else { emptyActions } } private def emptyActions = spark.createDataFrame(spark.sparkContext.emptyRDD[Row], logSchema).as[SingleAction] } object Snapshot extends DeltaLogging { private lazy val emptyMetadata = udf(() => Metadata()) private lazy val defaultProtocol = udf(() => Protocol()) /** Canonicalize the paths for Actions */ private def canonicalizePath(path: String, hadoopConf: Configuration): String = { val hadoopPath = new Path(new URI(path)) if (hadoopPath.isAbsoluteAndSchemeAuthorityNull) { val fs = FileSystem.get(hadoopConf) fs.makeQualified(hadoopPath).toUri.toString } else { // return untouched if it is a relative path or is already fully qualified hadoopPath.toUri.toString } } /** * Make sure that the delta file we're reading belongs to this table. Cached snapshots from * the previous states will contain empty strings as the file name. */ private def assertLogBelongsToTable(logBasePath: URI): UserDefinedFunction = { udf((filePath: String) => { if (filePath.isEmpty || new Path(new URI(filePath)).getParent == new Path(logBasePath)) { filePath } else { // scalastyle:off throwerror throw new AssertionError(s"File ($filePath) doesn't belong in the " + s"transaction log at $logBasePath. Please contact Databricks Support.") // scalastyle:on throwerror } }) } private case class State( protocol: Protocol, metadata: Metadata, setTransactions: Seq[SetTransaction], sizeInBytes: Long, numOfFiles: Long, numOfMetadata: Long, numOfProtocol: Long, numOfRemoves: Long, numOfSetTransactions: Long) private[this] lazy val _stateEncoder: ExpressionEncoder[State] = try { ExpressionEncoder[State]() } catch { case e: Throwable => logError(e.getMessage, e) throw e } implicit private def stateEncoder: ExpressionEncoder[State] = _stateEncoder.copy() } /** * An initial snapshot with only metadata specified. Useful for creating a DataFrame from an * existing parquet table during its conversion to delta. * @param logPath the path to transaction log * @param deltaLog the delta log object * @param metadata the metadata of the table */ class InitialSnapshot( val logPath: Path, override val deltaLog: DeltaLog, override val metadata: Metadata) extends Snapshot(logPath, -1, None, Nil, -1, deltaLog, -1)
nokia-wroclaw/innovativeproject-notifications
notifications/build.sbt
name := """notifications""" version := "1.0-SNAPSHOT" lazy val root = (project in file(".")).enablePlugins(PlayJava) scalaVersion := "2.11.7" libraryDependencies ++= Seq( javaJdbc, cache, javaWs, filters ) libraryDependencies += "com.rabbitmq" % "amqp-client" % "3.6.5" libraryDependencies += "mysql" % "mysql-connector-java" % "5.1.29" libraryDependencies += "com.typesafe.play" %% "play-json" % "2.5.9"
Ahmed-elsayed-mahmoud/incubator-openwhisk
common/scala/src/main/scala/whisk/core/connector/MessageConsumer.scala
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 whisk.core.connector import akka.actor.ActorRef import scala.annotation.tailrec import scala.collection.immutable import scala.concurrent.Future import scala.concurrent.blocking import scala.concurrent.duration._ import scala.util.Failure import org.apache.kafka.clients.consumer.CommitFailedException import akka.actor.FSM import akka.pattern.pipe import whisk.common.Logging import whisk.common.TransactionId trait MessageConsumer { /** The maximum number of messages peeked (i.e., max number of messages retrieved during a long poll). */ val maxPeek: Int /** * Gets messages via a long poll. May or may not remove messages * from the message connector. Use commit() to ensure messages are * removed from the connector. * * @param duration for the long poll * @return iterable collection (topic, partition, offset, bytes) */ def peek(duration: FiniteDuration, retry: Int = 3): Iterable[(String, Int, Long, Array[Byte])] /** * Commits offsets from last peek operation to ensure they are removed * from the connector. */ def commit(retry: Int = 3): Unit /** Closes consumer. */ def close(): Unit } object MessageFeed { protected sealed trait FeedState protected[connector] case object Idle extends FeedState protected[connector] case object FillingPipeline extends FeedState protected[connector] case object DrainingPipeline extends FeedState protected sealed trait FeedData private case object NoData extends FeedData /** Indicates the consumer is ready to accept messages from the message bus for processing. */ object Ready /** Steady state message, indicates capacity in downstream process to receive more messages. */ object Processed /** message to indicate max offset is reached */ object MaxOffset /** Indicates the fill operation has completed. */ private case class FillCompleted(messages: Seq[(String, Int, Long, Array[Byte])]) } /** * This actor polls the message bus for new messages and dispatches them to the given * handler. The actor tracks the number of messages dispatched and will not dispatch new * messages until some number of them are acknowledged. * * This is used by the invoker to pull messages from the message bus and apply back pressure * when the invoker does not have resources to complete processing messages (i.e., no containers * are available to run new actions). It is also used in the load balancer to consume active * ack messages. * When the invoker releases resources (by reclaiming containers) it will send a message * to this actor which will then attempt to fill the pipeline with new messages. * * The actor tries to fill the pipeline with additional messages while the number * of outstanding requests is below the pipeline fill threshold. */ @throws[IllegalArgumentException] class MessageFeed(description: String, logging: Logging, consumer: MessageConsumer, maximumHandlerCapacity: Int, longPollDuration: FiniteDuration, handler: Array[Byte] => Future[Unit], autoStart: Boolean = true, logHandoff: Boolean = true, offsetMonitor: Option[ActorRef] = None) extends FSM[MessageFeed.FeedState, MessageFeed.FeedData] { import MessageFeed._ // double-buffer to make up for message bus read overhead val maxPipelineDepth = maximumHandlerCapacity * 2 private val pipelineFillThreshold = maxPipelineDepth - consumer.maxPeek require( consumer.maxPeek <= maxPipelineDepth, "consumer may not yield more messages per peek than permitted by max depth") // Immutable Queue // although on the surface it seems to make sense to use an immutable variable with a mutable Queue, // Akka Actor state defies the usual "prefer immutable" guideline in Scala, esp. w/ Collections. // If, for some reason, this Queue was mutable and is accidentally leaked in say an Akka message, // another Actor or recipient would be able to mutate the internal state of this Actor. // Best practice dictates a mutable variable pointing at an immutable collection for this reason private var outstandingMessages = immutable.Queue.empty[(String, Int, Long, Array[Byte])] private var handlerCapacity = maximumHandlerCapacity private implicit val tid = TransactionId.dispatcher logging.info( this, s"handler capacity = $maximumHandlerCapacity, pipeline fill at = $pipelineFillThreshold, pipeline depth = $maxPipelineDepth") when(Idle) { case Event(Ready, _) => fillPipeline() goto(FillingPipeline) case _ => stay } // wait for fill to complete, and keep filling if there is // capacity otherwise wait to drain when(FillingPipeline) { case Event(Processed, _) => updateHandlerCapacity() sendOutstandingMessages() stay case Event(FillCompleted(messages), _) => outstandingMessages = outstandingMessages ++ messages sendOutstandingMessages() if (shouldFillQueue()) { fillPipeline() stay } else { goto(DrainingPipeline) } case _ => stay } when(DrainingPipeline) { case Event(Processed, _) => updateHandlerCapacity() sendOutstandingMessages() if (shouldFillQueue()) { fillPipeline() goto(FillingPipeline) } else stay case _ => stay } onTransition { case _ -> Idle => if (autoStart) self ! Ready } startWith(Idle, MessageFeed.NoData) initialize() private implicit val ec = context.system.dispatchers.lookup("dispatchers.kafka-dispatcher") private def fillPipeline(): Unit = { if (outstandingMessages.size <= pipelineFillThreshold) { Future { blocking { // Grab next batch of messages and commit offsets immediately // essentially marking the activation as having satisfied "at most once" // semantics (this is the point at which the activation is considered started). // If the commit fails, then messages peeked are peeked again on the next poll. // While the commit is synchronous and will block until it completes, at steady // state with enough buffering (i.e., maxPipelineDepth > maxPeek), the latency // of the commit should be masked. val records = consumer.peek(longPollDuration) consumer.commit() if (records.size < maxPipelineDepth) { //reached the max offset offsetMonitor.foreach(_ ! MaxOffset) } FillCompleted(records.toSeq) } }.andThen { case Failure(e: CommitFailedException) => logging.error(this, s"failed to commit $description consumer offset: $e") case Failure(e: Throwable) => logging.error(this, s"exception while pulling new $description records: $e") } .recover { case _ => FillCompleted(Seq.empty) } .pipeTo(self) } else { logging.error(this, s"dropping fill request until $description feed is drained") } } /** Send as many messages as possible to the handler. */ @tailrec private def sendOutstandingMessages(): Unit = { val occupancy = outstandingMessages.size if (occupancy > 0 && handlerCapacity > 0) { // Easiest way with an immutable queue to cleanly dequeue // Head is the first elemeent of the queue, desugared w/ an assignment pattern // Tail is everything but the first element, thus mutating the collection variable val (topic, partition, offset, bytes) = outstandingMessages.head outstandingMessages = outstandingMessages.tail if (logHandoff) logging.debug(this, s"processing $topic[$partition][$offset] ($occupancy/$handlerCapacity)") handler(bytes) handlerCapacity -= 1 sendOutstandingMessages() } } private def shouldFillQueue(): Boolean = { val occupancy = outstandingMessages.size if (occupancy <= pipelineFillThreshold) { logging.debug( this, s"$description pipeline has capacity: $occupancy <= $pipelineFillThreshold ($handlerCapacity)") true } else { logging.debug(this, s"$description pipeline must drain: $occupancy > $pipelineFillThreshold") false } } private def updateHandlerCapacity(): Int = { logging.debug(self, s"$description received processed msg, current capacity = $handlerCapacity") if (handlerCapacity < maximumHandlerCapacity) { handlerCapacity += 1 handlerCapacity } else { if (handlerCapacity > maximumHandlerCapacity) logging.error(self, s"$description capacity already at max") maximumHandlerCapacity } } }
KyleErwin/cilib
work/src/main/scala/cilib/work/Main.scala
package cilib package work import scalaz.effect.IO._ import scalaz.effect.{IO, SafeApp} object Main extends SafeApp { override val runc: IO[Unit] = putStrLn("Hello world") }
KyleErwin/cilib
build.sbt
import sbt._ import sbt.Keys._ import sbtrelease.ReleaseStateTransformations._ val scalazVersion = "7.2.25" val scalazStreamVersion = "0.8.6a" val spireVersion = "0.13.0" val monocleVersion = "1.5.0" val scalacheckVersion = "1.14.0" val avro4sVersion = "1.8.3" val previousArtifactVersion = SettingKey[String]("previous-tagged-version") val siteStageDirectory = SettingKey[File]("site-stage-directory") val copySiteToStage = TaskKey[Unit]("copy-site-to-stage") lazy val commonSettings = Seq( organization := "net.cilib", autoAPIMappings := true, scalacOptions ++= Seq( "-deprecation", // Emit warning and location for usages of deprecated APIs. "-encoding", "utf-8", // Specify character encoding used by source files. "-explaintypes", // Explain type errors in more detail. "-feature", // Emit warning and location for usages of features that should be imported explicitly. "-language:existentials", // Existential types (besides wildcard types) can be written and inferred "-language:experimental.macros", // Allow macro definition (besides implementation and application) "-language:higherKinds", // Allow higher-kinded types "-language:implicitConversions", // Allow definition of implicit functions called views "-unchecked", // Enable additional warnings where generated code depends on assumptions. "-Xcheckinit", // Wrap field accessors to throw an exception on uninitialized access. //"-Xfatal-warnings", // Fail the compilation if there are any warnings. "-Xfuture", // Turn on future language features. "-Xlint:adapted-args", // Warn if an argument list is modified to match the receiver. "-Xlint:by-name-right-associative", // By-name parameter of right associative operator. "-Xlint:delayedinit-select", // Selecting member of DelayedInit. "-Xlint:doc-detached", // A Scaladoc comment appears to be detached from its element. "-Xlint:inaccessible", // Warn about inaccessible types in method signatures. "-Xlint:infer-any", // Warn when a type argument is inferred to be `Any`. "-Xlint:missing-interpolator", // A string literal appears to be missing an interpolator id. "-Xlint:nullary-override", // Warn when non-nullary `def f()' overrides nullary `def f'. "-Xlint:nullary-unit", // Warn when nullary methods return Unit. "-Xlint:option-implicit", // Option.apply used implicit view. "-Xlint:package-object-classes", // Class or object defined in package object. "-Xlint:poly-implicit-overload", // Parameterized overloaded implicit methods are not visible as view bounds. "-Xlint:private-shadow", // A private field (or class parameter) shadows a superclass field. "-Xlint:stars-align", // Pattern sequence wildcard must align with sequence component. "-Xlint:type-parameter-shadow", // A local type parameter shadows a type already in scope. "-Xlint:unsound-match", // Pattern match may not be typesafe. "-Yno-adapted-args", // Do not adapt an argument list (either by inserting () or creating a tuple) to match the receiver. "-Ypartial-unification", // Enable partial unification in type constructor inference "-Ywarn-dead-code", // Warn when dead code is identified. "-Ywarn-inaccessible", // Warn about inaccessible types in method signatures. "-Ywarn-infer-any", // Warn when a type argument is inferred to be `Any`. "-Ywarn-nullary-override", // Warn when non-nullary `def f()' overrides nullary `def f'. "-Ywarn-nullary-unit", // Warn when nullary methods return Unit. "-Ywarn-numeric-widen", // Warn when numerics are widened. "-Ywarn-value-discard" // Warn when non-Unit expression results are unused. ) ++ ( if (scalaVersion.value.startsWith("2.11")) Seq() else Seq( "-Xlint:constant", // Evaluation of a constant arithmetic expression results in an error. "-Ywarn-extra-implicit", // Warn when more than one implicit parameter section is defined. "-Ywarn-unused:implicits", // Warn if an implicit parameter is unused. "-Ywarn-unused:imports", // Warn if an import selector is not referenced. "-Ywarn-unused:locals", // Warn if a local definition is unused. "-Ywarn-unused:params", // Warn if a value parameter is unused. "-Ywarn-unused:patvars", // Warn if a variable bound in a pattern is unused. "-Ywarn-unused:privates", // Warn if a private member is unused. ) ), scalacOptions in (Compile, console) ~= (_.filterNot(Set( "-Ywarn-unused:imports", "-Xfatal-warnings" ))), resolvers ++= Seq( Resolver.sonatypeRepo("releases"), "bintray/non" at "http://dl.bintray.com/non/maven" ), libraryDependencies ++= Seq( compilerPlugin("org.spire-math" %% "kind-projector" % "0.9.7" cross CrossVersion.binary) ), scmInfo := Some(ScmInfo(url("https://github.com/cirg-up/cilib"), "scm:git:git@github.com:cirg-up/cilib.git")), initialCommands in console := """ |import scalaz._ |import Scalaz._ |import cilib._ |import spire.implicits._ |""".stripMargin, // MiMa related previousArtifactVersion := { // Can this be done nicer/safer? import org.eclipse.jgit._ import org.eclipse.jgit.api._ import org.eclipse.jgit.lib.Constants import scala.collection.JavaConverters._ val git = Git.open(new java.io.File(".")) val tags = git.tagList.call().asScala val current = git.getRepository.resolve(Constants.HEAD) val lastTag = tags.lift(tags.size - 1) val name = lastTag.flatMap(last => { if (last.getObjectId.getName == current.getName) tags.lift(tags.size - 2).map(_.getName) else Some(last.getName) }) name.getOrElse("NO_TAG").replace("refs/tags/v", "") }, mimaPreviousArtifacts := Set(organization.value %% moduleName.value % previousArtifactVersion.value) ) lazy val noPublishSettings = Seq( skip in publish := true, mimaPreviousArtifacts := Set() ) lazy val publishSettings = Seq( organizationHomepage := Some(url("https://github.com/cirg-up")), homepage := Some(url("https://cilib.net")), licenses := Seq("Apache-2.0" -> url("https://opensource.org/licenses/Apache-2.0")), autoAPIMappings := true, apiURL := Some(url("https://cilib.net/api/")), publishMavenStyle := true, //publishArtifact in packageDoc := false, publishArtifact in Test := false, pomIncludeRepository := { _ => false }, publishTo := Some("releases" at "https://oss.sonatype.org/service/local/staging/deploy/maven2"), // { // val nexus = "https://oss.sonatype.org/" // if (isSnapshot.value) // Some("snapshots" at nexus + "content/repositories/snapshots") // else // Some("releases" at nexus + "service/local/staging/deploy/maven2") // }, pomExtra := ( <developers> { Seq( ("gpampara", "<NAME>"), ("filinep", "<NAME>"), ("benniel", "<NAME>") ).map { case (id, name) => <developer> <id>{id}</id> <name>{name}</name> <url>https://github.com/{id}</url> </developer> } } </developers> ) ) lazy val cilibSettings = commonSettings ++ publishSettings ++ credentialSettings lazy val cilib = project .in(file(".")) .enablePlugins(GitVersioning, ReleasePlugin) .settings(credentialSettings ++ noPublishSettings ++ Seq( git.useGitDescribe := true, releaseProcess := Seq[ReleaseStep]( checkSnapshotDependencies, // runClean, // runTest, releaseStepCommand("publishSigned"), releaseStepCommand("sonatypeReleaseAll") ) )) .aggregate(core, de, docs, eda, example, exec, ga, moo, pso, tests) .dependsOn(core, de, docs, eda, example, exec, ga, moo, pso, tests) lazy val core = project .settings( cilibSettings ++ Seq( moduleName := "cilib-core", libraryDependencies ++= Seq( "org.scalaz" %% "scalaz-core" % scalazVersion, "org.scalaz" %% "scalaz-concurrent" % scalazVersion, "org.spire-math" %% "spire" % spireVersion, "com.github.julien-truffaut" %% "monocle-core" % monocleVersion, "com.chuusai" %% "shapeless" % "2.3.3", "eu.timepit" %% "refined" % "0.9.2" ), wartremoverErrors in (Compile, compile) ++= Seq( // Wart.Any, Wart.AnyVal, Wart.ArrayEquals, Wart.AsInstanceOf, Wart.DefaultArguments, Wart.ExplicitImplicitTypes, Wart.Enumeration, //Wart.Equals, Wart.FinalCaseClass, Wart.FinalVal, Wart.ImplicitConversion, Wart.ImplicitParameter, Wart.IsInstanceOf, Wart.JavaConversions, Wart.JavaSerializable, Wart.LeakingSealed, Wart.MutableDataStructures, Wart.NonUnitStatements, // Wart.Nothing, Wart.Null, Wart.Option2Iterable, Wart.OptionPartial, Wart.Overloading, Wart.Product, Wart.PublicInference, Wart.Return, // Wart.Recursion, Wart.Serializable, Wart.StringPlusAny, Wart.Throw, Wart.ToString, Wart.TraversableOps, Wart.TryPartial, Wart.Var, Wart.While ) )) lazy val docs = project .in(file("docs")) .enablePlugins(GhpagesPlugin, TutPlugin, ParadoxSitePlugin, ParadoxMaterialThemePlugin, ScalaUnidocPlugin) .settings(ParadoxMaterialThemePlugin.paradoxMaterialThemeSettings(Paradox)) .settings(moduleName := "cilib-docs") .settings(cilibSettings) .settings(noPublishSettings) .settings(docSettings) .dependsOn(core, example, exec, pso, moo, ga) lazy val docSettings = Seq( fork in tut := true, tutSourceDirectory := sourceDirectory.value / "main" / "tut", scalacOptions in Tut ~= (_.filterNot(Set("-Ywarn-unused:imports", "-Ywarn-dead-code"))), git.remoteRepo := "<EMAIL>:cirg-up/cilib.git", ghpagesNoJekyll := true, excludeFilter in ghpagesCleanSite := new FileFilter { def accept(f: File) = (ghpagesRepository.value / "CNAME").getCanonicalPath == f.getCanonicalPath }, siteSubdirName in SiteScaladoc := "api", unidocProjectFilter in (ScalaUnidoc, unidoc) := inAnyProject -- inProjects(example), addMappingsToSiteDir(mappings in (ScalaUnidoc, packageDoc), siteSubdirName in SiteScaladoc), siteStageDirectory := target.value / "site-stage", sourceDirectory in paradox in Paradox := siteStageDirectory.value, sourceDirectory in paradox := siteStageDirectory.value, // https://github.com/lightbend/paradox/issues/139 sourceDirectory in Paradox in paradoxTheme := sourceDirectory.value / "main" / "paradox" / "_template", paradoxMaterialTheme in Paradox ~= { _.withFavicon("img/favicon.png") .withLogo("img/cilib_logo_transparent.png") .withRepository(uri("https://github.com/cirg-up/cilib")) }, copySiteToStage := { IO.copyFile(sourceFile = sourceDirectory.value / "main" / "paradox" / "index.md", targetFile = siteStageDirectory.value / "index.md", preserveLastModified = true) IO.copyDirectory(source = sourceDirectory.value / "main" / "paradox" / "img", target = siteStageDirectory.value / "img", overwrite = false, preserveLastModified = true) IO.copyDirectory(source = tutTargetDirectory.value, target = siteStageDirectory.value, overwrite = false, preserveLastModified = true) IO.write(file = siteStageDirectory.value / "CNAME", content = "cilib.net") }, copySiteToStage := copySiteToStage.dependsOn(tutQuick).value, makeSite := makeSite.dependsOn(copySiteToStage).value ) lazy val credentialSettings = Seq( credentials ++= (for { username <- Option(System.getenv("SONATYPE_USERNAME")) password <- Option(System.getenv("SONATYPE_PASSWORD")) } yield Credentials("Sonatype Nexus Repository Manager", "oss.sonatype.org", username, password)).toSeq, sonatypeProfileName := "net.cilib", pgpPublicRing := file("./project/local.pubring.asc"), pgpSecretRing := file("./project/local.secring.asc"), pgpPassphrase := Option(System.getenv("PGP_PASS")).map(_.toArray) ) lazy val eda = project .dependsOn(core) .settings(Seq(moduleName := "cilib-eda") ++ cilibSettings) lazy val example = project .dependsOn(core, de, exec, ga, io, moo, pso) .settings( cilibSettings ++ noPublishSettings ++ Seq( fork in run := true, connectInput in run := true, moduleName := "cilib-example", libraryDependencies ++= Seq( "net.cilib" %% "benchmarks" % "0.1.1", "org.scalaz" %% "scalaz-effect" % scalazVersion ) )) lazy val work = project .dependsOn(core, de, exec, ga, io, moo, pso) .settings( cilibSettings ++ noPublishSettings ++ Seq( fork in run := true, connectInput in run := true, moduleName := "cilib-work", libraryDependencies ++= Seq( "net.cilib" %% "benchmarks" % "0.1.1", "org.scalaz" %% "scalaz-effect" % scalazVersion ) )) lazy val exec = project .dependsOn(core) .settings(cilibSettings ++ Seq( moduleName := "cilib-exec", libraryDependencies ++= Seq( "org.scalaz" %% "scalaz-concurrent" % scalazVersion, "org.scalaz.stream" %% "scalaz-stream" % scalazStreamVersion, "com.sksamuel.avro4s" %% "avro4s-core" % avro4sVersion ) )) lazy val moo = project .dependsOn(core) .settings(Seq(moduleName := "cilib-moo") ++ cilibSettings) lazy val pso = project .dependsOn(core) .settings(Seq(moduleName := "cilib-pso") ++ cilibSettings) lazy val ga = project .dependsOn(core) .settings(Seq(moduleName := "cilib-ga") ++ cilibSettings) lazy val de = project .dependsOn(core) .settings(Seq(moduleName := "cilib-de") ++ cilibSettings) lazy val tests = project .dependsOn(core, pso, ga, moo) .settings( cilibSettings ++ noPublishSettings ++ Seq( moduleName := "cilib-tests", fork in test := true, javaOptions in test += "-Xmx1G", libraryDependencies ++= Seq( "org.scalacheck" %% "scalacheck" % scalacheckVersion % "test", "org.scalaz" %% "scalaz-scalacheck-binding" % (scalazVersion + "-scalacheck-1.14") % "test" ) )) lazy val io = project .dependsOn(core, exec) .settings( cilibSettings ++ noPublishSettings ++ Seq( moduleName := "cilib-io", libraryDependencies ++= Seq( "com.chuusai" %% "shapeless" % "2.3.2", "com.sksamuel.avro4s" %% "avro4s-core" % avro4sVersion, "org.apache.parquet" % "parquet-avro" % "1.9.0", "org.apache.hadoop" % "hadoop-client" % "2.7.3", "org.scalaz.stream" %% "scalaz-stream" % scalazStreamVersion ) ))
az82/micronaut-opa-demo
src/gatling/simulations/de/az/demo/mn/opa/DemoSimulation.scala
<reponame>az82/micronaut-opa-demo package de.az.demo.mn.opa import io.gatling.core.Predef._ import io.gatling.http.Predef._ import scala.concurrent.duration._ /** * Gatling simulation for the Micronaut / OPA demo application */ class DemoSimulation extends Simulation { val appHost: String = getenv("app.host", "localhost") val appPort: String = getenv("app.port", 8080) val token = "<KEY>" val users = 100 val rampDuration: FiniteDuration = 20 seconds val constantDuration: FiniteDuration = 40 seconds setUp( scenario("Load test") .randomSwitch( 90.0 -> exec(http("/free") .get("/free") .check(status is 200)), 8.0 -> exec(http("/protected (authorized)") .get("/protected") .header("Authorization", s"Bearer $token") .check(status is 200)), 2.0 -> exec(http("/protected (unauthorized)") .get("/protected") .check(status is 401))) .inject( rampUsers(users) during rampDuration, constantUsersPerSec(users) during constantDuration)) .protocols( http .baseUrl(s"http://$appHost:$appPort") .acceptHeader("text/plain")) .assertions( global.failedRequests.count is 0, global.responseTime.percentile3 lte 20, global.responseTime.percentile4 lte 100) def getenv[T](name:String, default: T): String = { System.getProperty(name, System.getenv(name.toUpperCase.replace('.', '_'))) match { case null => default.toString case x => x } } }
nelsonblaha/playframework
framework/src/play-java-ws/src/main/java/play/libs/ws/util/CollectionUtil.scala
<filename>framework/src/play-java-ws/src/main/java/play/libs/ws/util/CollectionUtil.scala package play.libs.ws.util import java.{util =>ju} import scala.collection.convert.WrapAsJava._ /** Utility class for converting a Scala `Map` with a nested collection type into its idiomatic Java counterpart. * The reason why this source is written in Scala is that doing the conversion using Java is a lot more involved. * This utility class is used by `play.libs.ws.StreamedResponse`. */ private[ws] object CollectionUtil { def convert(headers: Map[String, Seq[String]]): ju.Map[String, ju.List[String]] = mapAsJavaMap(headers.map { case (k, v) => k -> seqAsJavaList(v)}) }
nelsonblaha/playframework
framework/src/iteratees/src/main/scala/play/api/libs/iteratee/RunQueue.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api.libs.iteratee import scala.annotation.tailrec import scala.concurrent.{ ExecutionContext, Future } import java.util.concurrent.atomic.AtomicReference /** * Runs asynchronous operations in order. Operations are queued until * they can be run. Each item is added to a schedule, then each item * in the schedule is executed in order. * * {{{ * val runQueue = new RunQueue() * * // This operation will run first. It completes when * // the future it returns is completed. * runQueue.schedule { * Future { ... do some stuff ... } * } * * // This operation will run second. It will start running * // when the previous operation's futures complete. * runQueue.schedule { * future1.flatMap(x => future2.map(y => x + y)) * } * * // This operation will run when the second operation's * // future finishes. It's a simple synchronous operation. * runQueue.scheduleSimple { * 25 * } * }}} * * Unlike solutions built around a standard concurrent queue, there is no * need to use a separate thread to read from the queue and execute each * operation. The RunQueue runner performs both scheduling and * executions of operations internally without the need for a separate * thread. This means the RunQueue doesn't consume any resources * when it isn't being used. * * No locks are held by this class, only atomic operations are used. */ private[play] final class RunQueue { import RunQueue._ /** * The state of the RunQueue, either Inactive or Runnning. */ private val state = new AtomicReference[Vector[Op]](null) /** * Schedule an operation to be run. The operation is considered * complete when the Future that it returns is completed. In other words, * the next operation will not be started until the future is completed. * * Successive calls to the `run` and `runSynchronous` methods use an * atomic value to guarantee ordering (a *happens-before* relationship). * * The operation will execute in the given ExecutionContext. */ def schedule[A](body: => Future[A])(implicit ec: ExecutionContext): Unit = { schedule(Op(() => body.asInstanceOf[Future[Unit]], ec.prepare)) } /** * Schedule a simple synchronous operation to be run. The operation is considered * complete when it finishes executing. In other words, the next operation will begin * execution immediately when this operation finishes execution. * * This method is equivalent to * {{{ * schedule { * body * Future.successful(()) * } * }}} * * Successive calls to the `run` and `runSynchronous` methods use an * atomic value to guarantee ordering (a *happens-before* relationship). * * The operation will execute in the given ExecutionContext. */ def scheduleSimple(body: => Unit)(implicit ec: ExecutionContext): Unit = { schedule { body Future.successful(()) } } /** * Schedule a reified operation for execution. If no other operations * are currently executing then this operation will be started immediately. * But if there are other operations currently running then this operation * be added to the pending queue of operations awaiting execution. * * This method encapsulates an atomic compare-and-set operation, therefore * it may be retried. */ @tailrec private def schedule(op: Op): Unit = { val prevState = state.get val newState = prevState match { case null => Vector.empty case pending => pending :+ op } if (state.compareAndSet(prevState, newState)) { prevState match { case null => // We've update the state to say that we're running an op, // so we need to actually start it running. execute(op) case _ => } } else schedule(op) // Try again } private def execute(op: Op): Unit = { val f1: Future[Future[Unit]] = Future(op.thunk())(op.ec) val f2: Future[Unit] = f1.flatMap(identity)(Execution.trampoline) f2.onComplete(_ => opExecutionComplete())(Execution.trampoline) } /** * *De*schedule a reified operation for execution. If no other operations * are pending, then the RunQueue will enter an inactive state. * Otherwise, the first pending item will be scheduled for execution. */ @tailrec private def opExecutionComplete(): Unit = { val prevState = state.get val newState = prevState match { case null => throw new IllegalStateException("Can't be inactive, must have a queue of pending elements") case pending if pending.isEmpty => null case pending => pending.tail } if (state.compareAndSet(prevState, newState)) { prevState match { // We have a pending operation to execute case pending if !pending.isEmpty => execute(pending.head) case _ => } } else opExecutionComplete() // Try again } } private object RunQueue { /** * A reified operation to be executed. * * @param thunk The logic to execute. * @param ec The ExecutionContext to use for execution. Already prepared. */ final case class Op(thunk: () => Future[Unit], ec: ExecutionContext) }
nelsonblaha/playframework
framework/src/run-support/src/main/scala/play/runsupport/FileWatchService.scala
<filename>framework/src/run-support/src/main/scala/play/runsupport/FileWatchService.scala /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.runsupport import java.net.URLClassLoader import java.util.List import java.util.Locale import sbt._ import sbt.Path._ import scala.collection.JavaConversions import scala.reflect.ClassTag import scala.util.{ Properties, Try } import scala.util.control.NonFatal import java.io.File import java.util.concurrent.Callable /** * A service that can watch files */ trait FileWatchService { /** * Watch the given sequence of files or directories. * * @param filesToWatch The files to watch. * @param onChange A callback that is executed whenever something changes. * @return A watcher */ def watch(filesToWatch: Seq[File], onChange: () => Unit): FileWatcher /** * Watch the given sequence of files or directories. * * @param filesToWatch The files to watch. * @param onChange A callback that is executed whenever something changes. * @return A watcher */ def watch(filesToWatch: List[File], onChange: Callable[Void]): FileWatcher = { watch(JavaConversions.asScalaBuffer(filesToWatch), () => { onChange.call }) } } /** * A watcher, that watches files. */ trait FileWatcher { /** * Stop watching the files. */ def stop(): Unit } object FileWatchService { private sealed trait OS private case object Windows extends OS private case object Linux extends OS private case object OSX extends OS private case object Other extends OS private val os: OS = { sys.props.get("os.name").map { name => name.toLowerCase(Locale.ENGLISH) match { case osx if osx.contains("darwin") || osx.contains("mac") => OSX case windows if windows.contains("windows") => Windows case linux if linux.contains("linux") => Linux case _ => Other } }.getOrElse(Other) } def defaultWatchService(targetDirectory: File, pollDelayMillis: Int, logger: LoggerProxy): FileWatchService = new FileWatchService { lazy val delegate = os match { // If Windows or Linux and JDK7, use JDK7 watch service case (Windows | Linux) if Properties.isJavaAtLeast("1.7") => new JDK7FileWatchService(logger) // If Windows, Linux or OSX, use JNotify but fall back to SBT case (Windows | Linux | OSX) => JNotifyFileWatchService(targetDirectory).recover { case e => logger.warn("Error loading JNotify watch service: " + e.getMessage) logger.trace(e) new PollingFileWatchService(pollDelayMillis) }.get case _ => new PollingFileWatchService(pollDelayMillis) } def watch(filesToWatch: Seq[File], onChange: () => Unit) = delegate.watch(filesToWatch, onChange) } def jnotify(targetDirectory: File): FileWatchService = optional(JNotifyFileWatchService(targetDirectory)) def jdk7(logger: LoggerProxy): FileWatchService = new JDK7FileWatchService(logger) def sbt(pollDelayMillis: Int): FileWatchService = new PollingFileWatchService(pollDelayMillis) def optional(watchService: Try[FileWatchService]): FileWatchService = new OptionalFileWatchServiceDelegate(watchService) } private[play] trait DefaultFileWatchService extends FileWatchService { def delegate: FileWatchService } /** * A polling Play watch service. Polls in the background. */ private[play] class PollingFileWatchService(val pollDelayMillis: Int) extends FileWatchService { // Work around for https://github.com/sbt/sbt/issues/1973 def distinctPathFinder(pathFinder: PathFinder) = PathFinder { pathFinder.get.map(p => (p.asFile.getAbsolutePath, p)).toMap.values } def watch(filesToWatch: Seq[File], onChange: () => Unit) = { @volatile var stopped = false val thread = new Thread(new Runnable { def run() = { var state = WatchState.empty while (!stopped) { val (triggered, newState) = SourceModificationWatch.watch(distinctPathFinder(filesToWatch.***), pollDelayMillis, state)(stopped) if (triggered) onChange() state = newState } } }, "sbt-play-watch-service") thread.setDaemon(true) thread.start() new FileWatcher { def stop() = stopped = true } } } private[play] class JNotifyFileWatchService(delegate: JNotifyFileWatchService.JNotifyDelegate) extends FileWatchService { def watch(filesToWatch: Seq[File], onChange: () => Unit) = { val listener = delegate.newListener(onChange) val registeredIds = filesToWatch.map { file => delegate.addWatch(file.getAbsolutePath, listener) } new FileWatcher { def stop() = registeredIds.foreach(delegate.removeWatch) } } } private object JNotifyFileWatchService { import java.lang.reflect.{ Method, InvocationHandler, Proxy } /** * Captures all the reflection invocations in one place. */ class JNotifyDelegate(classLoader: ClassLoader, listenerClass: Class[_], addWatchMethod: Method, removeWatchMethod: Method) { def addWatch(fileOrDirectory: String, listener: AnyRef): Int = { addWatchMethod.invoke(null, fileOrDirectory, // The file or directory to watch 15: java.lang.Integer, // flags to say watch for all events true: java.lang.Boolean, // Watch subtree listener).asInstanceOf[Int] } def removeWatch(id: Int): Unit = { try { removeWatchMethod.invoke(null, id.asInstanceOf[AnyRef]) } catch { case _: Throwable => // Ignore, if we fail to remove a watch it's not the end of the world. // http://sourceforge.net/p/jnotify/bugs/12/ // We match on Throwable because matching on an IOException didn't work. // http://sourceforge.net/p/jnotify/bugs/5/ } } def newListener(onChange: () => Unit): AnyRef = { Proxy.newProxyInstance(classLoader, Seq(listenerClass).toArray, new InvocationHandler { def invoke(proxy: AnyRef, m: Method, args: Array[AnyRef]): AnyRef = { onChange() null } }) } @throws[Throwable]("If we were not able to successfully load JNotify") def ensureLoaded(): Unit = { removeWatchMethod.invoke(null, 0.asInstanceOf[java.lang.Integer]) } } // Tri state - null means no attempt to load yet, None means failed load, Some means successful load @volatile var watchService: Option[Try[JNotifyFileWatchService]] = None def apply(targetDirectory: File): Try[FileWatchService] = { watchService match { case None => val ws = scala.util.control.Exception.allCatch.withTry { val classloader = GlobalStaticVar.get[ClassLoader]("FileWatchServiceJNotifyHack").getOrElse { val jnotifyJarFile = this.getClass.getClassLoader.asInstanceOf[java.net.URLClassLoader].getURLs .map(_.getFile) .find(_.contains("/jnotify")) .map(new File(_)) .getOrElse(sys.error("Missing JNotify?")) val nativeLibrariesDirectory = new File(targetDirectory, "native_libraries") if (!nativeLibrariesDirectory.exists) { // Unzip native libraries from the jnotify jar to target/native_libraries IO.unzip(jnotifyJarFile, targetDirectory, (name: String) => name.startsWith("native_libraries")) } val libs = new File(nativeLibrariesDirectory, System.getProperty("sun.arch.data.model") + "bits").getAbsolutePath // Hack to set java.library.path System.setProperty("java.library.path", { Option(System.getProperty("java.library.path")).map { existing => existing + java.io.File.pathSeparator + libs }.getOrElse(libs) }) val fieldSysPath = classOf[ClassLoader].getDeclaredField("sys_paths") fieldSysPath.setAccessible(true) fieldSysPath.set(null, null) // Create classloader just for jnotify val loader = new URLClassLoader(Array(jnotifyJarFile.toURI.toURL), null) GlobalStaticVar.set("FileWatchServiceJNotifyHack", loader) loader } val jnotifyClass = classloader.loadClass("net.contentobjects.jnotify.JNotify") val jnotifyListenerClass = classloader.loadClass("net.contentobjects.jnotify.JNotifyListener") val addWatchMethod = jnotifyClass.getMethod("addWatch", classOf[String], classOf[Int], classOf[Boolean], jnotifyListenerClass) val removeWatchMethod = jnotifyClass.getMethod("removeWatch", classOf[Int]) val d = new JNotifyDelegate(classloader, jnotifyListenerClass, addWatchMethod, removeWatchMethod) // Try it d.ensureLoaded() new JNotifyFileWatchService(d) } watchService = Some(ws) ws case Some(ws) => ws } } } private[play] class JDK7FileWatchService(logger: LoggerProxy) extends FileWatchService { import java.nio.file._ import StandardWatchEventKinds._ def watch(filesToWatch: Seq[File], onChange: () => Unit) = { val dirsToWatch = filesToWatch.filter { file => if (file.isDirectory) { true } else if (file.isFile) { // JDK7 WatchService can't watch files logger.warn("JDK7 WatchService only supports watching directories, but an attempt has been made to watch the file: " + file.getCanonicalPath) logger.warn("This file will not be watched. Either remove the file from playMonitoredFiles, or configure a different WatchService, eg:") logger.warn("PlayKeys.fileWatchService := play.runsupport.FileWatchService.jnotify(target.value)") false } else false } val watcher = FileSystems.getDefault.newWatchService() def watchDir(dir: File) = { dir.toPath.register(watcher, Array[WatchEvent.Kind[_]](ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY), // This custom modifier exists just for polling implementations of the watch service, and means poll every 2 seconds. // For non polling event based watchers, it has no effect. com.sun.nio.file.SensitivityWatchEventModifier.HIGH) } // Get all sub directories val allDirsToWatch = allSubDirectories(dirsToWatch) allDirsToWatch.foreach(watchDir) val thread = new Thread(new Runnable { def run() = { try { while (true) { val watchKey = watcher.take() val events = watchKey.pollEvents() import scala.collection.JavaConversions._ // If a directory has been created, we must watch it and its sub directories events.foreach { event => if (event.kind == ENTRY_CREATE) { val file = watchKey.watchable.asInstanceOf[Path].resolve(event.context.asInstanceOf[Path]).toFile if (file.isDirectory) { allSubDirectories(Seq(file)).foreach(watchDir) } } } onChange() watchKey.reset() } } catch { case NonFatal(e) => // Do nothing, this means the watch service has been closed, or we've been interrupted. } finally { // Just in case it wasn't closed. watcher.close() } } }, "sbt-play-watch-service") thread.setDaemon(true) thread.start() new FileWatcher { def stop() = { watcher.close() } } } private def allSubDirectories(dirs: Seq[File]) = { (dirs ** (DirectoryFilter -- HiddenFileFilter)).get.distinct } } /** * Watch service that delegates to a try. This allows it to exist without reporting an exception unless it's used. */ private[play] class OptionalFileWatchServiceDelegate(val watchService: Try[FileWatchService]) extends FileWatchService { def watch(filesToWatch: Seq[File], onChange: () => Unit) = { watchService.map(ws => ws.watch(filesToWatch, onChange)).get } } /** * Provides a global (cross classloader) static var. * * This does not leak classloaders (unless the value passed to it references a classloader that shouldn't be leaked). * It uses an MBeanServer to store an AtomicReference as an mbean, exposing the get method of the AtomicReference as an * mbean operation, so that the value can be retrieved. */ private[runsupport] object GlobalStaticVar { import javax.management._ import javax.management.modelmbean._ import java.lang.management._ import java.util.concurrent.atomic.AtomicReference private def objectName(name: String) = { new ObjectName(":type=GlobalStaticVar,name=" + name) } /** * Set a global static variable with the given name. */ def set(name: String, value: AnyRef): Unit = { val reference = new AtomicReference[AnyRef](value) // Now we construct a MBean that exposes the AtomicReference.get method val getMethod = classOf[AtomicReference[_]].getMethod("get") val getInfo = new ModelMBeanOperationInfo("The value", getMethod) val mmbi = new ModelMBeanInfoSupport("GlobalStaticVar", "A global static variable", null, // no attributes null, // no constructors Array(getInfo), // the operation null); // no notifications val mmb = new RequiredModelMBean(mmbi) mmb.setManagedResource(reference, "ObjectReference") // Register the Model MBean in the MBean Server ManagementFactory.getPlatformMBeanServer.registerMBean(mmb, objectName(name)) } /** * Get a global static variable by the given name. */ def get[T](name: String)(implicit ct: ClassTag[T]): Option[T] = { try { val value = ManagementFactory.getPlatformMBeanServer.invoke(objectName(name), "get", Array.empty, Array.empty) if (ct.runtimeClass.isInstance(value)) { Some(value.asInstanceOf[T]) } else { throw new ClassCastException(s"Global static var $name is not an instance of ${ct.runtimeClass}, but is actually a ${Option(value).fold("null")(_.getClass.getName)}") } } catch { case e: InstanceNotFoundException => None } } /** * Clear a global static variable with the given name. */ def remove(name: String): Unit = { try { ManagementFactory.getPlatformMBeanServer.unregisterMBean(objectName(name)) } catch { case e: InstanceNotFoundException => } } }
nelsonblaha/playframework
framework/src/play-jdbc/src/main/scala/play/api/db/DB.scala
<filename>framework/src/play-jdbc/src/main/scala/play/api/db/DB.scala<gh_stars>0 /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api.db import java.sql.Connection import javax.sql.DataSource import play.api.Application /** * Provides a high-level API for getting JDBC connections. * * For example: * {{{ * val conn = DB.getConnection("customers") * }}} */ @deprecated(since = "2.4.3", message = "Use [[play.api.db.Database]]") object DB { private val dbCache = Application.instanceCache[DBApi] private def db(implicit app: Application): DBApi = dbCache(app) /** * Retrieves a JDBC connection. * * @param name data source name * @param autocommit when `true`, sets this connection to auto-commit * @return a JDBC connection */ def getConnection(name: String = "default", autocommit: Boolean = true)(implicit app: Application): Connection = db.database(name).getConnection(autocommit) /** * Retrieves a JDBC connection (autocommit is set to true). * * @param name data source name * @return a JDBC connection */ def getDataSource(name: String = "default")(implicit app: Application): DataSource = db.database(name).dataSource /** * Execute a block of code, providing a JDBC connection. The connection is * automatically released. * * @param name The datasource name. * @param autocommit when `true`, sets this connection to auto-commit * @param block Code block to execute. */ def withConnection[A](name: String = "default", autocommit: Boolean = true)(block: Connection => A)(implicit app: Application): A = db.database(name).withConnection(autocommit)(block) /** * Execute a block of code, providing a JDBC connection. The connection and all created statements are * automatically released. * * @param block Code block to execute. */ def withConnection[A](block: Connection => A)(implicit app: Application): A = db.database("default").withConnection(block) /** * Execute a block of code, in the scope of a JDBC transaction. * The connection and all created statements are automatically released. * The transaction is automatically committed, unless an exception occurs. * * @param name The datasource name. * @param block Code block to execute. */ def withTransaction[A](name: String = "default")(block: Connection => A)(implicit app: Application): A = db.database(name).withTransaction(block) /** * Execute a block of code, in the scope of a JDBC transaction. * The connection and all created statements are automatically released. * The transaction is automatically committed, unless an exception occurs. * * @param block Code block to execute. */ def withTransaction[A](block: Connection => A)(implicit app: Application): A = db.database("default").withTransaction(block) }
nelsonblaha/playframework
framework/src/play-ws/src/test/scala/play/api/libs/ws/WSRequestHolderSpec.scala
package play.api.libs.ws import org.specs2.mutable.Specification import play.api.test.WithApplication class WSRequestHolderSpec extends Specification { "WSRequestHolder" should { "give the full URL with the query string" in new WithApplication() { val ws = app.injector.instanceOf[WSClient] ws.url("http://foo.com").uri.toString must equalTo("http://foo.com") ws.url("http://foo.com").withQueryString("bar" -> "baz").uri.toString must equalTo("http://foo.com?bar=baz") ws.url("http://foo.com").withQueryString("bar" -> "baz", "bar" -> "bah").uri.toString must equalTo("http://foo.com?bar=bah&bar=baz") } "correctly URL-encode the query string part" in new WithApplication() { val ws = app.injector.instanceOf[WSClient] ws.url("http://foo.com").withQueryString("&" -> "=").uri.toString must equalTo("http://foo.com?%26=%3D") } } }
nelsonblaha/playframework
framework/src/play-streams/src/main/scala/play/api/libs/streams/Probes.scala
<filename>framework/src/play-streams/src/main/scala/play/api/libs/streams/Probes.scala package play.api.libs.streams import org.reactivestreams.{ Subscription, Subscriber, Publisher } /** * Probes, for debugging reactive streams. */ object Probes { private trait Probe { def startTime: Long def time = System.nanoTime() - startTime def probeName: String def log[T](method: String, message: String = "")(block: => T) = { val threadName = Thread.currentThread().getName try { println(s"ENTER $probeName.$method at $time in $threadName: $message") block } catch { case e: Exception => println(s"CATCH $probeName.$method ${e.getClass}: ${e.getMessage}") throw e } finally { println(s"LEAVE $probeName.$method at $time") } } } def publisherProbe[T](name: String, publisher: Publisher[T], messageLogger: T => String = (t: T) => t.toString): Publisher[T] = new Publisher[T] with Probe { val probeName = name val startTime = System.nanoTime() def subscribe(subscriber: Subscriber[_ >: T]) = { log("subscribe", subscriber.toString)(publisher.subscribe(subscriberProbe(name, subscriber, messageLogger, startTime))) } } def subscriberProbe[T](name: String, subscriber: Subscriber[_ >: T], messageLogger: T => String = (t: T) => t.toString, start: Long = System.nanoTime()): Subscriber[T] = new Subscriber[T] with Probe { val probeName = name val startTime = start def onError(t: Throwable) = log("onError", s"${t.getClass}: ${t.getMessage}")(subscriber.onError(t)) def onSubscribe(subscription: Subscription) = log("onSubscribe", subscription.toString)(subscriber.onSubscribe(subscriptionProbe(name, subscription, start))) def onComplete() = log("onComplete")(subscriber.onComplete()) def onNext(t: T) = log("onNext", messageLogger(t))(subscriber.onNext(t)) } def subscriptionProbe(name: String, subscription: Subscription, start: Long = System.nanoTime()): Subscription = new Subscription with Probe { val probeName = name val startTime = start def cancel() = log("cancel")(subscription.cancel()) def request(n: Long) = log("request", n.toString)(subscription.request(n)) } }
nelsonblaha/playframework
framework/src/play-ws/src/main/scala/play/api/libs/ws/ssl/package.scala
<reponame>nelsonblaha/playframework<filename>framework/src/play-ws/src/main/scala/play/api/libs/ws/ssl/package.scala<gh_stars>1-10 /* * * * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> * */ package play.api.libs.ws import java.security.cert.{ PKIXCertPathValidatorResult, CertPathValidatorResult, Certificate, X509Certificate } import scala.util.Properties.{ isJavaAtLeast, javaVmName } package object ssl { import scala.language.implicitConversions implicit def certificate2X509Certificate(cert: java.security.cert.Certificate): X509Certificate = { cert.asInstanceOf[X509Certificate] } implicit def arrayCertsToListCerts(chain: Array[Certificate]): java.util.List[Certificate] = { import scala.collection.JavaConverters._ chain.toList.asJava } implicit def certResult2PKIXResult(result: CertPathValidatorResult): PKIXCertPathValidatorResult = { result.asInstanceOf[PKIXCertPathValidatorResult] } def debugChain(chain: Array[X509Certificate]): Seq[String] = { chain.map { cert => s"${cert.getSubjectDN.getName}" } } def foldVersion[T](run16: => T, runHigher: => T): T = { System.getProperty("java.specification.version") match { case "1.6" => run16 case higher => runHigher } } def isOpenJdk: Boolean = javaVmName contains "OpenJDK" // NOTE: Some SSL classes in OpenJDK 6 are in the same locations as JDK 7 def foldRuntime[T](older: => T, newer: => T): T = { if (isJavaAtLeast("1.7") || isOpenJdk) newer else older } }
nelsonblaha/playframework
framework/src/sbt-plugin/src/sbt-test/play-sbt-plugin/multiproject/transitive/app/Transitive.scala
<reponame>nelsonblaha/playframework /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ object Transitive
nelsonblaha/playframework
documentation/manual/working/scalaGuide/main/http/code/ScalaContentNegotiation.scala
<filename>documentation/manual/working/scalaGuide/main/http/code/ScalaContentNegotiation.scala /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package scalaguide.http.scalacontentnegotiation { import play.api.mvc._ import play.api.test._ import play.api.test.Helpers._ import org.specs2.mutable.Specification import play.api.libs.json._ import org.junit.runner.RunWith import org.specs2.runner.JUnitRunner import scala.concurrent.Future import org.specs2.execute.AsResult @RunWith(classOf[JUnitRunner]) class ScalaContentNegotiation extends Specification with Controller { "A Scala Content Negotiation" should { "negotiate accept type" in { //#negotiate_accept_type val list = Action { implicit request => val items = Item.findAll render { case Accepts.Html() => Ok(views.html.list(items)) case Accepts.Json() => Ok(Json.toJson(items)) } } //#negotiate_accept_type val requestHtml = FakeRequest().withHeaders(ACCEPT -> "text/html") assertAction(list, OK, requestHtml)(r => contentAsString(r) === "<html>1,2,3</html>") val requestJson = FakeRequest().withHeaders(ACCEPT -> "application/json") assertAction(list, OK, requestJson)(r => contentAsString(r) === "[1,2,3]") } "negotiate accept type" in { val list = Action { implicit request => def ??? = Ok("ok") //#extract_custom_accept_type val AcceptsMp3 = Accepting("audio/mp3") render { case AcceptsMp3() => ??? } } //#extract_custom_accept_type val requestHtml = FakeRequest().withHeaders(ACCEPT -> "audio/mp3") assertAction(list, OK, requestHtml)(r => contentAsString(r) === "ok") } } def assertAction[A, T: AsResult](action: Action[A], expectedResponse: Int = OK, request: Request[A] = FakeRequest())(assertions: Future[Result] => T) = { running(FakeApplication()) { val result = action(request) status(result) must_== expectedResponse assertions(result) } } object Item { def findAll = List(1, 2, 3) } } } package views.html { object list { def apply(items: Seq[Int]) = items.mkString("<html>", ",", "</html>") } }
nelsonblaha/playframework
documentation/manual/working/scalaGuide/main/tests/code/specs2/ExampleEssentialActionSpec.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package scalaguide.tests.specs2 import play.api.mvc._ import play.api.test._ import play.api.mvc.Results._ import play.api.libs.json.Json // #scalatest-exampleessentialactionspec object ExampleEssentialActionSpec extends PlaySpecification { "An essential action" should { "can parse a JSON body" in new WithApplication() { val action: EssentialAction = Action { request => val value = (request.body.asJson.get \ "field").as[String] Ok(value) } val request = FakeRequest(POST, "/").withJsonBody(Json.parse("""{ "field": "value" }""")) val result = call(action, request) status(result) mustEqual OK contentAsString(result) mustEqual "value" } } } // #scalatest-exampleessentialactionspec
nelsonblaha/playframework
framework/src/play/src/test/scala/play/api/libs/iteratee/TestChannel.scala
<filename>framework/src/play/src/test/scala/play/api/libs/iteratee/TestChannel.scala /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api.libs.iteratee import java.lang.{ Boolean => JBoolean } import java.util.concurrent.LinkedBlockingQueue import java.util.function.{ BiFunction, Function } import scala.concurrent.duration._ /** * Implementation of Concurrent.Channel for testing. * Can be queried for expected chunks and end calls. */ class TestChannel[A](defaultTimeout: Duration) extends Concurrent.Channel[A] { def this() = this(5.seconds) private val chunks = new LinkedBlockingQueue[Input[A]] private val ends = new LinkedBlockingQueue[Option[Throwable]] def push(chunk: Input[A]): Unit = { chunks.offer(chunk) } def end(e: Throwable): Unit = { ends.offer(Some(e)) } def end(): Unit = { ends.offer(None) } private def takeChunk(timeout: Duration): Input[A] = { if (timeout.isFinite) chunks.poll(timeout.length, timeout.unit) else chunks.take } def expect(expected: A): A = expect(expected, defaultTimeout) def expect(expected: A, timeout: Duration): A = expect(expected, timeout, _ == _) def expect(expected: A, test: BiFunction[A, A, JBoolean]): A = expect(expected, defaultTimeout, test) def expect(expected: A, timeout: Duration, test: BiFunction[A, A, JBoolean]): A = expect(expected, timeout, test.apply(_, _)) def expect(expected: A, test: (A, A) => Boolean): A = expect(expected, defaultTimeout, test) def expect(expected: A, timeout: Duration, test: (A, A) => Boolean): A = { takeChunk(timeout) match { case null => throw new AssertionError(s"timeout ($timeout) waiting for $expected") case Input.El(input) => assert(test(expected, input), s"expected [$expected] but found [$input]") input case other => throw new AssertionError(s"expected Input.El [$expected] but found [$other]") } } def expectEOF(): Input[A] = expectEOF(defaultTimeout) def expectEOF(timeout: Duration): Input[A] = { takeChunk(timeout) match { case null => throw new AssertionError(s"timeout ($timeout) waiting for EOF") case eof @ Input.EOF => eof case other => throw new AssertionError(s"expected EOF but found [$other]") } } private def takeEnd(timeout: Duration): Option[Throwable] = { if (timeout.isFinite) ends.poll(timeout.length, timeout.unit) else ends.take } def expectEnd[T](expected: Class[T]): T = expectEnd(expected, defaultTimeout) def expectEnd[T](expected: Class[T], timeout: Duration): T = { val end = takeEnd(timeout) assert(end ne null, s"timeout ($timeout) waiting for end with failure [$expected]") end match { case Some(throwable) => assert(expected isInstance throwable, s"expected end with failure [$expected] but found [$throwable]") throwable.asInstanceOf[T] case None => throw new AssertionError(s"expected end with failure [$expected] but found end (without failure)") } } def expectEnd(): Unit = expectEnd(defaultTimeout) def expectEnd(timeout: Duration): Unit = { val end = takeEnd(timeout) assert(end ne null, s"timeout ($timeout) waiting for end") if (end.isDefined) throw new AssertionError(s"expected end (without failure) but found [${end.get}]") } def expectEmpty(): Unit = { assert(chunks.isEmpty, s"expected empty chunks but found $chunks") assert(ends.isEmpty, s"expected empty ends but found $ends") } }
nelsonblaha/playframework
framework/src/play-streams/src/main/scala/play/api/libs/streams/impl/EnumeratorPublisher.scala
package play.api.libs.streams.impl import org.reactivestreams._ import play.api.libs.concurrent.StateMachine import play.api.libs.iteratee._ import scala.concurrent.Promise import scala.util.{ Failure, Success, Try } import scala.language.higherKinds /** * Creates Subscriptions that link Subscribers to an Enumerator. */ private[streams] trait EnumeratorSubscriptionFactory[T] extends SubscriptionFactory[T] { def enum: Enumerator[T] def emptyElement: Option[T] override def createSubscription[U >: T]( subr: Subscriber[U], onSubscriptionEnded: SubscriptionHandle[U] => Unit) = { new EnumeratorSubscription[T, U](enum, emptyElement, subr, onSubscriptionEnded) } } /** * Adapts an Enumerator to a Publisher. */ private[streams] final class EnumeratorPublisher[T]( val enum: Enumerator[T], val emptyElement: Option[T] = None) extends RelaxedPublisher[T] with EnumeratorSubscriptionFactory[T] private[streams] object EnumeratorSubscription { /** * Internal state of the Publisher. */ sealed trait State[+T] /** * An active Subscription with n outstanding requested elements. * @param n Elements that have been requested by the Subscriber. May be 0. * @param attached The attached Iteratee we're using to read from the * Enumerator. Will be Unattached until the first element is requested. */ final case class Requested[T](n: Long, attached: IterateeState[T]) extends State[T] /** * A Subscription completed by the Publisher. */ final case object Completed extends State[Nothing] /** * A Subscription cancelled by the Subscriber. */ final case object Cancelled extends State[Nothing] /** * We use an Iteratee to read from the Enumerator. Controlled by the * extendIteratee method. */ sealed trait IterateeState[+T] /** * The Iteratee state before any elements have been requested, before * we've attached an Iteratee to the Enumerator. */ final case object Unattached extends IterateeState[Nothing] /** * The Iteratee state when we're reading from the Enumerator. */ final case class Attached[T](link: Promise[Iteratee[T, Unit]]) extends IterateeState[T] } import EnumeratorSubscription._ /** * Adapts an Enumerator to a Publisher. */ private[streams] class EnumeratorSubscription[T, U >: T]( enum: Enumerator[T], emptyElement: Option[T], subr: Subscriber[U], onSubscriptionEnded: SubscriptionHandle[U] => Unit) extends StateMachine[State[T]](initialState = Requested[T](0, Unattached)) with Subscription with SubscriptionHandle[U] { // SubscriptionHandle methods override def start(): Unit = { subr.onSubscribe(this) } override def subscriber: Subscriber[U] = subr override def isActive: Boolean = { // run immediately, don't need to wait for exclusive access state match { case Requested(_, _) => true case Completed | Cancelled => false } } // 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 Requested(0, its) => state = Requested(elements, extendIteratee(its)) case Requested(n, its) => state = Requested(n + elements, its) case Completed | Cancelled => () // FIXME: Check rules } } override def cancel(): Unit = exclusive { case Requested(_, its) => val cancelLink: Iteratee[T, Unit] = Done(()) its match { case Unattached => enum(cancelLink) case Attached(link0) => link0.success(cancelLink) } state = Cancelled case Cancelled | Completed => () } // Methods called by the iteratee when it receives input /** * Called when the Iteratee received Input.El, or when it recived * Input.Empty and the Publisher's `emptyElement` is Some(el). */ private def elementEnumerated(el: T): Unit = exclusive { case Requested(1, its) => subr.onNext(el) state = Requested(0, its) case Requested(n, its) => subr.onNext(el) state = Requested(n - 1, extendIteratee(its)) case Cancelled => () case Completed => throw new IllegalStateException("Shouldn't receive another element once completed") } /** * Called when the Iteratee received Input.Empty and the Publisher's * `emptyElement` value is `None` */ private def emptyEnumerated(): Unit = exclusive { case Requested(n, its) => state = Requested(n, extendIteratee(its)) case Cancelled => () case Completed => throw new IllegalStateException("Shouldn't receive an empty input once completed") } /** * Called when the Iteratee received Input.EOF */ private def eofEnumerated(): Unit = exclusive { case Requested(_, _) => subr.onComplete() state = Completed case Cancelled => () case Completed => throw new IllegalStateException("Shouldn't receive EOF once completed") } /** * Called when the enumerator is complete. If the enumerator didn't feed * EOF into the iteratee, then this is where the subscriber will be * completed. If the enumerator encountered an error, this error will be * sent to the subscriber. */ private def enumeratorApplicationComplete(result: Try[_]): Unit = exclusive { case Requested(_, _) => state = Completed result match { case Failure(error) => subr.onError(error) case Success(_) => subr.onComplete() } case Cancelled => () case Completed => () // Subscriber was already completed when the enumerator produced EOF } /** * Called when we want to read an input element from the Enumerator. This * method attaches an Iteratee to the end of the Iteratee chain. The * Iteratee it attaches will call one of the `*Enumerated` methods when * it recesives input. */ private def extendIteratee(its: IterateeState[T]): IterateeState[T] = { val link = Promise[Iteratee[T, Unit]]() val linkIteratee: Iteratee[T, Unit] = Iteratee.flatten(link.future) val iteratee: Iteratee[T, Unit] = Cont { input => input match { case Input.El(el) => elementEnumerated(el) case Input.Empty => emptyElement match { case None => emptyEnumerated() case Some(el) => elementEnumerated(el) } case Input.EOF => eofEnumerated() } linkIteratee } its match { case Unattached => enum(iteratee).onComplete(enumeratorApplicationComplete)(Execution.trampoline) case Attached(link0) => link0.success(iteratee) } Attached(link) } }
nelsonblaha/playframework
framework/src/play-ws/src/main/scala/play/api/libs/ws/ssl/debug/FixCertpathDebugLogging.scala
<gh_stars>1-10 /* * * * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> * */ package play.api.libs.ws.ssl.debug import java.security.AccessController import scala.util.control.NonFatal import sun.security.util.Debug /** * This singleton object turns on "certpath" debug logging (originally based off the "java.security.debug" debug flag), * and swaps out references to internal Sun JSSE classes to ensure that the new debug logging settings are honored, and * that debugging can be turned on dynamically, even after static class block initialization has been completed. It * does this using some {{sun.misc.Unsafe}} black magic. * * Note that currently the only functionality is to turn debug output ON, with the assumption that all output will * go to an appropriately configured logger that can ignore calls to it. There is no "off" method. */ object FixCertpathDebugLogging { val logger = org.slf4j.LoggerFactory.getLogger("play.api.libs.ws.ssl.debug.FixCertpathDebugLogging") class MonkeyPatchSunSecurityUtilDebugAction(val newDebug: Debug, val newOptions: String) extends FixLoggingAction { val logger = org.slf4j.LoggerFactory.getLogger("play.api.libs.ws.ssl.debug.FixCertpathDebugLogging.MonkeyPatchSunSecurityUtilDebugAction") val initialResource = "/sun/security/provider/certpath/Builder.class" val debugType = classOf[Debug] /** * Returns true if this class has an instance of {{Debug.getInstance("certpath")}}, false otherwise. * * @param className the name of the class. * @return true if this class should be returned in the set of findClasses, false otherwise. */ def isValidClass(className: String): Boolean = { if (className.startsWith("java.security.cert")) return true if (className.startsWith("sun.security.provider.certpath")) return true if (className.equals("sun.security.x509.InhibitAnyPolicyExtension")) return true false } /** * Returns true if the new options contains certpath, false otherwise. If it does not contain certpath, * then set the fields to null (which will disable logging). * * @return */ def isUsingDebug: Boolean = (newOptions != null) && newOptions.contains("certpath") def run() { System.setProperty("java.security.debug", newOptions) logger.debug(s"run: debugType = $debugType") val debugValue = if (isUsingDebug) newDebug else null var isPatched = false for ( debugClass <- findClasses; debugField <- debugClass.getDeclaredFields ) { if (isValidField(debugField, debugType)) { logger.debug(s"run: Patching $debugClass with $debugValue") monkeyPatchField(debugField, debugValue) isPatched = true } } // Add an assertion here in case the class location changes, so the tests fail... if (!isPatched) { throw new IllegalStateException("No debug classes found!") } // Switch out the args (for certpath loggers that AREN'T static and final) // This will result in those classes using the base Debug class which will write to System.out, but // I don't know how to switch out the Debug.getInstance method itself without using a java agent. val argsField = debugType.getDeclaredField("args") monkeyPatchField(argsField, newOptions) } } /** * Extends {{sun.security.util.Debug}} to delegate println to a logger. * * @param logger the logger which will receive debug calls. */ class SunSecurityUtilDebugLogger(logger: org.slf4j.Logger) extends sun.security.util.Debug { override def println(message: String) { if (logger.isDebugEnabled) { logger.debug(message) } } override def println() { if (logger.isDebugEnabled) { logger.debug("") } } } def apply(newOptions: String, debugOption: Option[Debug] = None) { logger.trace(s"apply: newOptions = $newOptions, debugOption = $debugOption") try { val newDebug = debugOption match { case Some(d) => d case None => new Debug() } val action = new MonkeyPatchSunSecurityUtilDebugAction(newDebug, newOptions) AccessController.doPrivileged(action) } catch { case NonFatal(e) => throw new IllegalStateException("CertificateDebug configuration error", e) } } }
nelsonblaha/playframework
framework/src/play-server/src/main/scala/play/core/server/ServerStartException.scala
<gh_stars>1-10 /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.core.server /** * Indicates an issue with starting a server, e.g. a problem reading its * configuration. */ final case class ServerStartException(message: String, cause: Option[Throwable] = None) extends Exception(message, cause.orNull)
nelsonblaha/playframework
documentation/manual/detailedTopics/configuration/filters/code/CorsFilter.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package detailedtopics.configuration.cors.sapi //#filters import javax.inject.Inject import play.api.http.HttpFilters import play.filters.cors.CORSFilter class Filters @Inject() (corsFilter: CORSFilter) extends HttpFilters { def filters = Seq(corsFilter) } //#filters
nelsonblaha/playframework
framework/src/sbt-plugin/src/main/scala/play/sbt/PlayRunHook.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.sbt import java.net.InetSocketAddress /** * The represents an object which "hooks into" play run, and is used to * apply startup/cleanup actions around a play application. */ trait PlayRunHook extends play.runsupport.RunHook object PlayRunHook { def makeRunHookFromOnStarted(f: (java.net.InetSocketAddress) => Unit): PlayRunHook = { // We create an object for a named class... object OnStartedPlayRunHook extends PlayRunHook { override def afterStarted(addr: InetSocketAddress): Unit = f(addr) } OnStartedPlayRunHook } def makeRunHookFromOnStopped(f: () => Unit): PlayRunHook = { object OnStoppedPlayRunHook extends PlayRunHook { override def afterStopped(): Unit = f() } OnStoppedPlayRunHook } }
nelsonblaha/playframework
framework/src/play/src/main/scala/play/core/parsers/Multipart.scala
<filename>framework/src/play/src/main/scala/play/core/parsers/Multipart.scala /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.core.parsers import akka.stream.Materializer import akka.stream.scaladsl._ import akka.stream.stage.{ TerminationDirective, SyncDirective, Context, PushPullStage } import akka.util.ByteString import play.api.Play import play.api.libs.Files.TemporaryFile import play.api.libs.streams.{ Streams, Accumulator } import play.api.mvc._ import play.api.mvc.MultipartFormData._ import play.api.http.Status._ import scala.annotation.tailrec import scala.collection.mutable.ListBuffer import scala.concurrent.Future import play.api.libs.iteratee.Execution.Implicits.trampoline /** * Utilities for handling multipart bodies */ object Multipart { private final val maxHeaderBuffer = 4096 /** * Parses the stream into a stream of [[play.api.mvc.MultipartFormData.Part]] to be handled by `partHandler`. * * @param maxMemoryBufferSize The maximum amount of data to parse into memory. * @param partHandler The accumulator to handle the parts. */ def partParser[A](maxMemoryBufferSize: Int)(partHandler: Accumulator[Part[Source[ByteString, _]], Either[Result, A]]): BodyParser[A] = BodyParser { request => val maybeBoundary = for { mt <- request.mediaType (_, value) <- mt.parameters.find(_._1.equalsIgnoreCase("boundary")) boundary <- value } yield boundary maybeBoundary.map { boundary => val multipartFlow = Flow[ByteString] .transform(() => new BodyPartParser(boundary, maxMemoryBufferSize, maxHeaderBuffer)) .splitWhen(_.isLeft) .map { source => source.prefixAndTail(1) .map { case (Seq(Left(part: FilePart[_])), body) => part.copy[Source[ByteString, _]](ref = body.collect { case Right(bytes) => bytes }) case (Seq(Left(other)), _) => other.asInstanceOf[Part[Nothing]] } }.flatten(FlattenStrategy.concat) partHandler.through(multipartFlow) }.getOrElse { Accumulator.done(createBadResult("Missing boundary header")(request)) } } /** * Parses the request body into a Multipart body. * * @param maxMemoryBufferSize The maximum amount of data to parse into memory. * @param filePartHandler The accumulator to handle the file parts. */ def multipartParser[A](maxMemoryBufferSize: Int, filePartHandler: FilePartHandler[A])(implicit mat: Materializer): BodyParser[MultipartFormData[A]] = BodyParser { request => partParser(maxMemoryBufferSize) { val handleFileParts = Flow[Part[Source[ByteString, _]]].mapAsync(1) { case filePart: FilePart[Source[ByteString, _]] => filePartHandler(FileInfo(filePart.key, filePart.filename, filePart.contentType)).run(filePart.ref) case other: Part[Nothing] => Future.successful(other) } val multipartAccumulator = Accumulator(Sink.fold[Seq[Part[A]], Part[A]](Vector.empty)(_ :+ _)).mapFuture { parts => def parseError = parts.collectFirst { case ParseError(msg) => createBadResult(msg)(request) } def bufferExceededError = parts.collectFirst { case MaxMemoryBufferExceeded(msg) => createBadResult(msg, REQUEST_ENTITY_TOO_LARGE)(request) } parseError orElse bufferExceededError getOrElse { Future.successful(Right(MultipartFormData( parts .collect { case dp: DataPart => dp }.groupBy(_.key) .map { case (key, partValues) => key -> partValues.map(_.value) }, parts.collect { case fp: FilePart[A] => fp }, parts.collect { case bad: BadPart => bad } ))) } } multipartAccumulator.through(handleFileParts) }(request) } type FilePartHandler[A] = FileInfo => Accumulator[ByteString, FilePart[A]] def handleFilePartAsTemporaryFile: FilePartHandler[TemporaryFile] = { case FileInfo(partName, filename, contentType) => val tempFile = TemporaryFile("multipartBody", "asTemporaryFile") Accumulator(Streams.outputStreamToSink(() => new java.io.FileOutputStream(tempFile.file))).map { _ => FilePart(partName, filename, contentType, tempFile) } } case class FileInfo( /** Name of the part in HTTP request (e.g. field name) */ partName: String, /** Name of the file */ fileName: String, /** Type of content (e.g. "application/pdf"), or `None` if unspecified. */ contentType: Option[String]) private[play] object FileInfoMatcher { private def split(str: String): List[String] = { var buffer = new java.lang.StringBuilder var escape: Boolean = false var quote: Boolean = false val result = new ListBuffer[String] def addPart() = { result += buffer.toString.trim buffer = new java.lang.StringBuilder } str foreach { case '\\' => buffer.append('\\') escape = true case '"' => buffer.append('"') if (!escape) quote = !quote escape = false case ';' => if (!quote) { addPart() } else { buffer.append(';') } escape = false case c => buffer.append(c) escape = false } addPart() result.toList } def unapply(headers: Map[String, String]): Option[(String, String, Option[String])] = { val KeyValue = """^([a-zA-Z_0-9]+)="?(.*?)"?$""".r for { values <- headers.get("content-disposition"). map(split(_).map(_.trim).map { // unescape escaped quotes case KeyValue(key, v) => (key.trim, v.trim.replaceAll("""\\"""", "\"")) case key => (key.trim, "") }.toMap) _ <- values.get("form-data") partName <- values.get("name") fileName <- values.get("filename") contentType = headers.get("content-type") } yield (partName, fileName, contentType) } } private[play] object PartInfoMatcher { def unapply(headers: Map[String, String]): Option[String] = { val KeyValue = """^([<KEY>]+)="(.*)"$""".r for { values <- headers.get("content-disposition").map( _.split(";").map(_.trim).map { case KeyValue(key, v) => (key.trim, v.trim) case key => (key.trim, "") }.toMap) _ <- values.get("form-data") partName <- values.get("name") } yield partName } } private def createBadResult[A](msg: String, status: Int = BAD_REQUEST): RequestHeader => Future[Either[Result, A]] = { request => Play.maybeApplication.fold(Future.successful(Left(Results.Status(status): Result)))( _.errorHandler.onClientError(request, status, msg).map(Left(_))) } private type RawPart = Either[Part[Unit], ByteString] private def byteChar(input: ByteString, ix: Int): Char = byteAt(input, ix).toChar private def byteAt(input: ByteString, ix: Int): Byte = if (ix < input.length) input(ix) else throw NotEnoughDataException private object NotEnoughDataException extends RuntimeException(null, null, false, false) private val crlfcrlf: ByteString = { ByteString("\r\n\r\n") } /** * Copied and then heavily modified to suit Play's needs from Akka HTTP akka.http.impl.engine.BodyPartParser. * * INTERNAL API * * see: http://tools.ietf.org/html/rfc2046#section-5.1.1 */ private final class BodyPartParser(boundary: String, maxMemoryBufferSize: Int, maxHeaderSize: Int) extends PushPullStage[ByteString, RawPart] { require(boundary.nonEmpty, "'boundary' parameter of multipart Content-Type must be non-empty") require(boundary.charAt(boundary.length - 1) != ' ', "'boundary' parameter of multipart Content-Type must not end with a space char") // phantom type for ensuring soundness of our parsing method setup sealed trait StateResult private[this] val needle: Array[Byte] = { val array = new Array[Byte](boundary.length + 4) array(0) = '\r'.toByte array(1) = '\n'.toByte array(2) = '-'.toByte array(3) = '-'.toByte System.arraycopy(boundary.getBytes("US-ASCII"), 0, array, 4, boundary.length) array } // we use the Boyer-Moore string search algorithm for finding the boundaries in the multipart entity, // see: http://www.cgjennings.ca/fjs/ and http://ijes.info/4/1/42544103.pdf private val boyerMoore = new BoyerMoore(needle) private var output = collection.immutable.Queue.empty[RawPart] private var state: ByteString ⇒ StateResult = tryParseInitialBoundary private var terminated = false override def onPush(input: ByteString, ctx: Context[RawPart]): SyncDirective = if (!terminated) { state(input) if (output.nonEmpty) ctx.push(dequeue()) else if (!terminated) ctx.pull() else ctx.finish() } else ctx.finish() override def onPull(ctx: Context[RawPart]): SyncDirective = { if (output.nonEmpty) ctx.push(dequeue()) else if (ctx.isFinishing) { if (terminated) ctx.finish() else ctx.pushAndFinish(Left(ParseError("Unexpected end of input"))) } else ctx.pull() } override def onUpstreamFinish(ctx: Context[RawPart]): TerminationDirective = ctx.absorbTermination() def tryParseInitialBoundary(input: ByteString): StateResult = // we don't use boyerMoore here because we are testing for the boundary *without* a // preceding CRLF and at a known location (the very beginning of the entity) try { if (boundary(input, 0)) { val ix = boundaryLength if (crlf(input, ix)) parseHeader(input, ix + 2, 0) else if (doubleDash(input, ix)) terminate() else parsePreamble(input, 0) } else parsePreamble(input, 0) } catch { case NotEnoughDataException ⇒ continue(input, 0)((newInput, _) ⇒ tryParseInitialBoundary(newInput)) } def parsePreamble(input: ByteString, offset: Int): StateResult = try { @tailrec def rec(index: Int): StateResult = { val needleEnd = boyerMoore.nextIndex(input, index) + needle.length if (crlf(input, needleEnd)) parseHeader(input, needleEnd + 2, 0) else if (doubleDash(input, needleEnd)) terminate() else rec(needleEnd) } rec(offset) } catch { case NotEnoughDataException ⇒ continue(input.takeRight(needle.length + 2), 0)(parsePreamble) } /** * Parsing the header is done by buffering up to 4096 bytes until CRLFCRLF is encountered. * * Then, the resulting ByteString is converted to a String, split into lines, and then split into keys and values. */ def parseHeader(input: ByteString, headerStart: Int, memoryBufferSize: Int): StateResult = { input.indexOfSlice(crlfcrlf, headerStart) match { case -1 if input.length - headerStart >= maxHeaderSize => bufferExceeded("Header length exceeded buffer size of " + memoryBufferSize) case -1 => continue(input, headerStart)(parseHeader(_, _, memoryBufferSize)) case headerEnd if headerEnd - headerStart >= maxHeaderSize => bufferExceeded("Header length exceeded buffer size of " + memoryBufferSize) case headerEnd => val headerString = input.slice(headerStart, headerEnd).utf8String val headers = headerString.lines.map { header => val key :: value = header.trim.split(":").toList (key.trim.toLowerCase(java.util.Locale.ENGLISH), value.mkString(":").trim) }.toMap val partStart = headerEnd + 4 // The amount of memory taken by the headers def headersSize = headers.foldLeft(0)((total, value) => total + value._1.length + value._2.length) headers match { case FileInfoMatcher(partName, fileName, contentType) => handleFilePart(input, partStart, memoryBufferSize + headersSize, partName, fileName, contentType) case PartInfoMatcher(name) => handleDataPart(input, partStart, memoryBufferSize + name.length, name) case _ => handleBadPart(input, partStart, memoryBufferSize + headersSize, headers) } } } def handleFilePart(input: ByteString, partStart: Int, memoryBufferSize: Int, partName: String, fileName: String, contentType: Option[String]): StateResult = { if (memoryBufferSize > maxMemoryBufferSize) { bufferExceeded(s"Memory buffer full ($maxMemoryBufferSize) on part $partName") } else { emit(FilePart(partName, fileName, contentType, ())) handleFileData(input, partStart, memoryBufferSize) } } def handleFileData(input: ByteString, offset: Int, memoryBufferSize: Int): StateResult = { try { val currentPartEnd = boyerMoore.nextIndex(input, offset) val needleEnd = currentPartEnd + needle.length if (crlf(input, needleEnd)) { emit(input.slice(offset, currentPartEnd)) parseHeader(input, needleEnd + 2, memoryBufferSize) } else if (doubleDash(input, needleEnd)) { emit(input.slice(offset, currentPartEnd)) terminate() } else { fail("Unexpected boundary") } } catch { case NotEnoughDataException => // we cannot emit all input bytes since the end of the input might be the start of the next boundary val emitEnd = input.length - needle.length - 2 if (emitEnd > offset) { emit(input.slice(offset, emitEnd)) continue(input.drop(emitEnd), 0)(handleFileData(_, _, memoryBufferSize)) } else { continue(input, offset)(handleFileData(_, _, memoryBufferSize)) } } } def handleDataPart(input: ByteString, partStart: Int, memoryBufferSize: Int, partName: String): StateResult = { try { val currentPartEnd = boyerMoore.nextIndex(input, partStart) val needleEnd = currentPartEnd + needle.length val newMemoryBufferSize = memoryBufferSize + (currentPartEnd - partStart) if (newMemoryBufferSize > maxMemoryBufferSize) { bufferExceeded("Memory buffer full on part " + partName) } else if (crlf(input, needleEnd)) { emit(DataPart(partName, input.slice(partStart, currentPartEnd).utf8String)) parseHeader(input, needleEnd + 2, newMemoryBufferSize) } else if (doubleDash(input, needleEnd)) { emit(DataPart(partName, input.slice(partStart, currentPartEnd).utf8String)) terminate() } else { fail("Unexpected boundary") } } catch { case NotEnoughDataException => if (memoryBufferSize + (input.length - partStart - needle.length) > maxMemoryBufferSize) { bufferExceeded("Memory buffer full on part " + partName) } continue(input, partStart)(handleDataPart(_, _, memoryBufferSize, partName)) } } def handleBadPart(input: ByteString, partStart: Int, memoryBufferSize: Int, headers: Map[String, String]): StateResult = { try { val currentPartEnd = boyerMoore.nextIndex(input, partStart) val needleEnd = currentPartEnd + needle.length if (crlf(input, needleEnd)) { emit(BadPart(headers)) parseHeader(input, needleEnd + 2, memoryBufferSize) } else if (doubleDash(input, needleEnd)) { emit(BadPart(headers)) terminate() } else { fail("Unexpected boundary") } } catch { case NotEnoughDataException => continue(input, partStart)(handleBadPart(_, _, memoryBufferSize, headers)) } } def emit(bytes: ByteString): Unit = if (bytes.nonEmpty) { output = output.enqueue(Right(bytes)) } def emit(part: Part[Unit]): Unit = { output = output.enqueue(Left(part)) } def dequeue(): RawPart = { val head = output.head output = output.tail head } def continue(input: ByteString, offset: Int)(next: (ByteString, Int) ⇒ StateResult): StateResult = { state = math.signum(offset - input.length) match { case -1 ⇒ more ⇒ next(input ++ more, offset) case 0 ⇒ next(_, 0) case 1 ⇒ throw new IllegalStateException } done() } def continue(next: (ByteString, Int) ⇒ StateResult): StateResult = { state = next(_, 0) done() } def bufferExceeded(message: String): StateResult = { emit(MaxMemoryBufferExceeded(message)) terminate() } def fail(message: String): StateResult = { emit(ParseError(message)) terminate() } def terminate(): StateResult = { terminated = true done() } def done(): StateResult = null // StateResult is a phantom type // the length of the needle without the preceding CRLF def boundaryLength = needle.length - 2 @tailrec def boundary(input: ByteString, offset: Int, ix: Int = 2): Boolean = (ix == needle.length) || (byteAt(input, offset + ix - 2) == needle(ix)) && boundary(input, offset, ix + 1) def crlf(input: ByteString, offset: Int): Boolean = byteChar(input, offset) == '\r' && byteChar(input, offset + 1) == '\n' def doubleDash(input: ByteString, offset: Int): Boolean = byteChar(input, offset) == '-' && byteChar(input, offset + 1) == '-' } /** * Copied from Akka HTTP. * * Straight-forward Boyer-Moore string search implementation. */ private class BoyerMoore(needle: Array[Byte]) { require(needle.length > 0, "needle must be non-empty") private[this] val nl1 = needle.length - 1 private[this] val charTable: Array[Int] = { val table = Array.fill(256)(needle.length) @tailrec def rec(i: Int): Unit = if (i < nl1) { table(needle(i) & 0xff) = nl1 - i rec(i + 1) } rec(0) table } private[this] val offsetTable: Array[Int] = { val table = new Array[Int](needle.length) @tailrec def isPrefix(i: Int, j: Int): Boolean = i == needle.length || needle(i) == needle(j) && isPrefix(i + 1, j + 1) @tailrec def loop1(i: Int, lastPrefixPosition: Int): Unit = if (i >= 0) { val nextLastPrefixPosition = if (isPrefix(i + 1, 0)) i + 1 else lastPrefixPosition table(nl1 - i) = nextLastPrefixPosition - i + nl1 loop1(i - 1, nextLastPrefixPosition) } loop1(nl1, needle.length) @tailrec def suffixLength(i: Int, j: Int, result: Int): Int = if (i >= 0 && needle(i) == needle(j)) suffixLength(i - 1, j - 1, result + 1) else result @tailrec def loop2(i: Int): Unit = if (i < nl1) { val sl = suffixLength(i, nl1, 0) table(sl) = nl1 - i + sl loop2(i + 1) } loop2(0) table } /** * Returns the index of the next occurrence of `needle` in `haystack` that is >= `offset`. * If none is found a `NotEnoughDataException` is thrown. */ def nextIndex(haystack: ByteString, offset: Int): Int = { @tailrec def rec(i: Int, j: Int): Int = { val byte = byteAt(haystack, i) if (needle(j) == byte) { if (j == 0) i // found else rec(i - 1, j - 1) } else rec(i + math.max(offsetTable(nl1 - j), charTable(byte & 0xff)), nl1) } rec(offset + nl1, nl1) } } }
nelsonblaha/playframework
framework/src/play-filters-helpers/src/main/scala/play/filters/csrf/csrf.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.filters.csrf import java.util.Optional import akka.stream.Materializer import com.typesafe.config.ConfigMemorySize import play.filters.csrf.CSRF.{ CSRFHttpErrorHandler, ErrorHandler } import play.mvc.Http import play.utils.Reflect import scala.compat.java8.FutureConverters import scala.concurrent.Future import play.api._ import play.api.inject.{ Binding, Module } import play.api.http.HttpErrorHandler import play.api.libs.Crypto import play.api.mvc.Results._ import play.api.mvc._ import play.core.j.JavaHelpers import javax.inject.{ Singleton, Provider, Inject } /** * CSRF configuration. * * @param tokenName The name of the token. * @param cookieName If defined, the name of the cookie to read the token from/write the token to. * @param secureCookie If using a cookie, whether it should be secure. * @param httpOnlyCookie If using a cookie, whether it should have the HTTP only flag. * @param postBodyBuffer How much of the POST body should be buffered if checking the body for a token. * @param signTokens Whether tokens should be signed. * @param checkMethod Returns true if a request for that method should be checked. * @param checkContentType Returns true if a request for that content type should be checked. * @param headerName The name of the HTTP header to check for tokens from. * @param headerBypass Whether CSRF check can be bypassed by the presence of certain headers, such as X-Requested-By. */ case class CSRFConfig(tokenName: String = "csrfToken", cookieName: Option[String] = None, secureCookie: Boolean = false, httpOnlyCookie: Boolean = false, createIfNotFound: (RequestHeader) => Boolean = CSRFConfig.defaultCreateIfNotFound, postBodyBuffer: Long = 102400, signTokens: Boolean = true, checkMethod: String => Boolean = CSRFConfig.UnsafeMethods, checkContentType: Option[String] => Boolean = _.exists(CSRFConfig.UnsafeContentTypes), headerName: String = "Csrf-Token", headerBypass: Boolean = true) object CSRFConfig { private val UnsafeContentTypes = Set("application/x-www-form-urlencoded", "text/plain", "multipart/form-data") private val UnsafeMethods = Set("POST") private def defaultCreateIfNotFound(request: RequestHeader) = { // If the request isn't accepting HTML, then it won't be rendering a form, so there's no point in generating a // CSRF token for it. (request.method == "GET" || request.method == "HEAD") && (request.accepts("text/html") || request.accepts("application/xml+xhtml")) } private[play] val HeaderNoCheck = "nocheck" def global = Play.maybeApplication.map(_.injector.instanceOf[CSRFConfig]).getOrElse(CSRFConfig()) def fromConfiguration(conf: Configuration): CSRFConfig = { val config = PlayConfig(conf).getDeprecatedWithFallback("play.filters.csrf", "csrf") val methodWhiteList = config.get[Seq[String]]("method.whiteList").toSet val methodBlackList = config.get[Seq[String]]("method.blackList").toSet val checkMethod: String => Boolean = if (methodWhiteList.nonEmpty) { !methodWhiteList.contains(_) } else { methodBlackList.contains } val contentTypeWhiteList = config.get[Seq[String]]("contentType.whiteList").toSet val contentTypeBlackList = config.get[Seq[String]]("contentType.blackList").toSet val checkContentType: String => Boolean = if (contentTypeWhiteList.nonEmpty) { !contentTypeWhiteList.contains(_) } else { contentTypeBlackList.contains } CSRFConfig( tokenName = config.get[String]("token.name"), cookieName = config.get[Option[String]]("cookie.name"), secureCookie = config.get[Boolean]("cookie.secure"), httpOnlyCookie = config.get[Boolean]("cookie.httpOnly"), postBodyBuffer = config.get[ConfigMemorySize]("body.bufferSize").toBytes, signTokens = config.get[Boolean]("token.sign"), checkMethod = checkMethod, checkContentType = _.exists(checkContentType), headerName = config.get[String]("header.name"), headerBypass = config.get[Boolean]("header.bypass") ) } } @Singleton class CSRFConfigProvider @Inject() (config: Configuration) extends Provider[CSRFConfig] { lazy val get = CSRFConfig.fromConfiguration(config) } object CSRF { private[csrf] val filterLogger = play.api.Logger("play.filters") /** * A CSRF token */ case class Token(value: String) object Token { val RequestTag = "CSRF_TOKEN" implicit def getToken(implicit request: RequestHeader): Token = { CSRF.getToken(request).getOrElse(sys.error("Missing CSRF Token")) } } /** * Extract token from current request */ def getToken(request: RequestHeader): Option[Token] = { val global = CSRFConfig.global // First check the tags, this is where tokens are added if it's added to the current request val token = request.tags.get(Token.RequestTag) // Check cookie if cookie name is defined .orElse(global.cookieName.flatMap(n => request.cookies.get(n).map(_.value))) // Check session .orElse(request.session.get(global.tokenName)) if (global.signTokens) { // Extract the signed token, and then resign it. This makes the token random per request, preventing the BREACH // vulnerability token.flatMap(Crypto.extractSignedToken) .map(token => Token(Crypto.signToken(token))) } else { token.map(Token.apply) } } /** * Extract token from current Java request * * @param request The request to extract the token from * @return The token, if found. */ def getToken(request: play.mvc.Http.Request): Optional[Token] = { Optional.ofNullable(getToken(request._underlyingHeader()).orNull) } /** * A token provider, for generating and comparing tokens. * * This abstraction allows the use of randomised tokens. */ trait TokenProvider { /** Generate a token */ def generateToken: String /** Compare two tokens */ def compareTokens(tokenA: String, tokenB: String): Boolean } class TokenProviderProvider @Inject() (config: CSRFConfig) extends Provider[TokenProvider] { override val get = config.signTokens match { case true => SignedTokenProvider case false => UnsignedTokenProvider } } class ConfigTokenProvider(config: => CSRFConfig) extends TokenProvider { lazy val underlying = new TokenProviderProvider(config).get def generateToken = underlying.generateToken def compareTokens(tokenA: String, tokenB: String) = underlying.compareTokens(tokenA, tokenB) } object SignedTokenProvider extends TokenProvider { def generateToken = Crypto.generateSignedToken def compareTokens(tokenA: String, tokenB: String) = Crypto.compareSignedTokens(tokenA, tokenB) } object UnsignedTokenProvider extends TokenProvider { def generateToken = Crypto.generateToken def compareTokens(tokenA: String, tokenB: String) = Crypto.constantTimeEquals(tokenA, tokenB) } /** * This trait handles the CSRF error. */ trait ErrorHandler { /** Handle a result */ def handle(req: RequestHeader, msg: String): Future[Result] } class CSRFHttpErrorHandler @Inject() (httpErrorHandler: HttpErrorHandler) extends ErrorHandler { import play.api.http.Status.FORBIDDEN def handle(req: RequestHeader, msg: String) = httpErrorHandler.onClientError(req, FORBIDDEN, msg) } object DefaultErrorHandler extends ErrorHandler { def handle(req: RequestHeader, msg: String) = Future.successful(Forbidden(msg)) } class JavaCSRFErrorHandlerAdapter @Inject() (underlying: CSRFErrorHandler) extends ErrorHandler { def handle(request: RequestHeader, msg: String) = JavaHelpers.invokeWithContext(request, req => underlying.handle(req, msg)) } class JavaCSRFErrorHandlerDelegate @Inject() (delegate: ErrorHandler) extends CSRFErrorHandler { import play.api.libs.iteratee.Execution.Implicits.trampoline def handle(req: Http.RequestHeader, msg: String) = FutureConverters.toJava(delegate.handle(req._underlyingHeader(), msg).map(_.asJava)) } object ErrorHandler { def bindingsFromConfiguration(environment: Environment, configuration: Configuration): Seq[Binding[_]] = { Reflect.bindingsFromConfiguration[ErrorHandler, CSRFErrorHandler, JavaCSRFErrorHandlerAdapter, JavaCSRFErrorHandlerDelegate, CSRFHttpErrorHandler](environment, PlayConfig(configuration), "play.filters.csrf.errorHandler", "CSRFErrorHandler") } } } /** * The CSRF module. */ class CSRFModule extends Module { def bindings(environment: Environment, configuration: Configuration) = { Seq( bind[CSRFConfig].toProvider[CSRFConfigProvider], bind[CSRF.TokenProvider].toProvider[CSRF.TokenProviderProvider], bind[CSRFFilter].toSelf ) ++ ErrorHandler.bindingsFromConfiguration(environment, configuration) } } /** * The CSRF components. */ trait CSRFComponents { def configuration: Configuration def httpErrorHandler: HttpErrorHandler implicit def flowMaterializer: Materializer lazy val csrfConfig: CSRFConfig = CSRFConfig.fromConfiguration(configuration) lazy val csrfTokenProvider: CSRF.TokenProvider = new CSRF.TokenProviderProvider(csrfConfig).get lazy val csrfErrorHandler: CSRF.ErrorHandler = new CSRFHttpErrorHandler(httpErrorHandler) lazy val csrfFilter: CSRFFilter = new CSRFFilter(csrfConfig, csrfTokenProvider, csrfErrorHandler) }
nelsonblaha/playframework
framework/src/play-integration-test/src/test/scala/play/it/http/parsing/XmlBodyParserSpec.scala
<reponame>nelsonblaha/playframework /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.it.http.parsing import akka.stream.Materializer import akka.stream.scaladsl.Source import akka.util.ByteString import play.api.test._ import play.api.mvc.{ BodyParser, BodyParsers } import scala.xml.NodeSeq import java.io.File import org.apache.commons.io.FileUtils object XmlBodyParserSpec extends PlaySpecification { "The XML body parser" should { def parse(xml: String, contentType: Option[String], encoding: String, bodyParser: BodyParser[NodeSeq] = BodyParsers.parse.tolerantXml(1048576))(implicit mat: Materializer) = { await( bodyParser(FakeRequest().withHeaders(contentType.map(CONTENT_TYPE -> _).toSeq: _*)) .run(Source.single(ByteString(xml, encoding))) ) } "parse XML bodies" in new WithApplication() { parse("<foo>bar</foo>", Some("application/xml; charset=utf-8"), "utf-8") must beRight.like { case xml => xml.text must_== "bar" } } "honour the external charset for application sub types" in new WithApplication() { parse("<foo>bär</foo>", Some("application/xml; charset=iso-8859-1"), "iso-8859-1") must beRight.like { case xml => xml.text must_== "bär" } parse("<foo>bär</foo>", Some("application/xml; charset=utf-16"), "utf-16") must beRight.like { case xml => xml.text must_== "bär" } } "honour the external charset for text sub types" in new WithApplication() { parse("<foo>bär</foo>", Some("text/xml; charset=iso-8859-1"), "iso-8859-1") must beRight.like { case xml => xml.text must_== "bär" } parse("<foo>bär</foo>", Some("text/xml; charset=utf-16"), "utf-16") must beRight.like { case xml => xml.text must_== "bär" } } "default to iso-8859-1 for text sub types" in new WithApplication() { parse("<foo>bär</foo>", Some("text/xml"), "iso-8859-1") must beRight.like { case xml => xml.text must_== "bär" } } "default to reading the encoding from the prolog for application sub types" in new WithApplication() { parse("""<?xml version="1.0" encoding="utf-16"?><foo>bär</foo>""", Some("application/xml"), "utf-16") must beRight.like { case xml => xml.text must_== "bär" } parse("""<?xml version="1.0" encoding="iso-8859-1"?><foo>bär</foo>""", Some("application/xml"), "iso-8859-1") must beRight.like { case xml => xml.text must_== "bär" } } "default to reading the encoding from the prolog for no content type" in new WithApplication() { parse("""<?xml version="1.0" encoding="utf-16"?><foo>bär</foo>""", None, "utf-16") must beRight.like { case xml => xml.text must_== "bär" } parse("""<?xml version="1.0" encoding="iso-8859-1"?><foo>bär</foo>""", None, "iso-8859-1") must beRight.like { case xml => xml.text must_== "bär" } } "accept all common xml content types" in new WithApplication() { parse("<foo>bar</foo>", Some("application/xml; charset=utf-8"), "utf-8", BodyParsers.parse.xml) must beRight.like { case xml => xml.text must_== "bar" } parse("<foo>bar</foo>", Some("text/xml; charset=utf-8"), "utf-8", BodyParsers.parse.xml) must beRight.like { case xml => xml.text must_== "bar" } parse("<foo>bar</foo>", Some("application/xml+rdf; charset=utf-8"), "utf-8", BodyParsers.parse.xml) must beRight.like { case xml => xml.text must_== "bar" } } "reject non XML content types" in new WithApplication() { parse("<foo>bar</foo>", Some("text/plain; charset=utf-8"), "utf-8", BodyParsers.parse.xml) must beLeft parse("<foo>bar</foo>", Some("xml/xml; charset=utf-8"), "utf-8", BodyParsers.parse.xml) must beLeft parse("<foo>bar</foo>", None, "utf-8", BodyParsers.parse.xml) must beLeft } "gracefully handle invalid xml" in new WithApplication() { parse("<foo", Some("text/xml; charset=utf-8"), "utf-8", BodyParsers.parse.xml) must beLeft } "parse XML bodies without loading in a related schema" in new WithApplication() { val f = File.createTempFile("xxe", ".txt") FileUtils.writeStringToFile(f, "I shouldn't be there!") f.deleteOnExit() val xml = s"""<?xml version="1.0" encoding="ISO-8859-1"?> | <!DOCTYPE foo [ | <!ELEMENT foo ANY > | <!ENTITY xxe SYSTEM "${f.toURI}">]><foo>hello&xxe;</foo>""".stripMargin parse(xml, Some("text/xml; charset=iso-8859-1"), "iso-8859-1") must beLeft } "parse XML bodies without loading in a related schema from a parameter" in new WithApplication() { val externalParameterEntity = File.createTempFile("xep", ".dtd") val externalGeneralEntity = File.createTempFile("xxe", ".txt") FileUtils.writeStringToFile(externalParameterEntity, s""" |<!ENTITY % xge SYSTEM "${externalGeneralEntity.toURI}"> |<!ENTITY % pe "<!ENTITY xxe '%xge;'>"> """.stripMargin) FileUtils.writeStringToFile(externalGeneralEntity, "I shouldnt be there!") externalGeneralEntity.deleteOnExit() externalParameterEntity.deleteOnExit() val xml = s"""<?xml version="1.0" encoding="ISO-8859-1"?> | <!DOCTYPE foo [ | <!ENTITY % xpe SYSTEM "${externalParameterEntity.toURI}"> | %xpe; | %pe; | ]><foo>hello&xxe;</foo>""".stripMargin parse(xml, Some("text/xml; charset=iso-8859-1"), "iso-8859-1") must beLeft } "gracefully fail when there are too many nested entities" in new WithApplication() { val nested = for (x <- 1 to 30) yield "<!ENTITY laugh" + x + " \"&laugh" + (x - 1) + ";&laugh" + (x - 1) + ";\">" val xml = s"""<?xml version="1.0"?> | <!DOCTYPE billion [ | <!ELEMENT billion (#PCDATA)> | <!ENTITY laugh0 "ha"> | ${nested.mkString("\n")} | ]> | <billion>&laugh30;</billion>""".stripMargin parse(xml, Some("text/xml; charset=utf-8"), "utf-8") must beLeft success } "gracefully fail when an entity expands to be very large" in new WithApplication() { val as = "a" * 50000 val entities = "&a;" * 50000 val xml = s"""<?xml version="1.0"?> | <!DOCTYPE kaboom [ | <!ENTITY a "$as"> | ]> | <kaboom>$entities</kaboom>""".stripMargin parse(xml, Some("text/xml; charset=utf-8"), "utf-8") must beLeft } } }
nelsonblaha/playframework
framework/src/run-support/src/test/scala/play/runsupport/GlobalStaticVarSpec.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.runsupport import org.specs2.mutable.Specification class GlobalStaticVarSpec extends Specification { "global static var" should { "support setting and getting" in { try { GlobalStaticVar.set("message", "hello world") GlobalStaticVar.get[String]("message") must beSome("hello world") } finally { GlobalStaticVar.remove("message") } } "return none when not set" in { GlobalStaticVar.get[String]("notset") must beNone } "support removing" in { try { GlobalStaticVar.set("msg", "hello world") GlobalStaticVar.get[String]("msg") must beSome("hello world") GlobalStaticVar.remove("msg") GlobalStaticVar.get[String]("msg") must beNone } finally { GlobalStaticVar.remove("msg") } } "support complex types like classloaders" in { try { val classLoader = this.getClass.getClassLoader GlobalStaticVar.set("classLoader", classLoader) GlobalStaticVar.get[ClassLoader]("classLoader") must beSome(classLoader) } finally { GlobalStaticVar.remove("classLoader") } } } }
nelsonblaha/playframework
framework/src/play/src/main/scala/play/api/inject/guice/GuiceApplicationBuilder.scala
<gh_stars>0 /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api.inject.guice import javax.inject.{ Provider, Inject } import com.google.inject.{ Module => GuiceModule } import play.api.routing.Router import play.api._ import play.api.inject.{ Injector => PlayInjector, RoutesProvider, bind } import play.core.{ DefaultWebCommands, WebCommands } /** * A builder for creating Applications using Guice. */ final class GuiceApplicationBuilder( environment: Environment = Environment.simple(), configuration: Configuration = Configuration.empty, modules: Seq[GuiceableModule] = Seq.empty, overrides: Seq[GuiceableModule] = Seq.empty, disabled: Seq[Class[_]] = Seq.empty, eagerly: Boolean = false, loadConfiguration: Environment => Configuration = Configuration.load, global: Option[GlobalSettings] = None, loadModules: (Environment, Configuration) => Seq[GuiceableModule] = GuiceableModule.loadModules) extends GuiceBuilder[GuiceApplicationBuilder]( environment, configuration, modules, overrides, disabled, eagerly ) { // extra constructor for creating from Java def this() = this(environment = Environment.simple()) /** * Set the initial configuration loader. * Overrides the default or any previously configured values. */ def loadConfig(loader: Environment => Configuration): GuiceApplicationBuilder = copy(loadConfiguration = loader) /** * Set the initial configuration. * Overrides the default or any previously configured values. */ def loadConfig(conf: Configuration): GuiceApplicationBuilder = loadConfig(env => conf) /** * Set the global settings object. * Overrides the default or any previously configured values. */ def global(globalSettings: GlobalSettings): GuiceApplicationBuilder = copy(global = Option(globalSettings)) /** * Set the module loader. * Overrides the default or any previously configured values. */ def load(loader: (Environment, Configuration) => Seq[GuiceableModule]): GuiceApplicationBuilder = copy(loadModules = loader) /** * Override the module loader with the given modules. */ def load(modules: GuiceableModule*): GuiceApplicationBuilder = load((env, conf) => modules) /** * Override the router with the given router. */ def router(router: Router): GuiceApplicationBuilder = overrides(bind[Router].toInstance(router)) /** * Override the router with a router that first tries to route to the passed in additional router, before falling * back to the default router. */ def additionalRouter(router: Router): GuiceApplicationBuilder = overrides(bind[Router].to(new AdditionalRouterProvider(router))) /** * Create a new Play application Module for an Application using this configured builder. */ override def applicationModule(): GuiceModule = { val initialConfiguration = loadConfiguration(environment) val appConfiguration = initialConfiguration ++ configuration val globalSettings = global.getOrElse(GlobalSettings(appConfiguration, environment)) LoggerConfigurator(environment.classLoader).foreach { _.configure(environment) } if (appConfiguration.underlying.hasPath("logger")) { Logger.warn("Logger configuration in conf files is deprecated and has no effect. Use a logback configuration file instead.") } val loadedModules = loadModules(environment, appConfiguration) copy(configuration = appConfiguration) .bindings(loadedModules: _*) .bindings( bind[GlobalSettings] to globalSettings, bind[OptionalSourceMapper] to new OptionalSourceMapper(None), bind[WebCommands] to new DefaultWebCommands ).createModule } /** * Create a new Play Application using this configured builder. */ def build(): Application = injector.instanceOf[Application] /** * Internal copy method with defaults. */ private def copy( environment: Environment = environment, configuration: Configuration = configuration, modules: Seq[GuiceableModule] = modules, overrides: Seq[GuiceableModule] = overrides, disabled: Seq[Class[_]] = disabled, eagerly: Boolean = eagerly, loadConfiguration: Environment => Configuration = loadConfiguration, global: Option[GlobalSettings] = global, loadModules: (Environment, Configuration) => Seq[GuiceableModule] = loadModules): GuiceApplicationBuilder = new GuiceApplicationBuilder(environment, configuration, modules, overrides, disabled, eagerly, loadConfiguration, global, loadModules) /** * Implementation of Self creation for GuiceBuilder. */ protected def newBuilder( environment: Environment, configuration: Configuration, modules: Seq[GuiceableModule], overrides: Seq[GuiceableModule], disabled: Seq[Class[_]], eagerly: Boolean): GuiceApplicationBuilder = copy(environment, configuration, modules, overrides, disabled, eagerly) } private class AdditionalRouterProvider(additional: Router) extends Provider[Router] { @Inject private var fallback: RoutesProvider = _ lazy val get = Router.from(additional.routes.orElse(fallback.get.routes)) }
nelsonblaha/playframework
framework/src/play-filters-helpers/src/test/scala/play/filters/csrf/JavaCSRFActionSpec.scala
<gh_stars>0 /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.filters.csrf import java.util.concurrent.CompletableFuture import play.api.libs.Crypto import play.api.mvc.Session import play.core.routing.HandlerInvokerFactory import play.mvc.Http.{ RequestHeader, Context } import scala.concurrent.Future import play.api.libs.ws._ import play.mvc.{ Results, Result, Controller } import play.core.j.{ JavaHandlerComponents, JavaActionAnnotations, JavaAction } import scala.reflect.ClassTag /** * Specs for the Java per action CSRF actions */ object JavaCSRFActionSpec extends CSRFCommonSpecs { def javaHandlerComponents = play.api.Play.current.injector.instanceOf[JavaHandlerComponents] def javaAction[T: ClassTag](method: String, inv: => Result) = new JavaAction(javaHandlerComponents) { val clazz = implicitly[ClassTag[T]].runtimeClass def parser = HandlerInvokerFactory.javaBodyParserToScala( javaHandlerComponents.injector.instanceOf(annotations.parser) ) def invocation = CompletableFuture.completedFuture(inv) val annotations = new JavaActionAnnotations(clazz, clazz.getMethod(method)) } def buildCsrfCheckRequest(sendUnauthorizedResult: Boolean, configuration: (String, String)*) = new CsrfTester { def apply[T](makeRequest: (WSRequest) => Future[WSResponse])(handleResponse: (WSResponse) => T) = withServer(configuration) { case _ if sendUnauthorizedResult => javaAction[MyUnauthorizedAction]("check", new MyUnauthorizedAction().check()) case _ => javaAction[MyAction]("check", new MyAction().check()) } { import play.api.Play.current handleResponse(await(makeRequest(WS.url("http://localhost:" + testServerPort)))) } } def buildCsrfAddToken(configuration: (String, String)*) = new CsrfTester { def apply[T](makeRequest: (WSRequest) => Future[WSResponse])(handleResponse: (WSResponse) => T) = withServer(configuration) { case _ => javaAction[MyAction]("add", new MyAction().add()) } { import play.api.Play.current handleResponse(await(makeRequest(WS.url("http://localhost:" + testServerPort)))) } } def buildCsrfWithSession(configuration: (String, String)*) = new CsrfTester { def apply[T](makeRequest: (WSRequest) => Future[WSResponse])(handleResponse: (WSResponse) => T) = withServer(configuration) { case _ => javaAction[MyAction]("withSession", new MyAction().withSession()) } { import play.api.Play.current handleResponse(await(makeRequest(WS.url("http://localhost:" + testServerPort)))) } } "The Java CSRF filter support" should { "allow adding things to the session when a token is also added to the session" in { buildCsrfWithSession()(_.get()) { response => val session = response.cookies.find(_.name.exists(_ == Session.COOKIE_NAME)).flatMap(_.value).map(Session.decode) session must beSome.which { s => s.get(TokenName) must beSome[String] s.get("hello") must beSome("world") } } } "allow accessing the token from the http context" in withServer(Nil) { case _ => javaAction[MyAction]("getToken", new MyAction().getToken()) } { lazy val token = Crypto.generateSignedToken import play.api.Play.current val returned = await(WS.url("http://localhost:" + testServerPort).withSession(TokenName -> token).get()).body Crypto.compareSignedTokens(token, returned) must beTrue } } class MyAction extends Controller { @AddCSRFToken def add(): Result = { // Simulate a template that adds a CSRF token import play.core.j.PlayMagicForJava.requestHeader import CSRF.Token.getToken Results.ok(implicitly[CSRF.Token].value) } def getToken(): Result = { Results.ok(Option(CSRF.getToken(Controller.request()).orElse(null)) match { case Some(CSRF.Token(value)) => value case None => "" }) } @RequireCSRFCheck def check(): Result = { Results.ok() } @AddCSRFToken def withSession(): Result = { Context.current().session().put("hello", "world") Results.ok() } } class MyUnauthorizedAction extends Controller { @AddCSRFToken def add(): Result = { // Simulate a template that adds a CSRF token import play.core.j.PlayMagicForJava.requestHeader import CSRF.Token.getToken Results.ok(implicitly[CSRF.Token].value) } @RequireCSRFCheck(error = classOf[CustomErrorHandler]) def check(): Result = { Results.ok() } } class CustomErrorHandler extends CSRFErrorHandler { def handle(req: RequestHeader, msg: String) = { CompletableFuture.completedFuture(Results.unauthorized(msg)) } } }
nelsonblaha/playframework
framework/src/play-streams/src/main/scala/play/api/libs/streams/AkkaStreams.scala
package play.api.libs.streams import akka.stream.scaladsl.FlexiMerge.{ MergeLogic, ReadAny } import akka.stream.scaladsl._ import akka.stream.{ Attributes, UniformFanInShape } import play.api.libs.iteratee._ import scala.util.{ Failure, Success } /** * Utilities for */ object AkkaStreams { /** * Bypass the given flow using the given splitter function. * * If the splitter function returns Left, they will go through the flow. If it returns Right, they will bypass the * flow. */ def bypassWith[In, FlowIn, Out](splitter: In => Either[FlowIn, Out]): Flow[FlowIn, Out, _] => Flow[In, Out, _] = { bypassWith(Flow[In].map(splitter)) } /** * Using the given splitter flow, allow messages to bypass a flow. * * If the splitter flow produces Left, they will be fed into the flow. If it produces Right, they will bypass the * flow. */ def bypassWith[In, FlowIn, Out](splitter: Flow[In, Either[FlowIn, Out], _], mergeStrategy: FlexiMerge[Out, UniformFanInShape[Out, Out]] = OnlyFirstCanFinishMerge[Out](2)): Flow[FlowIn, Out, _] => Flow[In, Out, _] = { flow => splitter via Flow[Either[FlowIn, Out], Out]() { implicit builder => import FlowGraph.Implicits._ // Eager cancel must be true so that if the flow cancels, that will be propagated upstream. // However, that means the bypasser must block cancel, since when this flow finishes, the merge // will result in a cancel flowing up through the bypasser, which could lead to dropped messages. val broadcast = builder.add(Broadcast[Either[FlowIn, Out]](2, eagerCancel = true)) val merge = builder.add(mergeStrategy) // Normal flow broadcast.out(0) ~> Flow[Either[FlowIn, Out]].collect { case Left(in) => in } ~> flow ~> merge.in(0) // Bypass flow, need to ignore downstream finish broadcast.out(1) ~> blockCancel[Either[FlowIn, Out]](() => ()) ~> Flow[Either[FlowIn, Out]].collect { case Right(out) => out } ~> merge.in(1) broadcast.in -> merge.out } } /** * Can be replaced if https://github.com/akka/akka/issues/18175 ever gets implemented. */ case class EagerFinishMerge[T](inputPorts: Int) extends FlexiMerge[T, UniformFanInShape[T, T]](new UniformFanInShape[T, T](inputPorts), Attributes.name("EagerFinishMerge")) { def createMergeLogic(s: UniformFanInShape[T, T]): MergeLogic[T] = new MergeLogic[T] { def initialState: State[T] = State[T](ReadAny(s.inSeq)) { case (ctx, port, in) => ctx.emit(in) SameState } override def initialCompletionHandling: CompletionHandling = eagerClose } } /** * A merge that only allows the first inlet to finish downstream. */ case class OnlyFirstCanFinishMerge[T](inputPorts: Int) extends FlexiMerge[T, UniformFanInShape[T, T]](new UniformFanInShape[T, T](inputPorts), Attributes.name("EagerFinishMerge")) { def createMergeLogic(s: UniformFanInShape[T, T]): MergeLogic[T] = new MergeLogic[T] { def initialState: State[T] = State[T](ReadAny(s.inSeq)) { case (ctx, port, in) => ctx.emit(in) SameState } override def initialCompletionHandling: CompletionHandling = CompletionHandling( onUpstreamFinish = { (ctx, port) => if (port == s.in(0)) { ctx.finish() } SameState }, onUpstreamFailure = { (ctx, port, error) => if (port == s.in(0)) { ctx.fail(error) } SameState } ) } } /** * Because https://github.com/akka/akka/issues/18189 */ private[play] def blockCancel[T](onCancel: () => Unit): Flow[T, T, Unit] = { import play.api.libs.iteratee.Execution.Implicits.trampoline val (enum, channel) = Concurrent.broadcast[T] val sink = Sink.foreach[T](channel.push).mapMaterializedValue(_.onComplete { case Success(_) => channel.end() case Failure(t) => channel.end(t) }) // This enumerator ignores cancel by flatmapping the iteratee to an Iteratee.ignore val cancelIgnoring = new Enumerator[T] { def apply[A](i: Iteratee[T, A]) = enum(i.flatMap { a => onCancel() Iteratee.ignore[T].map(_ => a) }) } Flow.wrap(sink, Source(Streams.enumeratorToPublisher(cancelIgnoring)))(Keep.none) } }
nelsonblaha/playframework
framework/src/play-json/src/main/scala/play/api/libs/json/package.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api.libs /** * Json API * For example: * {{{ * import play.api.libs.json._ * import play.api.libs.functional.syntax._ * * case class User(id: Long, name: String, friends: Seq[User] = Seq.empty) * object User { * * // In this format, an undefined friends property is mapped to an empty list * implicit val format: Format[User] = ( * (__ \ "id").format[Long] and * (__ \ "name").format[String] and * (__ \ "friends").lazyFormatNullable(implicitly[Format[Seq[User]]]) * .inmap[Seq[User]](_ getOrElse Seq.empty, Some(_)) * )(User.apply, unlift(User.unapply)) * } * * //then in a controller: * * object MyController extends Controller { * def displayUserAsJson(id: String) = Action { * Ok(Json.toJson(User(id.toLong, "myName"))) * } * def saveUser(jsonString: String)= Action { * val user = Json.parse(jsonString).as[User] * myDataStore.save(user) * Ok * } * } * }}} */ package object json { /** * Alias for `JsPath` companion object */ val __ = JsPath }
nelsonblaha/playframework
framework/src/play-json/src/main/scala/play/api/libs/json/Json.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api.libs.json import java.io.InputStream import play.api.libs.iteratee.Execution.Implicits.defaultExecutionContext import play.api.libs.json.jackson.JacksonJson /** * Helper functions to handle JsValues. */ object Json { /** * Parse a String representing a json, and return it as a JsValue. * * @param input a String to parse * @return the JsValue representing the string */ def parse(input: String): JsValue = JacksonJson.parseJsValue(input) /** * Parse an InputStream representing a json, and return it as a JsValue. * * @param input as InputStream to parse * @return the JsValue representing the InputStream */ def parse(input: InputStream): JsValue = JacksonJson.parseJsValue(input) /** * Parse a byte array representing a json, and return it as a JsValue. * * The character encoding used will be automatically detected as UTF-8, UTF-16 or UTF-32, as per the heuristics in * RFC-4627. * * @param input a byte array to parse * @return the JsValue representing the byte array */ def parse(input: Array[Byte]): JsValue = JacksonJson.parseJsValue(input) /** * Convert a JsValue to its string representation. * * {{{ * scala> Json.stringify(Json.obj( * "field1" -> Json.obj( * "field11" -> "value11", * "field12" -> Json.arr("alpha", 123L) * ) * )) * res0: String = {"field1":{"field11":"value11","field12":["alpha",123]}} * * scala> Json.stringify(res0) * res1: String = {"field1":{"field11":"value11","field12":["alpha",123]}} * }}} * * @param json the JsValue to convert * @return a String with the json representation */ def stringify(json: JsValue): String = JacksonJson.generateFromJsValue(json) //We use unicode \u005C for a backlash in comments, because Scala will replace unicode escapes during lexing //anywhere in the program. /** * Convert a JsValue to its string representation, escaping all non-ascii characters using \u005CuXXXX syntax. * * This is particularly useful when the output JSON will be executed as javascript, since JSON is not a strict * subset of javascript * (see <a href="http://timelessrepo.com/json-isnt-a-javascript-subset">JSON: The JavaScript subset that isn't</a>). * * {{{ * scala> Json.asciiStringify(JsString("some\u005Cu2028text\u005Cu2029")) * res0: String = "some\u005Cu2028text\u005Cu2029" * * scala> Json.stringify(JsString("some\u005Cu2028text\u005Cu2029")) * res1: String = "sometext" * }}} * * @param json the JsValue to convert * @return a String with the json representation with all non-ascii characters escaped. */ def asciiStringify(json: JsValue): String = JacksonJson.generateFromJsValue(json, true) /** * Convert a JsValue to its pretty string representation using default Jackson * pretty printer (line feeds after each fields and 2-spaces indentation). * * {{{ * scala> Json.stringify(Json.obj( * "field1" -> Json.obj( * "field11" -> "value11", * "field12" -> Json.arr("alpha", 123L) * ) * )) * res0: String = {"field1":{"field11":"value11","field12":["alpha",123]}} * * scala> Json.prettyPrint(res0) * res1: String = * { * "field1" : { * "field11" : "value11", * "field12" : [ "alpha", 123 ] * } * } * }}} * * @param json the JsValue to convert * @return a String with the json representation */ def prettyPrint(json: JsValue): String = JacksonJson.prettyPrint(json) /** * Provided a Writes implicit for its type is available, convert any object into a JsValue. * * @param o Value to convert in Json. */ def toJson[T](o: T)(implicit tjs: Writes[T]): JsValue = tjs.writes(o) /** * Provided a Reads implicit for that type is available, convert a JsValue to any type. * * @param json Json value to transform as an instance of T. */ def fromJson[T](json: JsValue)(implicit fjs: Reads[T]): JsResult[T] = fjs.reads(json) /** * Next is the trait that allows Simplified Json syntax : * * Example : * {{{ * JsObject(Seq( * "key1", JsString("value"), * "key2" -> JsNumber(123), * "key3" -> JsObject(Seq("key31" -> JsString("value31"))) * )) == Json.obj( "key1" -> "value", "key2" -> 123, "key3" -> obj("key31" -> "value31")) * * JsArray(JsString("value"), JsNumber(123), JsBoolean(true)) == Json.arr( "value", 123, true ) * }}} * * There is an implicit conversion from any Type with a Json Writes to JsValueWrapper * which is an empty trait that shouldn't end into unexpected implicit conversions. * * Something to note due to `JsValueWrapper` extending `NotNull` : * `null` or `None` will end into compiling error : use JsNull instead. */ sealed trait JsValueWrapper extends NotNull private case class JsValueWrapperImpl(field: JsValue) extends JsValueWrapper import scala.language.implicitConversions implicit def toJsFieldJsValueWrapper[T](field: T)(implicit w: Writes[T]): JsValueWrapper = JsValueWrapperImpl(w.writes(field)) def obj(fields: (String, JsValueWrapper)*): JsObject = JsObject(fields.map(f => (f._1, f._2.asInstanceOf[JsValueWrapperImpl].field))) def arr(fields: JsValueWrapper*): JsArray = JsArray(fields.map(_.asInstanceOf[JsValueWrapperImpl].field)) import play.api.libs.iteratee.Enumeratee /** * Transform a stream of A to a stream of JsValue * {{{ * val fooStream: Enumerator[Foo] = ??? * val jsonStream: Enumerator[JsValue] = fooStream &> Json.toJson * }}} */ def toJson[A: Writes]: Enumeratee[A, JsValue] = Enumeratee.map[A](Json.toJson(_)) /** * Transform a stream of JsValue to a stream of A, keeping only successful results * {{{ * val jsonStream: Enumerator[JsValue] = ??? * val fooStream: Enumerator[Foo] = jsonStream &> Json.fromJson * }}} */ def fromJson[A: Reads]: Enumeratee[JsValue, A] = Enumeratee.map[JsValue]((json: JsValue) => Json.fromJson(json)) ><> Enumeratee.collect[JsResult[A]] { case JsSuccess(value, _) => value } /** * Experimental JSON extensions to replace asProductXXX by generating * Reads[T]/Writes[T]/Format[T] from case class at COMPILE time using * new Scala 2.10 macro & reflection features. */ import scala.reflect.macros.Context import language.experimental.macros /** * Creates a Reads[T] by resolving case class fields & required implcits at COMPILE-time. * * If any missing implicit is discovered, compiler will break with corresponding error. * {{{ * import play.api.libs.json.Json * * case class User(name: String, age: Int) * * implicit val userReads = Json.reads[User] * // macro-compiler replaces Json.reads[User] by injecting into compile chain * // the exact code you would write yourself. This is strictly equivalent to: * implicit val userReads = ( * (__ \ 'name).read[String] and * (__ \ 'age).read[Int] * )(User) * }}} */ def reads[A]: Reads[A] = macro JsMacroImpl.readsImpl[A] /** * Creates a Writes[T] by resolving case class fields & required implcits at COMPILE-time * * If any missing implicit is discovered, compiler will break with corresponding error. * {{{ * import play.api.libs.json.Json * * case class User(name: String, age: Int) * * implicit val userWrites = Json.writes[User] * // macro-compiler replaces Json.writes[User] by injecting into compile chain * // the exact code you would write yourself. This is strictly equivalent to: * implicit val userWrites = ( * (__ \ 'name).write[String] and * (__ \ 'age).write[Int] * )(unlift(User.unapply)) * }}} */ def writes[A]: OWrites[A] = macro JsMacroImpl.writesImpl[A] /** * Creates a Format[T] by resolving case class fields & required implicits at COMPILE-time * * If any missing implicit is discovered, compiler will break with corresponding error. * {{{ * import play.api.libs.json.Json * * case class User(name: String, age: Int) * * implicit val userWrites = Json.format[User] * // macro-compiler replaces Json.format[User] by injecting into compile chain * // the exact code you would write yourself. This is strictly equivalent to: * implicit val userWrites = ( * (__ \ 'name).format[String] and * (__ \ 'age).format[Int] * )(User.apply, unlift(User.unapply)) * }}} */ def format[A]: OFormat[A] = macro JsMacroImpl.formatImpl[A] }
nelsonblaha/playframework
documentation/manual/working/scalaGuide/main/sql/code/ScalaInjectNamed.scala
<reponame>nelsonblaha/playframework package scalaguide.sql import javax.inject.Inject import play.api.db.{ Database, NamedDatabase } import play.api.mvc.Controller // inject "orders" database instead of "default" class ScalaInjectNamed @Inject()( @NamedDatabase("orders") db: Database) extends Controller { // do whatever you need with the db }
nelsonblaha/playframework
framework/src/play-akka-http-server/src/main/scala/play/core/server/akkahttp/AkkaHttpServer.scala
<filename>framework/src/play-akka-http-server/src/main/scala/play/core/server/akkahttp/AkkaHttpServer.scala package play.core.server.akkahttp import akka.actor.ActorSystem import akka.http.play.WebSocketHandler import akka.http.scaladsl.Http import akka.http.scaladsl.model._ import akka.http.scaladsl.model.headers.Expect import akka.http.scaladsl.model.ws.UpgradeToWebsocket import akka.stream.Materializer import akka.stream.scaladsl._ import java.net.InetSocketAddress import akka.util.ByteString import play.api._ import play.api.http.DefaultHttpErrorHandler import play.api.libs.streams.{ MaterializeOnDemandPublisher, Accumulator } import play.api.mvc._ import play.core.ApplicationProvider import play.core.server._ import play.core.server.common.{ ForwardedHeaderHandler, ServerResultUtils } import scala.concurrent.duration._ import scala.concurrent.{ Await, Future } import scala.util.control.NonFatal import scala.util.{ Failure, Success, Try } /** * Starts a Play server using Akka HTTP. */ class AkkaHttpServer( config: ServerConfig, val applicationProvider: ApplicationProvider, actorSystem: ActorSystem, materializer: Materializer, stopHook: () => Future[Unit]) extends Server { import AkkaHttpServer._ assert(config.port.isDefined, "AkkaHttpServer must be given an HTTP port") assert(!config.sslPort.isDefined, "AkkaHttpServer cannot handle HTTPS") def mode = config.mode // Remember that some user config may not be available in development mode due to // its unusual ClassLoader. implicit val system = actorSystem implicit val mat = materializer private val serverBinding: Http.ServerBinding = { // Listen for incoming connections and handle them with the `handleRequest` method. // TODO: pass in Inet.SocketOption, ServerSettings and LoggerAdapter params? val serverSource: Source[Http.IncomingConnection, Future[Http.ServerBinding]] = Http().bind(interface = config.address, port = config.port.get) val connectionSink: Sink[Http.IncomingConnection, _] = Sink.foreach { connection: Http.IncomingConnection => connection.handleWithAsyncHandler(handleRequest(connection.remoteAddress, _)) } val bindingFuture: Future[Http.ServerBinding] = serverSource.to(connectionSink).run() val bindTimeout = PlayConfig(config.configuration).get[Duration]("play.akka.http-bind-timeout") Await.result(bindingFuture, bindTimeout) } // Each request needs an id private val requestIDs = new java.util.concurrent.atomic.AtomicLong(0) // TODO: We can change this to an eager val when we fully support server configuration // instead of reading from the application configuration. At the moment we need to wait // until we have an Application available before we can read any configuration. :( private lazy val modelConversion: ModelConversion = { val forwardedHeaderHandler = new ForwardedHeaderHandler( ForwardedHeaderHandler.ForwardedHeaderHandlerConfig(applicationProvider.get.toOption.map(_.configuration))) new ModelConversion(forwardedHeaderHandler) } private def handleRequest(remoteAddress: InetSocketAddress, request: HttpRequest): Future[HttpResponse] = { val requestId = requestIDs.incrementAndGet() val (convertedRequestHeader, requestBodySource) = modelConversion.convertRequest( requestId = requestId, remoteAddress = remoteAddress, secureProtocol = false, // TODO: Change value once HTTPS connections are supported request = request) val (taggedRequestHeader, handler, newTryApp) = getHandler(convertedRequestHeader) val responseFuture = executeHandler( newTryApp, request, taggedRequestHeader, requestBodySource, handler ) responseFuture } private def getHandler(requestHeader: RequestHeader): (RequestHeader, Handler, Try[Application]) = { getHandlerFor(requestHeader) match { case Left(futureResult) => ( requestHeader, EssentialAction(_ => Accumulator.done(futureResult)), Failure(new Exception("getHandler returned Result, but not Application")) ) case Right((newRequestHeader, handler, newApp)) => ( newRequestHeader, handler, Success(newApp) // TODO: Change getHandlerFor to use the app that we already had ) } } private def executeHandler( tryApp: Try[Application], request: HttpRequest, taggedRequestHeader: RequestHeader, requestBodySource: Source[ByteString, _], handler: Handler): Future[HttpResponse] = { val upgradeToWebSocket = request.header[UpgradeToWebsocket] (handler, upgradeToWebSocket) match { //execute normal action case (action: EssentialAction, _) => val actionWithErrorHandling = EssentialAction { rh => import play.api.libs.iteratee.Execution.Implicits.trampoline action(rh).recoverWith { case error => handleHandlerError(tryApp, taggedRequestHeader, error) } } executeAction(tryApp, request, taggedRequestHeader, requestBodySource, actionWithErrorHandling) case (websocket: WebSocket, Some(upgrade)) => import play.api.libs.iteratee.Execution.Implicits.trampoline websocket(taggedRequestHeader).map { case Left(result) => modelConversion.convertResult(taggedRequestHeader, result, request.protocol) case Right(flow) => WebSocketHandler.handleWebSocket(upgrade, flow, 16384) } case (websocket: WebSocket, None) => // WebSocket handler for non WebSocket request sys.error(s"WebSocket returned for non WebSocket request") case (unhandled, _) => sys.error(s"AkkaHttpServer doesn't handle Handlers of this type: $unhandled") } } /** Error handling to use during execution of a handler (e.g. an action) */ private def handleHandlerError(tryApp: Try[Application], rh: RequestHeader, t: Throwable): Future[Result] = { tryApp match { case Success(app) => app.errorHandler.onServerError(rh, t) case Failure(_) => DefaultHttpErrorHandler.onServerError(rh, t) } } def executeAction( tryApp: Try[Application], request: HttpRequest, taggedRequestHeader: RequestHeader, requestBodySource: Source[ByteString, _], action: EssentialAction): Future[HttpResponse] = { import play.api.libs.iteratee.Execution.Implicits.trampoline val actionAccumulator: Accumulator[ByteString, Result] = action(taggedRequestHeader) val source = if (request.header[Expect].exists(_ == Expect.`100-continue`)) { // If we expect 100 continue, then we must not feed the source into the accumulator until the accumulator // requests demand. This is due to a semantic mismatch between Play and Akka-HTTP, Play signals to continue // by requesting demand, Akka-HTTP signals to continue by attaching a sink to the source. See // https://github.com/akka/akka/issues/17782 for more details. Source(new MaterializeOnDemandPublisher(requestBodySource)) } else { requestBodySource } val resultFuture: Future[Result] = actionAccumulator.run(source) val responseFuture: Future[HttpResponse] = resultFuture.map { result => val cleanedResult: Result = ServerResultUtils.cleanFlashCookie(taggedRequestHeader, result) modelConversion.convertResult(taggedRequestHeader, cleanedResult, request.protocol) } responseFuture } // TODO: Log information about the address we're listening on, like in NettyServer mode match { case Mode.Test => case _ => } override def stop() { // First, stop listening Await.result(serverBinding.unbind(), Duration.Inf) applicationProvider.current.foreach(Play.stop) try { super.stop() } catch { case NonFatal(e) => logger.error("Error while stopping logger", e) } mode match { case Mode.Test => case _ => logger.info("Stopping server...") } // TODO: Orderly shutdown system.shutdown() // Call provided hook // Do this last because the hooks were created before the server, // so the server might need them to run until the last moment. Await.result(stopHook(), Duration.Inf) } override lazy val mainAddress = { // TODO: Handle HTTPS here, like in NettyServer serverBinding.localAddress } def httpPort = Some(serverBinding.localAddress.getPort) def httpsPort = None } object AkkaHttpServer { private val logger = Logger(classOf[AkkaHttpServer]) /** * A ServerProvider for creating an AkkaHttpServer. */ implicit val provider = new AkkaHttpServerProvider } /** * Knows how to create an AkkaHttpServer. */ class AkkaHttpServerProvider extends ServerProvider { def createServer(context: ServerProvider.Context) = new AkkaHttpServer(context.config, context.appProvider, context.actorSystem, context.materializer, context.stopHook) }
nelsonblaha/playframework
framework/src/play-integration-test/src/test/scala/play/it/http/websocket/WebSocketClient.scala
<filename>framework/src/play-integration-test/src/test/scala/play/it/http/websocket/WebSocketClient.scala /** * Some elements of this were copied from: * * https://gist.github.com/casualjim/1819496 */ package play.it.http.websocket import java.io.IOException import org.jboss.netty.bootstrap.ClientBootstrap import org.jboss.netty.channel._ import socket.nio.NioClientSocketChannelFactory import java.util.concurrent.Executors import org.jboss.netty.handler.codec.http._ import collection.JavaConversions._ import websocketx._ import java.net.{ InetSocketAddress, URI } import org.jboss.netty.util.CharsetUtil import scala.concurrent.{ Promise, Future } import play.api.libs.iteratee.Execution.Implicits.trampoline import play.api.libs.iteratee._ /** * A basic WebSocketClient. Basically wraps Netty's WebSocket support into something that's much easier to use and much * more Scala friendly. */ trait WebSocketClient { import WebSocketClient._ /** * Connect to the given URI. * * @return A future that will be redeemed when the connection is closed. */ def connect(url: URI, version: WebSocketVersion = WebSocketVersion.V13)(onConnect: Handler): Future[Unit] /** * Shutdown the client and release all associated resources. */ def shutdown() } object WebSocketClient { type Handler = (Enumerator[WebSocketFrame], Iteratee[WebSocketFrame, _]) => Unit def create(): WebSocketClient = new DefaultWebSocketClient def apply[T](block: WebSocketClient => T) = { val client = WebSocketClient.create() try { block(client) } finally { client.shutdown() } } private implicit class ToFuture(chf: ChannelFuture) { def toScala: Future[Channel] = { val promise = Promise[Channel]() chf.addListener(new ChannelFutureListener { def operationComplete(future: ChannelFuture) = { if (future.isSuccess) { promise.success(future.getChannel) } else if (future.isCancelled) { promise.failure(new RuntimeException("Future cancelled")) } else { promise.failure(future.getCause) } } }) promise.future } } private class DefaultWebSocketClient extends WebSocketClient { val bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newSingleThreadExecutor(), Executors.newSingleThreadExecutor(), 1, 1)) bootstrap.setPipelineFactory(new ChannelPipelineFactory { def getPipeline = { val pipeline = Channels.pipeline() pipeline.addLast("decoder", new HttpResponseDecoder) pipeline.addLast("encoder", new HttpRequestEncoder) pipeline } }) /** * Connect to the given URI */ def connect(url: URI, version: WebSocketVersion)(onConnected: (Enumerator[WebSocketFrame], Iteratee[WebSocketFrame, _]) => Unit) = { val normalized = url.normalize() val tgt = if (normalized.getPath == null || normalized.getPath.trim().isEmpty) { new URI(normalized.getScheme, normalized.getAuthority, "/", normalized.getQuery, normalized.getFragment) } else normalized val disconnected = Promise[Unit]() bootstrap.connect(new InetSocketAddress(tgt.getHost, tgt.getPort)).toScala.map { channel => val handshaker = new WebSocketClientHandshakerFactory().newHandshaker(tgt, version, null, false, Map.empty[String, String]) channel.getPipeline.addLast("supervisor", new WebSocketSupervisor(disconnected, handshaker, onConnected)) handshaker.handshake(channel) }.onFailure { case t => disconnected.tryFailure(t) } disconnected.future } def shutdown() = bootstrap.releaseExternalResources() } private class WebSocketSupervisor(disconnected: Promise[Unit], handshaker: WebSocketClientHandshaker, onConnected: Handler) extends SimpleChannelUpstreamHandler { override def messageReceived(ctx: ChannelHandlerContext, e: MessageEvent) { e.getMessage match { case resp: HttpResponse if handshaker.isHandshakeComplete => throw new WebSocketException("Unexpected HttpResponse (status=" + resp.getStatus + ", content=" + resp.getContent.toString(CharsetUtil.UTF_8) + ")") case resp: HttpResponse => handshaker.finishHandshake(ctx.getChannel, e.getMessage.asInstanceOf[HttpResponse]) val handler = new WebSocketClientHandler(ctx.getChannel, disconnected) ctx.getPipeline.addLast("websocket", handler) onConnected(handler.enumerator, handler.iteratee) case _: WebSocketFrame => ctx.sendUpstream(e) case _ => throw new WebSocketException("Unexpected event: " + e) } } override def exceptionCaught(ctx: ChannelHandlerContext, e: ExceptionEvent) { disconnected.tryFailure(e.getCause) ctx.getChannel.close() ctx.sendDownstream(e) } } private class WebSocketClientHandler(out: Channel, disconnected: Promise[Unit]) extends SimpleChannelUpstreamHandler { @volatile var clientInitiatedClose = false val (enumerator, in) = Concurrent.broadcast[WebSocketFrame] val iteratee: Iteratee[WebSocketFrame, _] = Cont { case Input.El(wsf) => if (wsf.isInstanceOf[CloseWebSocketFrame]) { clientInitiatedClose = true } Iteratee.flatten(out.write(wsf).toScala.map(_ => iteratee)) case Input.EOF => disconnected.trySuccess(()) Iteratee.flatten(out.close().toScala.map(_ => Done((), Input.EOF))) case Input.Empty => iteratee } override def messageReceived(ctx: ChannelHandlerContext, e: MessageEvent) { e.getMessage match { case close: CloseWebSocketFrame => in.push(close) if (!clientInitiatedClose) { out.write(close) } case wsf: WebSocketFrame => in.push(wsf) case _ => throw new WebSocketException("Unexpected event: " + e) } } override def exceptionCaught(ctx: ChannelHandlerContext, e: ExceptionEvent) { e.getCause match { case io: IOException => // We're talking to loopback, an IO exception is probably fine to ignore, if there's a problem, the tests // should catch it. println("IO exception caught in WebSocket client: " + io) disconnected.success(()) in.end() out.close() case other => val exception = new RuntimeException("Exception caught in web socket handler", other) disconnected.tryFailure(exception) in.end(exception) out.close() } } override def channelClosed(ctx: ChannelHandlerContext, e: ChannelStateEvent) = { disconnected.trySuccess(()) in.end() } } class WebSocketException(s: String, th: Throwable) extends java.io.IOException(s, th) { def this(s: String) = this(s, null) } }
nelsonblaha/playframework
framework/src/sbt-fork-run-plugin/src/sbt-test/fork-run/dev-mode/build.sbt
<filename>framework/src/sbt-fork-run-plugin/src/sbt-test/fork-run/dev-mode/build.sbt lazy val root = (project in file(".")).enablePlugins(PlayScala) DevModeBuild.settings fork in run := true // This actually doesn't do anything, since the build runs in a forked sbt server which doesn't have the same // system properties as the sbt client that forked it. scalaVersion := Option(System.getProperty("scala.version")).getOrElse("2.11.7")
nelsonblaha/playframework
framework/src/play/src/main/scala/play/api/libs/EventSource.scala
<filename>framework/src/play/src/main/scala/play/api/libs/EventSource.scala /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api.libs import play.api.http.{ ContentTypeOf, ContentTypes, Writeable } import play.api.mvc._ import play.api.libs.iteratee._ import play.core.Execution.Implicits.internalContext import play.api.libs.json.{ Json, JsValue } /** * Helps you format Server-Sent Events * @see [[http://www.w3.org/TR/eventsource/]] */ object EventSource { case class EventDataExtractor[A](eventData: A => String) trait LowPriorityEventEncoder { implicit val stringEvents: EventDataExtractor[String] = EventDataExtractor(identity) implicit val jsonEvents: EventDataExtractor[JsValue] = EventDataExtractor(Json.stringify) } object EventDataExtractor extends LowPriorityEventEncoder case class EventNameExtractor[E](eventName: E => Option[String]) case class EventIdExtractor[E](eventId: E => Option[String]) trait LowPriorityEventNameExtractor { implicit def non[E]: EventNameExtractor[E] = EventNameExtractor[E](_ => None) } trait LowPriorityEventIdExtractor { implicit def non[E]: EventIdExtractor[E] = EventIdExtractor[E](_ => None) } object EventNameExtractor extends LowPriorityEventNameExtractor { implicit def pair[E]: EventNameExtractor[(String, E)] = EventNameExtractor[(String, E)](p => Some(p._1)) } object EventIdExtractor extends LowPriorityEventIdExtractor /** * Makes an `Enumeratee[E, Event]`, that is an [[iteratee.Enumeratee]] transforming `E` values * into [[Event]] values. * * Usage example: * * {{{ * val someDataStream: Enumerator[SomeData] = ??? * Ok.chunked(someDataStream &> EventSource()) * }}} * * @tparam E from type of the Enumeratee */ def apply[E: EventDataExtractor: EventNameExtractor: EventIdExtractor](): Enumeratee[E, Event] = Enumeratee.map[E] { e => Event(e) } case class Event(data: String, id: Option[String], name: Option[String]) { /** * This event, formatted according to the EventSource protocol. */ lazy val formatted = { val sb = new StringBuilder name.foreach(sb.append("event: ").append(_).append('\n')) id.foreach(sb.append("id: ").append(_).append('\n')) for (line <- data.split("(\r?\n)|\r")) { sb.append("data: ").append(line).append('\n') } sb.append('\n') sb.toString() } } object Event { def apply[A](a: A)(implicit dataExtractor: EventDataExtractor[A], nameExtractor: EventNameExtractor[A], idExtractor: EventIdExtractor[A]): Event = Event(dataExtractor.eventData(a), idExtractor.eventId(a), nameExtractor.eventName(a)) implicit def writeable(implicit codec: Codec): Writeable[Event] = Writeable(event => codec.encode(event.formatted)) implicit def contentType(implicit codec: Codec): ContentTypeOf[Event] = ContentTypeOf(Some(ContentTypes.EVENT_STREAM)) } }
nelsonblaha/playframework
documentation/manual/working/scalaGuide/advanced/routing/code/scalaguide/binder/controllers/BinderApplication.scala
package scalaguide.binder.controllers import play.api._ import play.api.mvc._ import scalaguide.binder.models._ class BinderApplication extends Controller{ //#path def user(user: User) = Action { Ok(user.name) } //#path //#query def age(age: AgeRange) = Action { Ok(age.from.toString) } //#query }
nelsonblaha/playframework
framework/src/play/src/main/scala/play/core/system/RequestIdProvider.scala
<gh_stars>1-10 /* * Copyright (C) 2015 Typesafe Inc. <http://www.typesafe.com> */ package play.core.system import java.util.concurrent.atomic.AtomicLong; private[play] object RequestIdProvider { val requestIDs: AtomicLong = new AtomicLong(0) }
nelsonblaha/playframework
framework/src/run-support/src/main/scala/play/runsupport/NamedURLClassLoader.scala
<reponame>nelsonblaha/playframework package play.runsupport import java.net.{ URL, URLClassLoader } /** * A ClassLoader with a toString() that prints name/urls. */ class NamedURLClassLoader(name: String, urls: Array[URL], parent: ClassLoader) extends URLClassLoader(urls, parent) { override def toString = name + "{" + getURLs.map(_.toString).mkString(", ") + "}" }
nelsonblaha/playframework
framework/src/play-server/src/test/scala/play/core/server/common/ForwardedHeaderHandlerSpec.scala
<reponame>nelsonblaha/playframework<filename>framework/src/play-server/src/test/scala/play/core/server/common/ForwardedHeaderHandlerSpec.scala /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.core.server.common import java.net.InetAddress import org.specs2.mutable.Specification import org.specs2.specification.Scope import play.api.mvc.Headers import play.api.{ PlayException, Configuration } import play.core.server.common.ForwardedHeaderHandler.ForwardedHeaderHandlerConfig class ForwardedHeaderHandlerSpec extends Specification { "ForwardedHeaderHandler" should { """not accept a wrong setting as "play.http.forwarded.version" in config""" in { handler(version("rfc7240")) must throwA[PlayException] } "ignore proxy hosts with rfc7239 when no proxies are trusted" in { handler(version("rfc7239") ++ trustedProxies(Nil)).remoteConnection(localhost, false, headers( """ |Forwarded: for="_gazonk" |Forwarded: For="[2001:db8:cafe::17]:4711" |Forwarded: for=192.0.2.60;proto=http;by=203.0.113.43 |Forwarded: for=192.0.2.43, for=198.51.100.17, for=127.0.0.1 """.stripMargin)) mustEqual ConnectionInfo(localhost, false) } "get first untrusted proxy host with rfc7239 with ipv4 localhost" in { handler(version("rfc7239")).remoteConnection(localhost, false, headers( """ |Forwarded: for="_gazonk" |Forwarded: For="[2fc00:e968:6179::de52:7100]:4711" |Forwarded: for=192.0.2.60;proto=http;by=203.0.113.43 |Forwarded: for=192.0.2.43, for=198.51.100.17, for=127.0.0.1 """.stripMargin)) mustEqual ConnectionInfo(addr("198.51.100.17"), false) } "get first untrusted proxy host with rfc7239 with ipv6 localhost" in { handler(version("rfc7239")).remoteConnection(localhost, false, headers( """ |Forwarded: for="_gazonk" |Forwarded: For="[200fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b]:4711" |Forwarded: for=192.0.2.60;proto=http;by=203.0.113.43 |Forwarded: for=192.0.2.43, for=[::1] """.stripMargin)) mustEqual ConnectionInfo(addr("192.0.2.43"), false) } "get first untrusted proxy with rfc7239 with trusted proxy subnet" in { handler(version("rfc7239") ++ trustedProxies("192.168.1.1/24" :: "127.0.0.1" :: Nil)).remoteConnection(localhost, false, headers( """ |Forwarded: for="_gazonk" |Forwarded: For="[2001:db8:cafe::17]:4711" |Forwarded: for=192.0.2.60;proto=http;by=203.0.113.43 |Forwarded: for=192.168.1.10, for=127.0.0.1 """.stripMargin)) mustEqual ConnectionInfo(addr("192.0.2.60"), false) } "get first untrusted proxy protocol with rfc7239 with trusted localhost proxy" in { handler(version("rfc7239") ++ trustedProxies("127.0.0.1" :: Nil)).remoteConnection(localhost, false, headers( """ |Forwarded: for="_gazonk" |Forwarded: For="[2001:db8:cafe::17]:4711" |Forwarded: for=192.0.2.60;proto=http;by=203.0.113.43 |Forwarded: for=192.168.1.10, for=127.0.0.1 """.stripMargin)) mustEqual ConnectionInfo(addr("192.168.1.10"), false) } "get first untrusted proxy protocol with rfc7239 with subnet mask" in { handler(version("rfc7239") ++ trustedProxies("192.168.1.1/24" :: "127.0.0.1" :: Nil)).remoteConnection(localhost, false, headers( """ |Forwarded: for="_gazonk" |Forwarded: For="[2001:db8:cafe::17]:4711" |Forwarded: for=192.0.2.60;proto=https;by=203.0.113.43 |Forwarded: for=192.168.1.10, for=127.0.0.1 """.stripMargin)) mustEqual ConnectionInfo(addr("192.0.2.60"), true) } "get first untrusted proxy with x-forwarded with subnet mask" in { handler(version("x-forwarded") ++ trustedProxies("192.168.1.1/24" :: "127.0.0.1" :: Nil)).remoteConnection(localhost, false, headers( """ |X-Forwarded-For: 203.0.113.43, 192.168.1.43 |X-Forwarded-Proto: https, http """.stripMargin)) mustEqual ConnectionInfo(addr("203.0.113.43"), true) } "not treat the first x-forwarded entry as a proxy even if it is in trustedProxies range" in { handler(version("x-forwarded") ++ trustedProxies("192.168.1.1/24" :: "127.0.0.1" :: Nil)).remoteConnection(localhost, true, headers( """ |X-Forwarded-For: 192.168.1.2, 192.168.1.3 |X-Forwarded-Proto: http, http """.stripMargin)) mustEqual ConnectionInfo(addr("192.168.1.2"), false) } "assume http protocol with x-forwarded when proto list is missing" in { handler(version("x-forwarded") ++ trustedProxies("192.168.1.1/24" :: "127.0.0.1" :: Nil)).remoteConnection(localhost, false, headers( """ |X-Forwarded-For: 203.0.113.43 """.stripMargin)) mustEqual ConnectionInfo(addr("203.0.113.43"), false) } "assume http protocol with x-forwarded when proto list is shorter than for list" in { handler(version("x-forwarded") ++ trustedProxies("192.168.1.1/24" :: "127.0.0.1" :: Nil)).remoteConnection(localhost, false, headers( """ |X-Forwarded-For: 203.0.113.43, 192.168.1.43 |X-Forwarded-Proto: https """.stripMargin)) mustEqual ConnectionInfo(addr("203.0.113.43"), false) } "assume http protocol with x-forwarded when proto list is shorter than for list and all addresses are trusted" in { handler(version("x-forwarded") ++ trustedProxies("0.0.0.0/0" :: Nil)).remoteConnection(localhost, false, headers( """ |X-Forwarded-For: 203.0.113.43, 192.168.1.43 |X-Forwarded-Proto: https """.stripMargin)) mustEqual ConnectionInfo(addr("203.0.113.43"), false) } "assume http protocol with x-forwarded when proto list is longer than for list" in { handler(version("x-forwarded") ++ trustedProxies("192.168.1.1/24" :: "127.0.0.1" :: Nil)).remoteConnection(localhost, false, headers( """ |X-Forwarded-For: 203.0.113.43, 192.168.1.43 |X-Forwarded-Proto: https, https, https """.stripMargin)) mustEqual ConnectionInfo(addr("203.0.113.43"), false) } } def handler(config: Map[String, Any]) = new ForwardedHeaderHandler(ForwardedHeaderHandlerConfig(Some(Configuration.from(config)))) def version(s: String) = { Map("play.http.forwarded.version" -> s) } def trustedProxies(s: List[String]) = { Map("play.http.forwarded.trustedProxies" -> s) } def headers(s: String): Headers = { def split(s: String, regex: String): Option[(String, String)] = s.split(regex, 2).toList match { case k :: v :: Nil => Some(k -> v) case _ => None } new Headers(s.split("\n").flatMap(split(_, ":\\s*"))) } def addr(ip: String): InetAddress = InetAddress.getByName(ip) val localhost: InetAddress = addr("127.0.0.1") }
nelsonblaha/playframework
framework/src/play-java-ws/src/test/scala/play/libs/ws/WSSpec.scala
<filename>framework/src/play-java-ws/src/test/scala/play/libs/ws/WSSpec.scala package play.libs.ws import play.api.mvc.{ Result, Action } import play.api.mvc.Results._ import play.api.test._ object WSSpec extends PlaySpecification { sequential val uploadApp = FakeApplication(withRoutes = { case ("POST", "/") => Action { request => request.body.asRaw.fold[Result](BadRequest) { raw => val size = raw.size Ok(s"size=$size") } } }) "WS.url().post(InputStream)" should { "uploads the stream" in new WithServer(app = uploadApp, port = 3333) { val input = this.getClass.getClassLoader.getResourceAsStream("play/libs/ws/play_full_color.png") val req = WS.url("http://localhost:3333").post(input).wrapped() val rep = await(req) rep.getStatus must ===(200) rep.getBody must ===("size=20039") } } }
nelsonblaha/playframework
framework/src/play/src/main/scala/views/defaultpages/package.scala
<filename>framework/src/play/src/main/scala/views/defaultpages/package.scala /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package views.html /** * Contains default error, 404, forbidden, etc. pages. */ package object defaultpages
nelsonblaha/playframework
framework/src/play-streams/src/test/scala/play/api/libs/streams/impl/PublisherEvents.scala
/* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api.libs.streams.impl import org.reactivestreams._ import scala.concurrent._ object PublisherEvents { case class RequestMore(elementCount: Long) case object Cancel } trait PublisherEvents[T] { self: EventRecorder => import PublisherEvents._ case class BoundedSubscription[T, U >: T](pr: Publisher[T], sr: Subscriber[U]) extends Subscription { def cancel(): Unit = { record(Cancel) } def request(elements: Long): Unit = { record(RequestMore(elements)) } def onNext(element: T): Unit = sr.onNext(element) } object publisher extends Publisher[T] { val subscription = Promise[BoundedSubscription[T, _]]() override def subscribe(sr: Subscriber[_ >: T]) = { subscription.success(BoundedSubscription(this, sr)) } } private def forSubscription(f: BoundedSubscription[T, _] => Any)(implicit ec: ExecutionContext): Future[Unit] = { publisher.subscription.future.map { sn => f(sn) () } } def onSubscribe()(implicit ec: ExecutionContext): Unit = { forSubscription { sn => sn.sr.onSubscribe(sn) } } def onNext(element: T)(implicit ec: ExecutionContext): Unit = { forSubscription { sn => sn.onNext(element) } } def onError(t: Throwable)(implicit ec: ExecutionContext): Unit = { forSubscription { sn => sn.sr.onError(t) } } def onComplete()(implicit ec: ExecutionContext): Unit = { forSubscription { sn => sn.sr.onComplete() } } }
nelsonblaha/playframework
framework/src/play-ws/src/main/scala/play/api/libs/oauth/package.scala
<reponame>nelsonblaha/playframework /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api.libs /** * OAuth integration helpers. */ package object oauth
nelsonblaha/playframework
framework/src/iteratees/src/main/scala/play/api/libs/iteratee/package.scala
<filename>framework/src/iteratees/src/main/scala/play/api/libs/iteratee/package.scala /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api.libs { /** * The Iteratee monad provides strict, safe, and functional I/O. */ package object iteratee { type K[E, A] = Input[E] => Iteratee[E, A] } } package play.api.libs.iteratee { private[iteratee] object internal { import play.api.libs.iteratee.Iteratee import scala.concurrent.{ ExecutionContext, Future } import scala.util.control.NonFatal /** * Executes code immediately on the current thread, returning a successful or failed Future depending on * the result. * * TODO: Rename to `tryFuture`. */ def eagerFuture[A](body: => A): Future[A] = try Future.successful(body) catch { case NonFatal(e) => Future.failed(e) } /** * Executes code in the given ExecutionContext, flattening the resulting Future. */ def executeFuture[A](body: => Future[A])(implicit ec: ExecutionContext): Future[A] = { Future { body }(ec /* Future.apply will prepare */ ).flatMap(identityFunc.asInstanceOf[Future[A] => Future[A]])(Execution.trampoline) } /** * Executes code in the given ExecutionContext, flattening the resulting Iteratee. */ def executeIteratee[A, E](body: => Iteratee[A, E])(implicit ec: ExecutionContext): Iteratee[A, E] = Iteratee.flatten(Future(body)(ec)) /** * Prepare an ExecutionContext and pass it to the given function, returning the result of * the function. * * Makes it easy to write single line functions with a prepared ExecutionContext, eg: * {{{ * def myFunc(implicit ec: ExecutionContext) = prepared(ec)(pec => ...) * }}} */ def prepared[A](ec: ExecutionContext)(f: ExecutionContext => A): A = { val pec = ec.prepare() f(pec) } val identityFunc: (Any => Any) = (x: Any) => x } }
nelsonblaha/playframework
framework/src/play-functional/src/main/scala/play/api/libs/functional/syntax/package.scala
<reponame>nelsonblaha/playframework /* * Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> */ package play.api.libs.functional.syntax import scala.language.higherKinds import scala.language.implicitConversions import play.api.libs.functional._ /** * Don't forget to {{{import play.api.libs.functional.syntax._}}} to enable functional combinators * when using Json API. */ object `package` { implicit def toAlternativeOps[M[_], A](a: M[A])(implicit app: Alternative[M]): AlternativeOps[M, A] = new AlternativeOps(a) implicit def toApplicativeOps[M[_], A](a: M[A])(implicit app: Applicative[M]): ApplicativeOps[M, A] = new ApplicativeOps(a) implicit def toFunctionalBuilderOps[M[_], A](a: M[A])(implicit fcb: FunctionalCanBuild[M]) = new FunctionalBuilderOps[M, A](a)(fcb) implicit def functionalCanBuildApplicative[M[_]](implicit app: Applicative[M]): FunctionalCanBuild[M] = new FunctionalCanBuild[M] { def apply[A, B](a: M[A], b: M[B]): M[A ~ B] = app.apply(app.map[A, B => A ~ B](a, a => ((b: B) => new ~(a, b))), b) } implicit def functorOption: Functor[Option] = new Functor[Option] { def fmap[A, B](a: Option[A], f: A => B): Option[B] = a.map(f) } implicit def applicativeOption: Applicative[Option] = new Applicative[Option] { def pure[A](a: A): Option[A] = Some(a) def map[A, B](m: Option[A], f: A => B): Option[B] = m.map(f) def apply[A, B](mf: Option[A => B], ma: Option[A]): Option[B] = mf.flatMap(f => ma.map(f)) } implicit def functionMonoid[A] = new Monoid[A => A] { override def append(f1: A => A, f2: A => A) = f2 compose f1 override def identity = Predef.identity } implicit def toMonoidOps[A](a: A)(implicit m: Monoid[A]): MonoidOps[A] = new MonoidOps(a) implicit def toFunctorOps[M[_], A](ma: M[A])(implicit fu: Functor[M]): FunctorOps[M, A] = new FunctorOps(ma) implicit def toContraFunctorOps[M[_], A](ma: M[A])(implicit fu: ContravariantFunctor[M]): ContravariantFunctorOps[M, A] = new ContravariantFunctorOps(ma) implicit def toInvariantFunctorOps[M[_], A](ma: M[A])(implicit fu: InvariantFunctor[M]): InvariantFunctorOps[M, A] = new InvariantFunctorOps(ma) def unapply[B, A](f: B => Option[A]) = { b: B => f(b).get } def unlift[A, B](f: A => Option[B]): A => B = Function.unlift(f) }