diff options
author | Jakob Odersky <jakob@odersky.com> | 2017-11-20 21:38:21 -0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2017-11-20 21:38:21 -0800 |
commit | f2a56045d0b29291a18054607701d5863722121e (patch) | |
tree | 34b5fc63cc425a27969c73354fd7a2071ea67ba3 /src/main/scala/xyz/driver/core | |
parent | 8d30baada3a9c25ef61ef80511f4b4f25799f0cb (diff) | |
parent | b872ee2649c7b56df413fbde746ee68312c17abd (diff) | |
download | driver-core-f2a56045d0b29291a18054607701d5863722121e.tar.gz driver-core-f2a56045d0b29291a18054607701d5863722121e.tar.bz2 driver-core-f2a56045d0b29291a18054607701d5863722121e.zip |
Merge pull request #91 from drivergroup/new-creds-and-format
New creds and format
Diffstat (limited to 'src/main/scala/xyz/driver/core')
26 files changed, 177 insertions, 153 deletions
diff --git a/src/main/scala/xyz/driver/core/app/DriverApp.scala b/src/main/scala/xyz/driver/core/app/DriverApp.scala index 5297c90..6ba9949 100644 --- a/src/main/scala/xyz/driver/core/app/DriverApp.scala +++ b/src/main/scala/xyz/driver/core/app/DriverApp.scala @@ -32,18 +32,19 @@ import scala.util.control.NonFatal import scalaz.Scalaz.stringInstance import scalaz.syntax.equal._ -class DriverApp(appName: String, - version: String, - gitHash: String, - modules: Seq[Module], - time: TimeProvider = new SystemTimeProvider(), - log: Logger = Logger(LoggerFactory.getLogger(classOf[DriverApp])), - config: Config = core.config.loadDefaultConfig, - interface: String = "::0", - baseUrl: String = "localhost:8080", - scheme: String = "http", - port: Int = 8080, - tracer: Tracer = NoTracer)(implicit actorSystem: ActorSystem, executionContext: ExecutionContext) { +class DriverApp( + appName: String, + version: String, + gitHash: String, + modules: Seq[Module], + time: TimeProvider = new SystemTimeProvider(), + log: Logger = Logger(LoggerFactory.getLogger(classOf[DriverApp])), + config: Config = core.config.loadDefaultConfig, + interface: String = "::0", + baseUrl: String = "localhost:8080", + scheme: String = "http", + port: Int = 8080, + tracer: Tracer = NoTracer)(implicit actorSystem: ActorSystem, executionContext: ExecutionContext) { self => import DriverApp._ @@ -115,10 +116,11 @@ class DriverApp(appName: String, MDC.put("ip", ip.toOption.map(_.getHostAddress).getOrElse("unknown")) MDC.put("remoteHost", ip.toOption.map(_.getHostName).getOrElse("unknown")) - MDC.put("xForwardedFor", - extractHeader(request)("x-forwarded-for") - .orElse(extractHeader(request)("x_forwarded_for")) - .getOrElse("unknown")) + MDC.put( + "xForwardedFor", + extractHeader(request)("x-forwarded-for") + .orElse(extractHeader(request)("x_forwarded_for")) + .getOrElse("unknown")) MDC.put("remoteAddress", extractHeader(request)("remote-address").getOrElse("unknown")) MDC.put("userAgent", extractHeader(request)("user-agent").getOrElse("unknown")) } @@ -204,10 +206,11 @@ class DriverApp(appName: String, "totalGarbageCollections" -> gcStats.totalGarbageCollections.toJson ).toJson, "fileSystemSpace" -> SystemStats.fileSystemSpace.map { f => - Map("path" -> f.path.toJson, - "freeSpace" -> f.freeSpace.toJson, - "totalSpace" -> f.totalSpace.toJson, - "usableSpace" -> f.usableSpace.toJson) + Map( + "path" -> f.path.toJson, + "freeSpace" -> f.freeSpace.toJson, + "totalSpace" -> f.totalSpace.toJson, + "usableSpace" -> f.usableSpace.toJson) }.toJson, "operatingSystem" -> SystemStats.operatingSystemStats.toJson )) diff --git a/src/main/scala/xyz/driver/core/app/init.scala b/src/main/scala/xyz/driver/core/app/init.scala index 36eaeda..6cdd46f 100644 --- a/src/main/scala/xyz/driver/core/app/init.scala +++ b/src/main/scala/xyz/driver/core/app/init.scala @@ -90,11 +90,12 @@ object init { ApplicationContext(config, time, log) } - def createDefaultApplication(modules: Seq[Module], - buildInfo: RequiredBuildInfo, - actorSystem: ActorSystem, - tracer: Tracer, - context: ApplicationContext) = { + def createDefaultApplication( + modules: Seq[Module], + buildInfo: RequiredBuildInfo, + actorSystem: ActorSystem, + tracer: Tracer, + context: ApplicationContext) = { val scheme = context.config.getString("application.scheme") val baseUrl = context.config.getString("application.baseUrl") val port = context.config.getInt("application.port") diff --git a/src/main/scala/xyz/driver/core/auth.scala b/src/main/scala/xyz/driver/core/auth.scala index 11c6c7f..ec58ad5 100644 --- a/src/main/scala/xyz/driver/core/auth.scala +++ b/src/main/scala/xyz/driver/core/auth.scala @@ -25,21 +25,23 @@ object auth { final case class AuthToken(value: String) - final case class AuthUser(id: Id[AuthUser], - userId: Id[User], - email: Email, - emailVerified: Boolean, - phoneNumber: Option[PhoneNumber], - phoneVerified: Boolean, - isBlocked: Boolean, - roles: Set[Role]) - - final case class AuthTokenUserInfo(id: Id[User], - authUserId: Id[AuthUser], - email: Email, - emailVerified: Boolean, - audience: String, - roles: Set[Role]) + final case class AuthUser( + id: Id[AuthUser], + userId: Id[User], + email: Email, + emailVerified: Boolean, + phoneNumber: Option[PhoneNumber], + phoneVerified: Boolean, + isBlocked: Boolean, + roles: Set[Role]) + + final case class AuthTokenUserInfo( + id: Id[User], + authUserId: Id[AuthUser], + email: Email, + emailVerified: Boolean, + audience: String, + roles: Set[Role]) extends User final case class RefreshToken(value: String) diff --git a/src/main/scala/xyz/driver/core/cache.scala b/src/main/scala/xyz/driver/core/cache.scala index a929171..3500a2a 100644 --- a/src/main/scala/xyz/driver/core/cache.scala +++ b/src/main/scala/xyz/driver/core/cache.scala @@ -92,11 +92,12 @@ object cache { val DEFAULT_READ_EXPIRATION: Duration = 10 minutes val DEFAULT_WRITE_EXPIRATION: Duration = 1 hour - def apply[K <: AnyRef, V <: AnyRef](name: String, - capacity: Long = DEFAULT_CAPACITY, - readExpiration: Duration = DEFAULT_READ_EXPIRATION, - writeExpiration: Duration = DEFAULT_WRITE_EXPIRATION)( - implicit executionContext: ExecutionContext): AsyncCache[K, V] = { + def apply[K <: AnyRef, V <: AnyRef]( + name: String, + capacity: Long = DEFAULT_CAPACITY, + readExpiration: Duration = DEFAULT_READ_EXPIRATION, + writeExpiration: Duration = DEFAULT_WRITE_EXPIRATION)( + implicit executionContext: ExecutionContext): AsyncCache[K, V] = { val guavaCache = CacheBuilder .newBuilder() .maximumSize(capacity) diff --git a/src/main/scala/xyz/driver/core/database/Dal.scala b/src/main/scala/xyz/driver/core/database/Dal.scala index 52f8477..581bd0f 100644 --- a/src/main/scala/xyz/driver/core/database/Dal.scala +++ b/src/main/scala/xyz/driver/core/database/Dal.scala @@ -61,7 +61,7 @@ class SlickDal(database: Database, executionContext: ExecutionContext) extends D } def insertReturning[AT <: AbstractTable[_], V](table: TableQuery[AT])( - row: AT#TableElementType): slick.dbio.DBIO[AT#TableElementType] = { + row: AT#TableElementType): slick.dbio.DBIO[AT#TableElementType] = { table.returning(table) += row } } diff --git a/src/main/scala/xyz/driver/core/database/database.scala b/src/main/scala/xyz/driver/core/database/database.scala index 26c1027..ae06517 100644 --- a/src/main/scala/xyz/driver/core/database/database.scala +++ b/src/main/scala/xyz/driver/core/database/database.scala @@ -69,16 +69,16 @@ package database { trait RefinedColumnTypes[T, Predicate] extends ColumnTypes { import profile.api._ implicit def `eu.timepit.refined.api.Refined`( - implicit columnType: BaseColumnType[T], - validate: Validate[T, Predicate]): BaseColumnType[T Refined Predicate] + implicit columnType: BaseColumnType[T], + validate: Validate[T, Predicate]): BaseColumnType[T Refined Predicate] } object RefinedColumnTypes { trait RefinedValue[T, Predicate] extends RefinedColumnTypes[T, Predicate] { import profile.api._ override implicit def `eu.timepit.refined.api.Refined`( - implicit columnType: BaseColumnType[T], - validate: Validate[T, Predicate]): BaseColumnType[T Refined Predicate] = + implicit columnType: BaseColumnType[T], + validate: Validate[T, Predicate]): BaseColumnType[T Refined Predicate] = MappedColumnType.base[T Refined Predicate, T]( _.value, { dbValue => refineV[Predicate](dbValue) match { @@ -130,8 +130,9 @@ package database { import profile.api._ override implicit def `xyz.driver.core.time.Time.columnType`: BaseColumnType[Time] = - MappedColumnType.base[Time, java.sql.Timestamp](time => new java.sql.Timestamp(time.millis), - timestamp => Time(timestamp.getTime)) + MappedColumnType.base[Time, java.sql.Timestamp]( + time => new java.sql.Timestamp(time.millis), + timestamp => Time(timestamp.getTime)) } trait PrimitiveTimestamp extends TimestampColumnTypes { diff --git a/src/main/scala/xyz/driver/core/file/FileSystemStorage.scala b/src/main/scala/xyz/driver/core/file/FileSystemStorage.scala index 0d49f2d..5a0df39 100644 --- a/src/main/scala/xyz/driver/core/file/FileSystemStorage.scala +++ b/src/main/scala/xyz/driver/core/file/FileSystemStorage.scala @@ -58,11 +58,12 @@ class FileSystemStorage(executionContext: ExecutionContext) extends FileStorage val file = new File(path.toString) if (file.isDirectory) { file.listFiles().toList.filter(_.isFile).map { file => - FileLink(Name[File](file.getName), - Paths.get(file.getPath), - Revision[File](file.hashCode.toString), - Time(file.lastModified()), - file.length()) + FileLink( + Name[File](file.getName), + Paths.get(file.getPath), + Revision[File](file.hashCode.toString), + Time(file.lastModified()), + file.length()) } } else List.empty[FileLink] }) diff --git a/src/main/scala/xyz/driver/core/file/GcsStorage.scala b/src/main/scala/xyz/driver/core/file/GcsStorage.scala index 629b1d8..0970092 100644 --- a/src/main/scala/xyz/driver/core/file/GcsStorage.scala +++ b/src/main/scala/xyz/driver/core/file/GcsStorage.scala @@ -20,10 +20,11 @@ import scala.concurrent.duration.Duration import scala.concurrent.{ExecutionContext, Future} import scalaz.{ListT, OptionT} -class GcsStorage(storageClient: Storage, - bucketName: Name[Bucket], - executionContext: ExecutionContext, - chunkSize: Int = 4096) +class GcsStorage( + storageClient: Storage, + bucketName: Name[Bucket], + executionContext: ExecutionContext, + chunkSize: Int = 4096) extends SignedFileStorage { implicit private val execution: ExecutionContext = executionContext diff --git a/src/main/scala/xyz/driver/core/file/package.scala b/src/main/scala/xyz/driver/core/file/package.scala index dd0998d..58955e5 100644 --- a/src/main/scala/xyz/driver/core/file/package.scala +++ b/src/main/scala/xyz/driver/core/file/package.scala @@ -18,11 +18,11 @@ package file { import scala.concurrent.duration.Duration final case class FileLink( - name: Name[File], - location: Path, - revision: Revision[File], - lastModificationDate: Time, - fileSize: Long + name: Name[File], + location: Path, + revision: Revision[File], + lastModificationDate: Time, + fileSize: Long ) trait FileService { diff --git a/src/main/scala/xyz/driver/core/generators.scala b/src/main/scala/xyz/driver/core/generators.scala index e6eb654..e2a4d5a 100644 --- a/src/main/scala/xyz/driver/core/generators.scala +++ b/src/main/scala/xyz/driver/core/generators.scala @@ -67,8 +67,9 @@ object generators { val oneTime = nextTime() val anotherTime = nextTime() - TimeRange(Time(scala.math.min(oneTime.millis, anotherTime.millis)), - Time(scala.math.max(oneTime.millis, anotherTime.millis))) + TimeRange( + Time(scala.math.min(oneTime.millis, anotherTime.millis)), + Time(scala.math.max(oneTime.millis, anotherTime.millis))) } def nextDate(): Date = nextTime().toDate(java.util.TimeZone.getTimeZone("UTC")) @@ -95,9 +96,10 @@ object generators { def setOf[T](generator: => T, maxLength: Int = DefaultMaxLength, minLength: Int = 0): Set[T] = seqOf(generator, maxLength, minLength).toSet - def mapOf[K, V](keyGenerator: => K, - valueGenerator: => V, - maxLength: Int = DefaultMaxLength, - minLength: Int = 0): Map[K, V] = + def mapOf[K, V]( + keyGenerator: => K, + valueGenerator: => V, + maxLength: Int = DefaultMaxLength, + minLength: Int = 0): Map[K, V] = seqOf(nextPair(keyGenerator, valueGenerator), maxLength, minLength).toMap } diff --git a/src/main/scala/xyz/driver/core/json.scala b/src/main/scala/xyz/driver/core/json.scala index 6b27a9c..313849c 100644 --- a/src/main/scala/xyz/driver/core/json.scala +++ b/src/main/scala/xyz/driver/core/json.scala @@ -168,9 +168,10 @@ object json { } } - class GadtJsonFormat[T: TypeTag](typeField: String, - typeValue: PartialFunction[T, String], - jsonFormat: PartialFunction[String, JsonFormat[_ <: T]]) + class GadtJsonFormat[T: TypeTag]( + typeField: String, + typeValue: PartialFunction[T, String], + jsonFormat: PartialFunction[String, JsonFormat[_ <: T]]) extends RootJsonFormat[T] { def write(value: T): JsValue = { @@ -210,7 +211,7 @@ object json { object GadtJsonFormat { def create[T: TypeTag](typeField: String)(typeValue: PartialFunction[T, String])( - jsonFormat: PartialFunction[String, JsonFormat[_ <: T]]) = { + jsonFormat: PartialFunction[String, JsonFormat[_ <: T]]) = { new GadtJsonFormat[T](typeField, typeValue, jsonFormat) } @@ -221,8 +222,9 @@ object json { * * @see https://github.com/fthomas/refined */ - implicit def refinedJsonFormat[T, Predicate](implicit valueFormat: JsonFormat[T], - validate: Validate[T, Predicate]): JsonFormat[Refined[T, Predicate]] = + implicit def refinedJsonFormat[T, Predicate]( + implicit valueFormat: JsonFormat[T], + validate: Validate[T, Predicate]): JsonFormat[Refined[T, Predicate]] = new JsonFormat[Refined[T, Predicate]] { def write(x: T Refined Predicate): JsValue = valueFormat.write(x.value) def read(value: JsValue): T Refined Predicate = { diff --git a/src/main/scala/xyz/driver/core/pubsub.scala b/src/main/scala/xyz/driver/core/pubsub.scala index 7885c1f..149b0db 100644 --- a/src/main/scala/xyz/driver/core/pubsub.scala +++ b/src/main/scala/xyz/driver/core/pubsub.scala @@ -22,8 +22,8 @@ object pubsub { } class GooglePubsubPublisher[Message](projectId: String, topic: String, log: Logger, autoCreate: Boolean = true)( - implicit messageMarshaller: Marshaller[Message, String], - ex: ExecutionContext + implicit messageMarshaller: Marshaller[Message, String], + ex: ExecutionContext ) extends PubsubPublisher[Message] { type Result = Id[PubsubMessage] @@ -72,8 +72,8 @@ object pubsub { } class FakePubsubPublisher[Message](topicName: String, log: Logger)( - implicit messageMarshaller: Marshaller[Message, String], - ex: ExecutionContext) + implicit messageMarshaller: Marshaller[Message, String], + ex: ExecutionContext) extends PubsubPublisher[Message] { type Result = Id[PubsubMessage] @@ -91,11 +91,11 @@ object pubsub { } class GooglePubsubSubscriber[Message]( - projectId: String, - subscriptionId: String, - receiver: Message => Future[Unit], - log: Logger, - autoCreateSettings: Option[GooglePubsubSubscriber.SubscriptionSettings] = None + projectId: String, + subscriptionId: String, + receiver: Message => Future[Unit], + log: Logger, + autoCreateSettings: Option[GooglePubsubSubscriber.SubscriptionSettings] = None )(implicit messageMarshaller: Unmarshaller[String, Message], mat: Materializer, ex: ExecutionContext) extends PubsubSubscriber { @@ -117,10 +117,11 @@ object pubsub { val subscriptionExists = Try(adminClient.getSubscription(subscriptionName)).isSuccess if (!subscriptionExists) { val topicName = TopicName.create(projectId, subscriptionSettings.topic) - adminClient.createSubscription(subscriptionName, - topicName, - subscriptionSettings.pushConfig, - subscriptionSettings.ackDeadlineSeconds) + adminClient.createSubscription( + subscriptionName, + topicName, + subscriptionSettings.pushConfig, + subscriptionSettings.ackDeadlineSeconds) } } diff --git a/src/main/scala/xyz/driver/core/rest/DriverRoute.scala b/src/main/scala/xyz/driver/core/rest/DriverRoute.scala index eb9a31a..4c483c6 100644 --- a/src/main/scala/xyz/driver/core/rest/DriverRoute.scala +++ b/src/main/scala/xyz/driver/core/rest/DriverRoute.scala @@ -55,10 +55,11 @@ trait DriverRoute { case cm: ConcurrentModificationException => ctx => log.warn(s"Concurrent modification of the resource ${ctx.request.method} ${ctx.request.uri}", cm) - errorResponse(ctx, - StatusCodes.Conflict, - "Resource was changed concurrently, try requesting a newer version", - cm)(ctx) + errorResponse( + ctx, + StatusCodes.Conflict, + "Resource was changed concurrently, try requesting a newer version", + cm)(ctx) case se: SQLException => ctx => @@ -98,10 +99,11 @@ trait DriverRoute { } } - protected def errorResponse[T <: Exception](ctx: RequestContext, - statusCode: StatusCode, - message: String, - exception: T): Route = { + protected def errorResponse[T <: Exception]( + ctx: RequestContext, + statusCode: StatusCode, + message: String, + exception: T): Route = { val trackingId = rest.extractTrackingId(ctx.request) MDC.put("trackingId", trackingId) complete(HttpResponse(statusCode, entity = message)) diff --git a/src/main/scala/xyz/driver/core/rest/HttpRestServiceTransport.scala b/src/main/scala/xyz/driver/core/rest/HttpRestServiceTransport.scala index 376b154..235c61d 100644 --- a/src/main/scala/xyz/driver/core/rest/HttpRestServiceTransport.scala +++ b/src/main/scala/xyz/driver/core/rest/HttpRestServiceTransport.scala @@ -15,12 +15,13 @@ import xyz.driver.core.time.provider.TimeProvider import scala.concurrent.{ExecutionContext, Future} import scala.util.{Failure, Success} -class HttpRestServiceTransport(applicationName: Name[App], - applicationVersion: String, - actorSystem: ActorSystem, - executionContext: ExecutionContext, - log: Logger, - time: TimeProvider) +class HttpRestServiceTransport( + applicationName: Name[App], + applicationVersion: String, + actorSystem: ActorSystem, + executionContext: ExecutionContext, + log: Logger, + time: TimeProvider) extends ServiceTransport { protected implicit val execution: ExecutionContext = executionContext @@ -36,10 +37,11 @@ class HttpRestServiceTransport(applicationName: Name[App], case (ContextHeaders.TrackingIdHeader, _) => RawHeader(ContextHeaders.TrackingIdHeader, context.trackingId) case (ContextHeaders.StacktraceHeader, _) => - RawHeader(ContextHeaders.StacktraceHeader, - Option(MDC.get("stack")) - .orElse(context.contextHeaders.get(ContextHeaders.StacktraceHeader)) - .getOrElse("")) + RawHeader( + ContextHeaders.StacktraceHeader, + Option(MDC.get("stack")) + .orElse(context.contextHeaders.get(ContextHeaders.StacktraceHeader)) + .getOrElse("")) case (header, headerValue) => RawHeader(header, headerValue) }: _*) @@ -67,7 +69,7 @@ class HttpRestServiceTransport(applicationName: Name[App], } def sendRequest(context: ServiceRequestContext)(requestStub: HttpRequest)( - implicit mat: Materializer): Future[Unmarshal[ResponseEntity]] = { + implicit mat: Materializer): Future[Unmarshal[ResponseEntity]] = { sendRequestGetResponse(context)(requestStub) flatMap { response => if (response.status == StatusCodes.NotFound) { diff --git a/src/main/scala/xyz/driver/core/rest/PooledHttpClient.scala b/src/main/scala/xyz/driver/core/rest/PooledHttpClient.scala index 2c9dcac..2854257 100644 --- a/src/main/scala/xyz/driver/core/rest/PooledHttpClient.scala +++ b/src/main/scala/xyz/driver/core/rest/PooledHttpClient.scala @@ -14,11 +14,11 @@ import scala.concurrent.duration._ import scala.util.{Failure, Success} class PooledHttpClient( - baseUri: Uri, - applicationName: Name[App], - applicationVersion: String, - requestRateLimit: Int = 64, - requestQueueSize: Int = 1024)(implicit actorSystem: ActorSystem, executionContext: ExecutionContext) + baseUri: Uri, + applicationName: Name[App], + applicationVersion: String, + requestRateLimit: Int = 64, + requestQueueSize: Int = 1024)(implicit actorSystem: ActorSystem, executionContext: ExecutionContext) extends HttpClient { private val host = baseUri.authority.host.toString() diff --git a/src/main/scala/xyz/driver/core/rest/RestService.scala b/src/main/scala/xyz/driver/core/rest/RestService.scala index aed8d28..c1d883a 100644 --- a/src/main/scala/xyz/driver/core/rest/RestService.scala +++ b/src/main/scala/xyz/driver/core/rest/RestService.scala @@ -24,11 +24,11 @@ trait RestService extends Service { OptionT[Future, Unit](request.flatMap(_.to[String]).map(_ => Option(()))) protected def optionalResponse[T](request: Future[Unmarshal[ResponseEntity]])( - implicit um: Unmarshaller[ResponseEntity, Option[T]]): OptionT[Future, T] = + implicit um: Unmarshaller[ResponseEntity, Option[T]]): OptionT[Future, T] = OptionT[Future, T](request.flatMap(_.fold(Option.empty[T]))) protected def listResponse[T](request: Future[Unmarshal[ResponseEntity]])( - implicit um: Unmarshaller[ResponseEntity, List[T]]): ListT[Future, T] = + implicit um: Unmarshaller[ResponseEntity, List[T]]): ListT[Future, T] = ListT[Future, T](request.flatMap(_.fold(List.empty[T]))) protected def jsonEntity(json: JsValue): RequestEntity = diff --git a/src/main/scala/xyz/driver/core/rest/Swagger.scala b/src/main/scala/xyz/driver/core/rest/Swagger.scala index e0efeaf..de785a7 100644 --- a/src/main/scala/xyz/driver/core/rest/Swagger.scala +++ b/src/main/scala/xyz/driver/core/rest/Swagger.scala @@ -10,12 +10,13 @@ import io.swagger.models.Scheme import scala.reflect.runtime.universe._ -class Swagger(override val host: String, - override val scheme: Scheme, - version: String, - override val actorSystem: ActorSystem, - override val apiTypes: Seq[Type], - val config: Config) +class Swagger( + override val host: String, + override val scheme: Scheme, + version: String, + override val actorSystem: ActorSystem, + override val apiTypes: Seq[Type], + val config: Config) extends SwaggerHttpService with HasActorSystem { val materializer: ActorMaterializer = ActorMaterializer()(actorSystem) diff --git a/src/main/scala/xyz/driver/core/rest/auth/AlwaysAllowAuthorization.scala b/src/main/scala/xyz/driver/core/rest/auth/AlwaysAllowAuthorization.scala index ea29a6a..5007774 100644 --- a/src/main/scala/xyz/driver/core/rest/auth/AlwaysAllowAuthorization.scala +++ b/src/main/scala/xyz/driver/core/rest/auth/AlwaysAllowAuthorization.scala @@ -7,7 +7,7 @@ import scala.concurrent.Future class AlwaysAllowAuthorization[U <: User] extends Authorization[U] { override def userHasPermissions(user: U, permissions: Seq[Permission])( - implicit ctx: ServiceRequestContext): Future[AuthorizationResult] = { + implicit ctx: ServiceRequestContext): Future[AuthorizationResult] = { val permissionsMap = permissions.map(_ -> true).toMap Future.successful(AuthorizationResult(authorized = permissionsMap, ctx.permissionsToken)) } diff --git a/src/main/scala/xyz/driver/core/rest/auth/AuthProvider.scala b/src/main/scala/xyz/driver/core/rest/auth/AuthProvider.scala index 35b65f7..9c89fc6 100644 --- a/src/main/scala/xyz/driver/core/rest/auth/AuthProvider.scala +++ b/src/main/scala/xyz/driver/core/rest/auth/AuthProvider.scala @@ -14,7 +14,7 @@ import scalaz.Scalaz.futureInstance import scalaz.OptionT abstract class AuthProvider[U <: User](val authorization: Authorization[U], log: Logger)( - implicit execution: ExecutionContext) { + implicit execution: ExecutionContext) { import akka.http.scaladsl.server._ import Directives._ diff --git a/src/main/scala/xyz/driver/core/rest/auth/Authorization.scala b/src/main/scala/xyz/driver/core/rest/auth/Authorization.scala index 87d0614..1a5e9be 100644 --- a/src/main/scala/xyz/driver/core/rest/auth/Authorization.scala +++ b/src/main/scala/xyz/driver/core/rest/auth/Authorization.scala @@ -7,5 +7,5 @@ import scala.concurrent.Future trait Authorization[U <: User] { def userHasPermissions(user: U, permissions: Seq[Permission])( - implicit ctx: ServiceRequestContext): Future[AuthorizationResult] + implicit ctx: ServiceRequestContext): Future[AuthorizationResult] } diff --git a/src/main/scala/xyz/driver/core/rest/auth/CachedTokenAuthorization.scala b/src/main/scala/xyz/driver/core/rest/auth/CachedTokenAuthorization.scala index 4f4c811..66de4ef 100644 --- a/src/main/scala/xyz/driver/core/rest/auth/CachedTokenAuthorization.scala +++ b/src/main/scala/xyz/driver/core/rest/auth/CachedTokenAuthorization.scala @@ -13,7 +13,7 @@ import scalaz.syntax.std.boolean._ class CachedTokenAuthorization[U <: User](publicKey: => PublicKey, issuer: String) extends Authorization[U] { override def userHasPermissions(user: U, permissions: Seq[Permission])( - implicit ctx: ServiceRequestContext): Future[AuthorizationResult] = { + implicit ctx: ServiceRequestContext): Future[AuthorizationResult] = { import spray.json._ def extractPermissionsFromTokenJSON(tokenObject: JsObject): Option[Map[String, Boolean]] = diff --git a/src/main/scala/xyz/driver/core/rest/auth/ChainedAuthorization.scala b/src/main/scala/xyz/driver/core/rest/auth/ChainedAuthorization.scala index f5eb402..131e7fc 100644 --- a/src/main/scala/xyz/driver/core/rest/auth/ChainedAuthorization.scala +++ b/src/main/scala/xyz/driver/core/rest/auth/ChainedAuthorization.scala @@ -12,7 +12,7 @@ class ChainedAuthorization[U <: User](authorizations: Authorization[U]*)(implici extends Authorization[U] { override def userHasPermissions(user: U, permissions: Seq[Permission])( - implicit ctx: ServiceRequestContext): Future[AuthorizationResult] = { + implicit ctx: ServiceRequestContext): Future[AuthorizationResult] = { def allAuthorized(permissionsMap: Map[Permission, Boolean]): Boolean = permissions.forall(permissionsMap.getOrElse(_, false)) diff --git a/src/main/scala/xyz/driver/core/rest/errors/serviceException.scala b/src/main/scala/xyz/driver/core/rest/errors/serviceException.scala index e91a3c2..d842c94 100644 --- a/src/main/scala/xyz/driver/core/rest/errors/serviceException.scala +++ b/src/main/scala/xyz/driver/core/rest/errors/serviceException.scala @@ -9,8 +9,7 @@ final case class InvalidInputException(override val message: String = "Invalid i final case class InvalidActionException(override val message: String = "This action is not allowed") extends ServiceException -final case class ResourceNotFoundException(override val message: String = "Resource not found") - extends ServiceException +final case class ResourceNotFoundException(override val message: String = "Resource not found") extends ServiceException final case class ExternalServiceException(serviceName: String, serviceMessage: String) extends ServiceException { override def message = s"Error while calling '$serviceName': $serviceMessage" diff --git a/src/main/scala/xyz/driver/core/rest/package.scala b/src/main/scala/xyz/driver/core/rest/package.scala index 03313d1..9ac1b62 100644 --- a/src/main/scala/xyz/driver/core/rest/package.scala +++ b/src/main/scala/xyz/driver/core/rest/package.scala @@ -30,7 +30,7 @@ trait ServiceTransport { def sendRequestGetResponse(context: ServiceRequestContext)(requestStub: HttpRequest): Future[HttpResponse] def sendRequest(context: ServiceRequestContext)(requestStub: HttpRequest)( - implicit mat: Materializer): Future[Unmarshal[ResponseEntity]] + implicit mat: Materializer): Future[Unmarshal[ResponseEntity]] } final case class Pagination(pageSize: Int, pageNumber: Int) { @@ -40,8 +40,8 @@ final case class Pagination(pageSize: Int, pageNumber: Int) { object `package` { implicit class OptionTRestAdditions[T](optionT: OptionT[Future, T]) { def responseOrNotFound(successCode: StatusCodes.Success = StatusCodes.OK)( - implicit F: Functor[Future], - em: ToEntityMarshaller[T]): Future[ToResponseMarshallable] = { + implicit F: Functor[Future], + em: ToEntityMarshaller[T]): Future[ToResponseMarshallable] = { optionT.fold[ToResponseMarshallable](successCode -> _, StatusCodes.NotFound -> None) } } @@ -101,9 +101,10 @@ object `package` { } def extractServiceContext(request: HttpRequest, remoteAddress: RemoteAddress): ServiceRequestContext = - new ServiceRequestContext(extractTrackingId(request), - extractOriginatingIP(request, remoteAddress), - extractContextHeaders(request)) + new ServiceRequestContext( + extractTrackingId(request), + extractOriginatingIP(request, remoteAddress), + extractContextHeaders(request)) def extractTrackingId(request: HttpRequest): String = { request.headers diff --git a/src/main/scala/xyz/driver/core/rest/serviceRequestContext.scala b/src/main/scala/xyz/driver/core/rest/serviceRequestContext.scala index 58ff1f1..5282956 100644 --- a/src/main/scala/xyz/driver/core/rest/serviceRequestContext.scala +++ b/src/main/scala/xyz/driver/core/rest/serviceRequestContext.scala @@ -8,9 +8,10 @@ import xyz.driver.core.generators import scalaz.Scalaz.{mapEqual, stringInstance} import scalaz.syntax.equal._ -class ServiceRequestContext(val trackingId: String = generators.nextUuid().toString, - val originatingIp: Option[InetAddress] = None, - val contextHeaders: Map[String, String] = Map.empty[String, String]) { +class ServiceRequestContext( + val trackingId: String = generators.nextUuid().toString, + val originatingIp: Option[InetAddress] = None, + val contextHeaders: Map[String, String] = Map.empty[String, String]) { def authToken: Option[AuthToken] = contextHeaders.get(AuthProvider.AuthenticationTokenHeader).map(AuthToken.apply) @@ -44,11 +45,11 @@ class ServiceRequestContext(val trackingId: String = generators.nextUuid().toStr override def toString: String = s"ServiceRequestContext($trackingId, $contextHeaders)" } -class AuthorizedServiceRequestContext[U <: User](override val trackingId: String = generators.nextUuid().toString, - override val originatingIp: Option[InetAddress] = None, - override val contextHeaders: Map[String, String] = - Map.empty[String, String], - val authenticatedUser: U) +class AuthorizedServiceRequestContext[U <: User]( + override val trackingId: String = generators.nextUuid().toString, + override val originatingIp: Option[InetAddress] = None, + override val contextHeaders: Map[String, String] = Map.empty[String, String], + val authenticatedUser: U) extends ServiceRequestContext { def withPermissionsToken(permissionsToken: PermissionsToken): AuthorizedServiceRequestContext[U] = diff --git a/src/main/scala/xyz/driver/core/swagger.scala b/src/main/scala/xyz/driver/core/swagger.scala index 44ca6e1..6567290 100644 --- a/src/main/scala/xyz/driver/core/swagger.scala +++ b/src/main/scala/xyz/driver/core/swagger.scala @@ -15,8 +15,9 @@ import spray.json._ object swagger { - def configureCustomSwaggerModels(customPropertiesExamples: Map[Class[_], Property], - customObjectsExamples: Map[Class[_], JsValue]) = { + def configureCustomSwaggerModels( + customPropertiesExamples: Map[Class[_], Property], + customObjectsExamples: Map[Class[_], JsValue]) = { ModelConverters .getInstance() .addConverter(new CustomSwaggerJsonConverter(Json.mapper(), customPropertiesExamples, customObjectsExamples)) @@ -54,16 +55,18 @@ object swagger { } @SuppressWarnings(Array("org.wartremover.warts.Null")) - class CustomSwaggerJsonConverter(mapper: ObjectMapper, - customProperties: Map[Class[_], Property], - customObjects: Map[Class[_], JsValue]) + class CustomSwaggerJsonConverter( + mapper: ObjectMapper, + customProperties: Map[Class[_], Property], + customObjects: Map[Class[_], JsValue]) extends AbstractModelConverter(mapper) { import CustomSwaggerJsonConverter._ - override def resolveProperty(`type`: Type, - context: ModelConverterContext, - annotations: Array[Annotation], - chain: util.Iterator[ModelConverter]): Property = { + override def resolveProperty( + `type`: Type, + context: ModelConverterContext, + annotations: Array[Annotation], + chain: util.Iterator[ModelConverter]): Property = { val javaType = Json.mapper().constructType(`type`) Option(javaType.getRawClass) flatMap { cls => |