Skip to content

Commit

Permalink
#23 Update play to 2.6.3 and scala to 2.12.3
Browse files Browse the repository at this point in the history
  • Loading branch information
To-om committed Aug 14, 2017
1 parent 7cae8d4 commit e9e4d71
Show file tree
Hide file tree
Showing 71 changed files with 505 additions and 464 deletions.
12 changes: 3 additions & 9 deletions app/org/elastic4play/ErrorHandler.scala
Original file line number Diff line number Diff line change
@@ -1,23 +1,17 @@
package org.elastic4play

import scala.annotation.implicitNotFound
import scala.concurrent.Future

import play.api.Logger
import play.api.http.HttpErrorHandler
import play.api.libs.json.Json
import play.api.mvc.{ RequestHeader, Result, Results }
import play.api.http.{ HttpErrorHandler, Status, Writeable }
import play.api.libs.json.{ JsNull, JsValue, Json }
import play.api.mvc.{ RequestHeader, ResponseHeader, Result, Results }

import org.elasticsearch.client.transport.NoNodeAvailableException
import org.elasticsearch.index.IndexNotFoundException
import org.elasticsearch.transport.RemoteTransportException

import org.elastic4play.JsonFormat.attributeCheckingExceptionWrites
import play.api.libs.json.JsValue
import play.api.http.Status
import play.api.libs.json.JsNull
import play.api.mvc.ResponseHeader
import play.api.http.Writeable

/**
* This class handles errors. It traverses all causes of exception to find known error and shows the appropriate message
Expand Down
5 changes: 3 additions & 2 deletions app/org/elastic4play/JsonFormat.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ package org.elastic4play

import java.util.Date

import scala.util.{ Failure, Success, Try }

import play.api.libs.json._
import org.elastic4play.controllers.JsonFormat._

import scala.util.{ Failure, Success, Try }
import org.elastic4play.controllers.JsonFormat.inputValueFormat

object JsonFormat {
val datePattern = "yyyyMMdd'T'HHmmssZ"
Expand Down
24 changes: 15 additions & 9 deletions app/org/elastic4play/controllers/Authenticated.scala
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
package org.elastic4play.controllers

import java.util.Date

import javax.inject.{ Inject, Singleton }

import scala.language.reflectiveCalls
import scala.concurrent.{ ExecutionContext, Future }
import scala.concurrent.duration.{ DurationLong, FiniteDuration }
import scala.concurrent.{ ExecutionContext, Future }
import scala.util.Try

import play.api.Configuration
import play.api.http.HeaderNames
import play.api.mvc.{ ActionBuilder, Request, RequestHeader, Result, Security, WrappedRequest }
import play.api.mvc._

import org.elastic4play.AuthenticationError
import org.elastic4play.services.{ AuthContext, AuthSrv, Role, UserSrv }
Expand Down Expand Up @@ -39,20 +37,25 @@ case object ExpirationError extends ExpirationStatus
class Authenticated(
maxSessionInactivity: FiniteDuration,
sessionWarning: FiniteDuration,
sessionUsername: String,
userSrv: UserSrv,
authSrv: AuthSrv,
defaultParser: BodyParsers.Default,
implicit val ec: ExecutionContext) {

@Inject() def this(
configuration: Configuration,
userSrv: UserSrv,
authSrv: AuthSrv,
defaultParser: BodyParsers.Default,
ec: ExecutionContext) =
this(
configuration.getMilliseconds("session.inactivity").get.millis,
configuration.getMilliseconds("session.warning").get.millis,
configuration.getMillis("session.inactivity").millis,
configuration.getMillis("session.warning").millis,
configuration.get[String]("session.username"),
userSrv,
authSrv,
defaultParser,
ec)

private def now = (new Date).getTime
Expand All @@ -62,14 +65,14 @@ class Authenticated(
* Cookie is signed by Play framework (it cannot be modified by user)
*/
def setSessingUser(result: Result, authContext: AuthContext)(implicit request: RequestHeader): Result =
result.addingToSession(Security.username authContext.userId, "expire" (now + maxSessionInactivity.toMillis).toString)
result.addingToSession(sessionUsername authContext.userId, "expire" (now + maxSessionInactivity.toMillis).toString)

/**
* Retrieve authentication information form cookie
*/
def getFromSession(request: RequestHeader): Future[AuthContext] = {
val userId = for {
userId request.session.get(Security.username)
userId request.session.get(sessionUsername)
if expirationStatus(request) != ExpirationError
} yield userId
userId.fold(Future.failed[AuthContext](AuthenticationError("Not authenticated")))(id userSrv.getFromId(request, id))
Expand Down Expand Up @@ -121,7 +124,10 @@ class Authenticated(
* If user has sufficient right (have required role) action is executed
* otherwise, action returns a not authorized error
*/
def apply(requiredRole: Role.Type) = new ActionBuilder[({ type R[A] = AuthenticatedRequest[A] })#R] {
def apply(requiredRole: Role.Type) = new ActionBuilder[AuthenticatedRequest, AnyContent] {
val executionContext: ExecutionContext = ec
def parser: BodyParser[AnyContent] = defaultParser

def invokeBlock[A](request: Request[A], block: (AuthenticatedRequest[A]) Future[Result]): Future[Result] = {
getContext(request).flatMap { authContext
if (authContext.roles.contains(requiredRole))
Expand Down
12 changes: 7 additions & 5 deletions app/org/elastic4play/controllers/DBListCtrl.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,22 @@ package org.elastic4play.controllers

import javax.inject.{ Inject, Singleton }

import org.elastic4play.services.{ DBLists, Role }
import org.elastic4play.{ MissingAttributeError, Timed }
import scala.concurrent.{ ExecutionContext, Future }

import play.api.libs.json.{ JsValue, Json }
import play.api.mvc.{ Action, AnyContent, Controller }
import play.api.mvc._

import scala.concurrent.{ ExecutionContext, Future }
import org.elastic4play.services.{ DBLists, Role }
import org.elastic4play.{ MissingAttributeError, Timed }

@Singleton
class DBListCtrl @Inject() (
dblists: DBLists,
authenticated: Authenticated,
renderer: Renderer,
components: ControllerComponents,
fieldsBodyParser: FieldsBodyParser,
implicit val ec: ExecutionContext) extends Controller {
implicit val ec: ExecutionContext) extends AbstractController(components) {

@Timed("controllers.DBListCtrl.list")
def list: Action[AnyContent] = authenticated(Role.read).async { implicit request
Expand Down
60 changes: 32 additions & 28 deletions app/org/elastic4play/controllers/Fields.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,22 @@ package org.elastic4play.controllers

import java.nio.file.Path
import java.util.Locale
import javax.inject.Inject

import scala.collection.{ GenTraversableOnce, immutable }
import scala.concurrent.ExecutionContext
import scala.util.Try

import akka.util.ByteString
import org.elastic4play.BadRequestError
import org.elastic4play.controllers.JsonFormat.{ fieldsReader, pathFormat }
import org.elastic4play.services.Attachment
import org.elastic4play.utils.Hash
import play.api.Logger
import play.api.libs.json.Json.toJsFieldJsValueWrapper
import play.api.libs.json._
import play.api.libs.streams.Accumulator
import play.api.mvc.{ BodyParser, MultipartFormData, RequestHeader, Result }
import play.api.mvc._

import scala.collection.{ GenTraversableOnce, immutable }
import scala.util.Try
import org.elastic4play.BadRequestError
import org.elastic4play.controllers.JsonFormat.{ fieldsReader, pathFormat }
import org.elastic4play.services.Attachment
import org.elastic4play.utils.Hash

/**
* Define a data value from HTTP request. It can be simple string, json, file or null (maybe xml in future)
Expand Down Expand Up @@ -214,36 +216,38 @@ object Fields {
}
}

class FieldsBodyParser extends BodyParser[Fields] {
import play.api.libs.iteratee.Execution.Implicits.trampoline
import play.api.mvc.BodyParsers.parse._
class FieldsBodyParser @Inject() (
playBodyParsers: PlayBodyParsers,
implicit val ec: ExecutionContext) extends BodyParser[Fields] {

def apply(request: RequestHeader): Accumulator[ByteString, Either[Result, Fields]] = {
def apply(request: RequestHeader) = {
def queryFields = request.queryString.mapValues(v StringInputValue(v))

request.contentType.map(_.toLowerCase(Locale.ENGLISH)) match {

case Some("text/json") | Some("application/json") json[Fields].map(f f ++ queryFields).apply(request)
case Some("text/json") | Some("application/json") playBodyParsers.json[Fields].map(f f ++ queryFields).apply(request)

case Some("application/x-www-form-urlencoded") tolerantFormUrlEncoded
case Some("application/x-www-form-urlencoded") playBodyParsers.tolerantFormUrlEncoded
.map { form Fields(form.mapValues(v StringInputValue(v))) }
.map(f f ++ queryFields)
.apply(request)

case Some("multipart/form-data") multipartFormData.map {
case MultipartFormData(dataParts, files, _)
val dataFields = dataParts
.getOrElse("_json", Nil)
.headOption
.map { s
Json.parse(s).as[JsObject]
.value.toMap
.mapValues(v JsonInputValue(v))
}
.getOrElse(Map.empty)
val fileFields = files.map { f f.key FileInputValue(f.filename.split("[/\\\\]").last, f.ref.file.toPath, f.contentType.getOrElse("application/octet-stream")) }
Fields(dataFields ++ fileFields ++ queryFields)
}.apply(request)
case Some("multipart/form-data") playBodyParsers.multipartFormData
.map {
case MultipartFormData(dataParts, files, _)
val dataFields = dataParts
.getOrElse("_json", Nil)
.headOption
.map { s
Json.parse(s).as[JsObject]
.value.toMap
.mapValues(v JsonInputValue(v))
}
.getOrElse(Map.empty)
val fileFields = files.map { f f.key FileInputValue(f.filename.split("[/\\\\]").last, f.ref.path, f.contentType.getOrElse("application/octet-stream")) }
Fields(dataFields ++ fileFields ++ queryFields)
}
.apply(request)

case contentType
val contentLength = request.headers.get("Content-Length").fold(0)(_.toInt)
Expand Down
4 changes: 1 addition & 3 deletions app/org/elastic4play/controllers/JsonFormat.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@ package org.elastic4play.controllers
import java.io.File
import java.nio.file.{ Path, Paths }

import play.api.libs.json.{ Format, JsError, JsObject, JsString, JsSuccess, JsValue }
import play.api.libs.json.{ Reads, Writes }
import play.api.libs.json.JsValue.jsValueToJsLookup
import play.api.libs.json.Json
import play.api.libs.json.Json.toJsFieldJsValueWrapper
import play.api.libs.json._

import org.elastic4play.utils.Hash

Expand Down
8 changes: 5 additions & 3 deletions app/org/elastic4play/controllers/MigrationCtrl.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ package org.elastic4play.controllers

import javax.inject.{ Inject, Singleton }

import scala.annotation.implicitNotFound
import scala.concurrent.ExecutionContext
import play.api.mvc.{ Action, AnyContent, Controller }

import play.api.mvc._

import org.elastic4play.Timed
import org.elastic4play.services.MigrationSrv

Expand All @@ -14,7 +15,8 @@ import org.elastic4play.services.MigrationSrv
@Singleton
class MigrationCtrl @Inject() (
migrationSrv: MigrationSrv,
implicit val ec: ExecutionContext) extends Controller {
components: ControllerComponents,
implicit val ec: ExecutionContext) extends AbstractController(components) {

@Timed("controllers.MigrationCtrl.migrate")
def migrate: Action[AnyContent] = Action.async {
Expand Down
19 changes: 9 additions & 10 deletions app/org/elastic4play/controllers/Renderer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,13 @@ import javax.inject.Inject
import scala.concurrent.{ ExecutionContext, Future }
import scala.util.{ Failure, Success, Try }

import akka.stream.Materializer
import akka.stream.scaladsl.Source

import play.api.http.Status
import play.api.libs.json.{ JsValue, Json }
import play.api.libs.json.Json.toJsFieldJsValueWrapper
import play.api.libs.json.Writes
import play.api.mvc.{ Request, Result, Results }
import play.api.libs.json.{ JsValue, Json, Writes }
import play.api.mvc.{ Result, Results }

import akka.stream.Materializer
import akka.stream.scaladsl.Source

import org.elastic4play.ErrorHandler

Expand All @@ -21,7 +20,7 @@ class Renderer @Inject() (
implicit val ec: ExecutionContext,
implicit val mat: Materializer) {

def toMultiOutput[A](status: Int, objects: Seq[Try[A]])(implicit writes: Writes[A], request: Request[_]): Result = {
def toMultiOutput[A](status: Int, objects: Seq[Try[A]])(implicit writes: Writes[A]): Result = {

val (success, failure) = objects.foldLeft((Seq.empty[JsValue], Seq.empty[JsValue])) {
case ((artifacts, errors), Success(a)) (Json.toJson(a) +: artifacts, errors)
Expand All @@ -41,14 +40,14 @@ class Renderer @Inject() (
toOutput(Status.MULTI_STATUS, Json.obj("success" success, "failure" failure))
}

def toOutput[C](status: Int, content: C)(implicit writes: Writes[C], request: Request[_]): Result = {
def toOutput[C](status: Int, content: C)(implicit writes: Writes[C]): Result = {
val json = Json.toJson(content)
val s = new Results.Status(status)
s(json)
}

def toOutput[C](status: Int, src: Source[C, _], total: Future[Long])(implicit writes: Writes[C], request: Request[_]): Future[Result] = {
val stringSource = src.map(_.toString).intersperse("[", ",", "]")
def toOutput[C](status: Int, src: Source[C, _], total: Future[Long])(implicit writes: Writes[C]): Future[Result] = {
val stringSource = src.map(s Json.toJson(s).toString).intersperse("[", ",", "]")
total.map { t
new Results.Status(status)
.chunked(stringSource)
Expand Down
26 changes: 11 additions & 15 deletions app/org/elastic4play/database/DBConfiguration.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,25 @@ package org.elastic4play.database

import javax.inject.{ Inject, Named, Singleton }

import scala.annotation.implicitNotFound
import scala.concurrent.{ ExecutionContext, Future, Promise }
import scala.concurrent.duration.DurationInt
import scala.concurrent.{ ExecutionContext, Future, Promise }

import play.api.inject.ApplicationLifecycle
import play.api.{ Configuration, Logger }

import akka.NotUsed
import akka.actor.ActorSystem
import akka.stream.scaladsl.{ Sink, Source }

import play.api.{ Configuration, Logger }
import play.api.inject.ApplicationLifecycle

import com.sksamuel.elastic4s.ElasticDsl.{ BulkDefinitionExecutable, ClearScrollDefinitionExecutable, CreateIndexDefinitionExecutable, DeleteByIdDefinitionExecutable, GetDefinitionExecutable, IndexDefinitionExecutable, IndexExistsDefinitionExecutable, ScrollExecutable, SearchDefinitionExecutable, UpdateDefinitionExecutable }
import com.sksamuel.elastic4s._
import com.sksamuel.elastic4s.streams.ReactiveElastic.ReactiveElastic
import com.sksamuel.elastic4s.streams.{ RequestBuilder, ResponseListener }
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse
import org.elasticsearch.action.delete.DeleteResponse
import org.elasticsearch.action.update.UpdateResponse
import org.elasticsearch.common.settings.Settings

import com.sksamuel.elastic4s.{ BulkDefinition, BulkItemResult, BulkResult, ClearScrollDefinition, ClearScrollResult, CreateIndexDefinition, DeleteByIdDefinition, ElasticClient }
import com.sksamuel.elastic4s.{ ElasticsearchClientUri, GetDefinition, IndexDefinition, IndexResult, RichGetResponse, RichSearchHit, RichSearchResponse, SearchDefinition, SearchScrollDefinition, UpdateDefinition, admin }
import com.sksamuel.elastic4s.ElasticDsl.{ BulkDefinitionExecutable, ClearScrollDefinitionExecutable, CreateIndexDefinitionExecutable, DeleteByIdDefinitionExecutable, GetDefinitionExecutable, IndexDefinitionExecutable, IndexExistsDefinitionExecutable, ScrollExecutable, SearchDefinitionExecutable, UpdateDefinitionExecutable }
import com.sksamuel.elastic4s.streams.{ RequestBuilder, ResponseListener }
import com.sksamuel.elastic4s.streams.ReactiveElastic.ReactiveElastic

import org.elastic4play.Timed

/**
Expand All @@ -49,9 +45,9 @@ class DBConfiguration(
ec: ExecutionContext,
actorSystem: ActorSystem) = {
this(
configuration.getStringSeq("search.host").get,
configuration.getString("search.cluster").get,
configuration.getString("search.index").get,
configuration.get[Seq[String]]("search.host"),
configuration.get[String]("search.cluster"),
configuration.get[String]("search.index"),
lifecycle,
version,
ec,
Expand Down
Loading

0 comments on commit e9e4d71

Please sign in to comment.