play.api.Environment Scala Examples

The following examples show how to use play.api.Environment. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: PreferencesFrontendService.scala    From pertax-frontend   with Apache License 2.0 6 votes vote down vote up
package services

import com.kenshoo.play.metrics.Metrics
import config.ConfigDecorator
import controllers.auth.requests.UserRequest
import com.google.inject.{Inject, Singleton}
import metrics.HasMetrics
import models.{ActivatePaperlessActivatedResponse, ActivatePaperlessNotAllowedResponse, ActivatePaperlessRequiresUserActionResponse, ActivatePaperlessResponse}
import play.api.Mode.Mode
import play.api.i18n.{I18nSupport, Messages, MessagesApi}
import play.api.libs.json.{JsObject, Json}
import play.api.{Configuration, Environment, Logger}
import uk.gov.hmrc.play.bootstrap.http.DefaultHttpClient
import uk.gov.hmrc.crypto.PlainText
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import uk.gov.hmrc.play.bootstrap.filters.frontend.crypto.SessionCookieCrypto
import uk.gov.hmrc.play.partials.HeaderCarrierForPartialsConverter
import util.Tools

import scala.concurrent.{ExecutionContext, Future}

@Singleton
class PreferencesFrontendService @Inject()(
  environment: Environment,
  runModeConfiguration: Configuration,
  val simpleHttp: DefaultHttpClient,
  val messagesApi: MessagesApi,
  val metrics: Metrics,
  val configDecorator: ConfigDecorator,
  val sessionCookieCrypto: SessionCookieCrypto,
  val tools: Tools,
  servicesConfig: ServicesConfig)(implicit ec: ExecutionContext)
    extends HeaderCarrierForPartialsConverter with HasMetrics with I18nSupport {

  val mode: Mode = environment.mode
  val preferencesFrontendUrl = servicesConfig.baseUrl("preferences-frontend")

  override def crypto: String => String = cookie => cookie
  def getPaperlessPreference()(implicit request: UserRequest[_]): Future[ActivatePaperlessResponse] = {

    def absoluteUrl = configDecorator.pertaxFrontendHost + request.uri

    def activatePaperless: Future[ActivatePaperlessResponse] =
      withMetricsTimer("get-activate-paperless") { timer =>
        val url =
          s"$preferencesFrontendUrl/paperless/activate?returnUrl=${tools.encryptAndEncode(absoluteUrl)}&returnLinkText=${tools
            .encryptAndEncode(Messages("label.continue"))}" //TODO remove ref to Messages
        simpleHttp.PUT[JsObject, ActivatePaperlessResponse](url, Json.obj("active" -> true)) map {

          case ActivatePaperlessActivatedResponse =>
            timer.completeTimerAndIncrementSuccessCounter()
            ActivatePaperlessActivatedResponse

          case response: ActivatePaperlessRequiresUserActionResponse =>
            timer.completeTimerAndIncrementSuccessCounter()
            response

          case ActivatePaperlessNotAllowedResponse =>
            timer.completeTimerAndIncrementFailedCounter()
            ActivatePaperlessNotAllowedResponse
        } recover {
          case e =>
            timer.completeTimerAndIncrementFailedCounter()
            Logger.warn("Error getting paperless preference record from preferences-frontend-service", e)
            ActivatePaperlessNotAllowedResponse
        }
      }

    if (request.isGovernmentGateway) {
      activatePaperless
    } else {
      Future.successful(ActivatePaperlessNotAllowedResponse)
    }
  }

} 
Example 2
Source File: JacksonModule.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.javadsl.jackson

import akka.actor.ActorSystem
import akka.serialization.jackson.JacksonMigration
import play.api.Configuration
import play.api.Environment
import play.api.inject.Binding
import play.api.inject.Module
import javax.inject.Inject


class JacksonModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = Seq(
    bind[JacksonMigrationCheck].toSelf.eagerly(),
    bind[JacksonSerializerFactory].toSelf,
    bind[JacksonExceptionSerializer].toSelf
  )
}

private[lagom] class JacksonMigrationCheck @Inject() (system: ActorSystem) {
  if (system.settings.config.hasPath("lagom.serialization.json.migrations")) {
    throw new IllegalStateException(
      "JacksonJsonSerializer migrations defined in " +
        s"'lagom.serialization.json.migrations' must be rewritten as [${classOf[JacksonMigration].getName}] " +
        "and defined in config 'akka.serialization.jackson.migrations'."
    )
  }
} 
Example 3
Source File: AuthUtils.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.controllers

import de.frosner.broccoli.auth.{Account, Role}
import de.frosner.broccoli.services.SecurityService
import jp.t2v.lab.play2.auth.test.Helpers._
import org.mockito.Mockito._
import org.specs2.matcher.MatchResult
import org.specs2.matcher.MatchersImplicits._
import play.api.cache.CacheApi
import play.api.mvc.{Action, AnyContentAsEmpty, Result}
import play.api.test.Helpers._
import play.api.test._
import play.api.{Application, Environment}

import scala.concurrent.Future

trait AuthUtils extends ServiceMocks {

  def playEnv(implicit app: Application): Environment = app.injector.instanceOf[Environment]

  def cacheApi(implicit app: Application): CacheApi = app.injector.instanceOf[CacheApi]

  def testWithAllAuths[T <: AuthConfigImpl, B](account: Account)(controller: SecurityService => T)(
      action: T => Action[B])(requestModifier: FakeRequest[AnyContentAsEmpty.type] => FakeRequest[B])(
      matcher: (T, Future[Result]) => MatchResult[_]): MatchResult[_] = {
    val confAuthController = controller(withAuthConf(mock[SecurityService], List(account)))
    val confAuthRequest = requestModifier(FakeRequest().withLoggedIn(confAuthController)(account.name))
    val confAuthResult = action(confAuthController).apply(confAuthRequest)
    val confAuthMatcher = matcher(confAuthController, confAuthResult)

    val noAuthController = controller(withAuthNone(mock[SecurityService]))
    val noAuthRequest = requestModifier(FakeRequest())
    val confAuthNoLoginResult = action(confAuthController).apply(noAuthRequest)
    val confAuthNoLoginMatcher = status(confAuthNoLoginResult) === 403

    confAuthMatcher and confAuthNoLoginMatcher
  }

  def testWithAllAuths[T <: AuthConfigImpl, B](controller: SecurityService => T)(action: T => Action[B])(
      requestModifier: FakeRequest[AnyContentAsEmpty.type] => FakeRequest[B])(
      matcher: (T, Future[Result]) => MatchResult[_]): MatchResult[_] = {
    val account = Account("user", ".*", Role.Administrator)
    val noAuthController = controller(withAuthNone(mock[SecurityService]))
    val noAuthRequest = requestModifier(FakeRequest())
    val noAuthResult = action(noAuthController).apply(noAuthRequest)
    val noAuthMatcher = matcher(noAuthController, noAuthResult)

    val authMatchers = testWithAllAuths(account)(controller)(action)(requestModifier)(matcher)

    noAuthMatcher and authMatchers
  }

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

import javax.inject.Inject

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

import scala.concurrent.Future

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

  private val log = Logger(getClass)

  import scala.concurrent.ExecutionContext.Implicits.global

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

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

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

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

}

object SecurityController {

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

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

import javax.inject.Inject

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

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

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

}

object AboutController {

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

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

import com.mohiva.play.silhouette.api.LoginInfo
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import de.frosner.broccoli.auth.{Account, Role}
import de.frosner.broccoli.services.SecurityService
import jp.t2v.lab.play2.auth._
import play.api.{Environment, Mode}
import play.api.cache.CacheApi
import play.api.libs.json.JsString
import play.api.mvc.{RequestHeader, Result, Results}

import scala.concurrent.{ExecutionContext, Future}
import scala.reflect.ClassTag

trait AuthConfigImpl extends AuthConfig {

  val securityService: SecurityService

  val playEnv: Environment

  val cacheApi: CacheApi

  type Id = String

  type User = Account

  type Authority = Role

  val idTag: ClassTag[Id] = scala.reflect.classTag[Id]

  val sessionTimeoutInSeconds = securityService.sessionTimeoutInSeconds

  val cookieSecure = securityService.cookieSecure

  override lazy val idContainer: AsyncIdContainer[Id] = securityService.allowMultiLogin match {
    case true  => AsyncIdContainer(new MultiLoginCacheIdContainer[Id](cacheApi))
    case false => AsyncIdContainer(new CacheIdContainer[Id])
  }

  def resolveUser(id: Id)(implicit ctx: ExecutionContext): Future[Option[User]] =
    securityService.identityService.retrieve(LoginInfo(CredentialsProvider.ID, id))

  def loginSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext): Future[Result] =
    Future.successful(Results.Ok(JsString("Login successful!"))) // the content is not used anyway as the controller replaces it

  def logoutSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext): Future[Result] =
    Future.successful(Results.Ok(JsString("Logout successful!")))

  def authenticationFailed(request: RequestHeader)(implicit ctx: ExecutionContext): Future[Result] =
    Future.successful(Results.Forbidden("Authentication failed."))

  override def authorizationFailed(request: RequestHeader, user: User, authority: Option[Authority])(
      implicit context: ExecutionContext): Future[Result] =
    Future.successful(Results.Forbidden(
      s"Authorization failed: Your privileges (${user.role}) are not matching the required (${authority.getOrElse("None")})."))

  def authorize(user: User, authority: Authority)(implicit ctx: ExecutionContext): Future[Boolean] = Future.successful {
    user.role match {
      case Role.Administrator => true
      case Role.Operator      => authority == Role.Operator || authority == Role.User
      case Role.User          => authority == Role.User
    }
  }

  override lazy val tokenAccessor = new CookieTokenAccessor(
    cookieName = AuthConfigImpl.CookieName,
    cookieSecureOption = playEnv.mode == Mode.Prod && cookieSecure,
    cookieHttpOnlyOption = true,
    cookieDomainOption = None,
    cookiePathOption = "/",
    cookieMaxAge = Some(sessionTimeoutInSeconds)
  )

}

object AuthConfigImpl {

  val CookieName = "BROCCOLI_SESS_ID"

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

import javax.inject.Inject

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

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

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

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

}

object TemplateController {

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

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

import javax.inject.Inject

import cats.data.EitherT
import cats.instances.future._
import de.frosner.broccoli.services.WebSocketService.Msg
import de.frosner.broccoli.services._
import de.frosner.broccoli.websocket.{IncomingMessage, OutgoingMessage, WebSocketMessageHandler}
import jp.t2v.lab.play2.auth.BroccoliWebsocketSecurity
import play.api.cache.CacheApi
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.iteratee._
import play.api.libs.json._
import play.api.mvc._
import play.api.{Environment, Logger}

import scala.concurrent.Future

case class WebSocketController @Inject()(webSocketService: WebSocketService,
                                         templateService: TemplateService,
                                         instanceService: InstanceService,
                                         aboutService: AboutInfoService,
                                         messageHandler: WebSocketMessageHandler,
                                         override val cacheApi: CacheApi,
                                         override val playEnv: Environment,
                                         override val securityService: SecurityService)
    extends Controller
    with BroccoliWebsocketSecurity {

  protected val log = Logger(getClass)

  def requestToSocket(request: RequestHeader): Future[Either[Result, (Iteratee[Msg, _], Enumerator[Msg])]] =
    withSecurity(request) { (maybeToken, user, request) =>
      val (connectionId, connectionEnumerator) = maybeToken match {
        case Some(token) =>
          (token, webSocketService.newConnection(token, user)) // auth is enabled and we can use the session ID
        case None => webSocketService.newConnection(user) // no session ID available so we generate one
      }
      val connectionLogString = s"$connectionId by $user from ${request.remoteAddress} at $request"
      log.info(s"New connection $connectionLogString")

      // TODO receive string and try json decoding here because I can handle the error better
      val in = Enumeratee.mapM[Msg] { incomingMessage =>
        EitherT
          .fromEither(Json.fromJson[IncomingMessage](incomingMessage).asEither)
          .leftMap[OutgoingMessage] { jsonErrors =>
            log.warn(s"Can't parse a message from $connectionId: $jsonErrors")
            OutgoingMessage.Error(s"Failed to parse message message: $jsonErrors")
          }
          .semiflatMap { incomingMessage =>
            // Catch all exceptions from the message handler and map them to a generic error message to send over the
            // websocket, to prevent the Enumeratee from stopping at the failure, causing the websocket to be closed and
            // preventing all future messages.
            messageHandler.processMessage(user)(incomingMessage).recover {
              case exception =>
                log.error(s"Message handler threw exception for message $incomingMessage: ${exception.getMessage}",
                          exception)
                OutgoingMessage.Error("Unexpected error in message handler")
            }
          }
          .merge
      } transform Iteratee
        .foreach[OutgoingMessage](msg => webSocketService.send(connectionId, Json.toJson(msg)))
        .map { _ =>
          webSocketService.closeConnections(connectionId)
          log.info(s"Closed connection $connectionLogString")
        }

      val aboutEnumerator =
        Enumerator[Msg](Json.toJson(OutgoingMessage.AboutInfoMsg(AboutController.about(aboutService, user))))

      val templateEnumerator = Enumerator[Msg](
        Json.toJson(
          OutgoingMessage.ListTemplates(TemplateController.list(templateService))
        ))

      val instanceEnumerator = Enumerator[Msg](
        Json.toJson(OutgoingMessage.ListInstances(InstanceController.list(None, user, instanceService))))
      (in, aboutEnumerator.andThen(templateEnumerator).andThen(instanceEnumerator).andThen(connectionEnumerator))
    }

  def socket: WebSocket = WebSocket.tryAccept[Msg](requestToSocket)

} 
Example 9
Source File: MessagesSupport.scala    From play-ui   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play

import play.api.http.HttpConfiguration
import play.api.{Configuration, Environment}
import play.api.i18n._
import play.api.mvc.MessagesRequest
import play.api.test.FakeRequest

trait MessagesSupport {

  implicit lazy val messagesApi: MessagesApi = {

    val environment = Environment.simple()

    val configuration = Configuration.load(environment)

    val langs = new DefaultLangs()

    new DefaultMessagesApiProvider(
      environment       = environment,
      config            = configuration,
      langs             = langs,
      httpConfiguration = new HttpConfiguration()
    ).get
  }

  implicit val messages: Messages = new MessagesRequest(FakeRequest(), messagesApi).messages
} 
Example 10
Source File: CouchbaseClusteredPersistentEntitySpec.scala    From akka-persistence-couchbase   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.scaladsl.persistence.couchbase

import java.io.File

import akka.actor.{ActorSystem, CoordinatedShutdown}
import akka.persistence.couchbase.CouchbaseClusterConnection
import akka.stream.{ActorMaterializer, Materializer}
import com.lightbend.lagom.internal.persistence.couchbase.TestConfig
import com.lightbend.lagom.internal.persistence.testkit.AwaitPersistenceInit.awaitPersistenceInit
import com.lightbend.lagom.scaladsl.api.ServiceLocator
import com.lightbend.lagom.scaladsl.api.ServiceLocator.NoServiceLocator
import com.lightbend.lagom.scaladsl.persistence.multinode.{
  AbstractClusteredPersistentEntityConfig,
  AbstractClusteredPersistentEntitySpec
}
import com.lightbend.lagom.scaladsl.persistence.{ReadSideProcessor, TestEntity}
import com.lightbend.lagom.scaladsl.playjson.JsonSerializerRegistry
import com.typesafe.config.Config
import play.api.{Configuration, Environment, Mode}
import play.api.inject.DefaultApplicationLifecycle

import scala.concurrent.{ExecutionContext, Future}

object CouchbaseClusteredPersistentEntityConfig extends AbstractClusteredPersistentEntityConfig {
  override def additionalCommonConfig(databasePort: Int): Config =
    TestConfig.persistenceConfig
}

class CouchbaseClusteredPersistentEntitySpecMultiJvmNode1 extends CouchbaseClusteredPersistentEntitySpec
class CouchbaseClusteredPersistentEntitySpecMultiJvmNode2 extends CouchbaseClusteredPersistentEntitySpec
class CouchbaseClusteredPersistentEntitySpecMultiJvmNode3 extends CouchbaseClusteredPersistentEntitySpec

class CouchbaseClusteredPersistentEntitySpec
    extends AbstractClusteredPersistentEntitySpec(CouchbaseClusteredPersistentEntityConfig) {
  import com.lightbend.lagom.scaladsl.persistence.couchbase.CouchbaseClusteredPersistentEntityConfig._

  override protected def atStartup(): Unit = {
    runOn(node1) {
      CouchbaseClusterConnection.connect().cleanUp().close()
      awaitPersistenceInit(system)
    }
    enterBarrier("couchbase-started")

    super.atStartup()
  }

  lazy val defaultApplicationLifecycle = new DefaultApplicationLifecycle

  override lazy val components: CouchbasePersistenceComponents =
    new CouchbasePersistenceComponents {
      override def actorSystem: ActorSystem = system
      override def executionContext: ExecutionContext = system.dispatcher
      override def materializer: Materializer = ActorMaterializer()(system)
      override def configuration: Configuration = Configuration(system.settings.config)
      override def serviceLocator: ServiceLocator = NoServiceLocator
      override def environment: Environment = Environment(new File("."), getClass.getClassLoader, Mode.Test)
      override def jsonSerializerRegistry: JsonSerializerRegistry = ???
      override def coordinatedShutdown: CoordinatedShutdown = CoordinatedShutdown(system)
    }

  def testEntityReadSide = new TestEntityReadSide(components.actorSystem, components.couchbase)

  override protected def readSideProcessor: () => ReadSideProcessor[TestEntity.Evt] =
    () => new TestEntityReadSide.TestEntityReadSideProcessor(system, components.couchbaseReadSide)

  override protected def getAppendCount(id: String): Future[Long] = testEntityReadSide.getAppendCount(id)
} 
Example 11
Source File: CouchbasePersistenceModule.scala    From akka-persistence-couchbase   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.javadsl.persistence.couchbase

import java.net.URI

import akka.actor.ActorSystem
import akka.event.Logging
import akka.stream.alpakka.couchbase.javadsl.CouchbaseSession
import akka.stream.alpakka.couchbase.CouchbaseSessionSettings
import com.google.inject.Provider
import com.lightbend.lagom.internal.javadsl.persistence.couchbase.{
  CouchbasePersistentEntityRegistry,
  CouchbaseReadSideImpl,
  JavadslCouchbaseOffsetStore
}
import com.lightbend.lagom.internal.persistence.couchbase.{
  CouchbaseConfigValidator,
  CouchbaseOffsetStore,
  ServiceLocatorAdapter,
  ServiceLocatorHolder
}
import com.lightbend.lagom.javadsl.api.ServiceLocator
import com.lightbend.lagom.javadsl.persistence.PersistentEntityRegistry
import com.lightbend.lagom.spi.persistence.OffsetStore
import com.typesafe.config.Config
import javax.inject.Inject
import play.api.inject.{Binding, Injector, Module}
import play.api.{Configuration, Environment}

import scala.compat.java8.FutureConverters._
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
import scala.util.Try


class CouchbasePersistenceModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = Seq(
    bind[CouchbasePersistenceModule.InitServiceLocatorHolder].toSelf.eagerly(),
    bind[PersistentEntityRegistry].to[CouchbasePersistentEntityRegistry],
    bind[CouchbaseSession].toProvider[CouchbaseProvider],
    bind[CouchbaseReadSide].to[CouchbaseReadSideImpl],
    //TODO: add other modules similar to Cassandra
    //    bind[CassandraReadSideSettings].toSelf,
    bind[CouchbaseOffsetStore].to(bind[JavadslCouchbaseOffsetStore]),
    bind[OffsetStore].to(bind[CouchbaseOffsetStore])
  )
}

private[lagom] class CouchbaseProvider @Inject() (system: ActorSystem, cfg: Config) extends Provider[CouchbaseSession] {
  private val log = Logging(system, classOf[CouchbaseProvider])

  CouchbaseConfigValidator.validateBucket("lagom.persistence.read-side.couchbase", cfg, log)

  private val readSideCouchbaseConfig: Config =
    cfg.getConfig("lagom.persistence.read-side.couchbase")

  private val sessionSettings = CouchbaseSessionSettings(
    readSideCouchbaseConfig.getConfig("connection")
  )

  private val bucket = readSideCouchbaseConfig.getString("bucket")

  // FIXME is there a way to have async component creation in lagom instead of letting every component know that the thing is async?
  // if not we should pass Future[CouchbaseSession] around and let the use sites mix in AsyncCouchbaseSession - but if we use
  // that from Lagom it needs to be made public API
  // FIXME this should be the Java API of CouchbaseSession, when there is one
  lazy val couchbase: CouchbaseSession =
    Await.result(CouchbaseSession.create(sessionSettings, bucket, system.dispatcher).toScala, 30.seconds)

  override def get(): CouchbaseSession = couchbase
}

private[lagom] object CouchbasePersistenceModule {
  class InitServiceLocatorHolder @Inject() (system: ActorSystem, injector: Injector) {
    def init(): Unit =
      Try(injector.instanceOf[ServiceLocator]).foreach { locator =>
        ServiceLocatorHolder(system).setServiceLocator(new ServiceLocatorAdapter {
          override def locateAll(name: String): Future[List[URI]] = {
            import system.dispatcher

            import scala.collection.JavaConverters._
            import scala.compat.java8.FutureConverters._
            locator.locateAll(name).toScala.map(_.asScala.toList)
          }
        })
      }
  }
} 
Example 12
Source File: AppConfig.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package config

import javax.inject.{Inject, Singleton}
import play.api.{Configuration, Environment}
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig

@Singleton
class AppConfig @Inject()(val environment: Environment,
                          val configuration: Configuration,
                          config: ServicesConfig) {

  def appName: String = config.getString("appName")
  def appUrl: String = config.getString("appUrl")
  def registrationEnabled: Boolean = config.getBoolean("microservice.services.service-locator.enabled")

  def featureSwitch: Option[Configuration] = configuration.getOptional[Configuration](s"feature-switch")
  def apiStatus(version: String): String = config.getString(s"api.$version.status")
  def apiGatewayContext: String = config.getString("api.gateway.context")

  //Services
  def saApiUrl: String = config.baseUrl("self-assessment-api")
  def cgApiUrl: String = config.baseUrl("mtd-charitable-giving")
  def taxCalcUrl: String = config.baseUrl("mtd-tax-calculation")
  def propertyUrl: String = config.baseUrl("mtd-property-api")
  def selfEmploymentUrl: String = config.baseUrl("mtd-self-employment")
  def release2Enabled: Boolean = config.getBoolean("release-2.enabled")
  def dividendsApiUrl: String = config.baseUrl("mtd-dividends-income")
  def savingsAccountApiUrl: String = config.baseUrl("mtd-savings-accounts")
  def crystallisationApiUrl: String = config.baseUrl("mtd-crystallisation")

} 
Example 13
Source File: AkkaManagementComponents.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.scaladsl.server

import akka.actor.ActorSystem
import akka.actor.CoordinatedShutdown
import com.lightbend.lagom.internal.akka.management.AkkaManagementTrigger
import play.api.Environment
import play.api.Mode

import scala.concurrent.ExecutionContext

trait AkkaManagementComponents {
  def configuration: play.api.Configuration
  def actorSystem: ActorSystem
  def coordinatedShutdown: CoordinatedShutdown
  def environment: Environment

  def executionContext: ExecutionContext

  // eager initialization
  private[lagom] val akkaManagementTrigger: AkkaManagementTrigger = {
    val instance =
      new AkkaManagementTrigger(configuration.underlying, actorSystem, coordinatedShutdown)(executionContext)
    if (environment.mode == Mode.Prod) {
      instance.start()
    }
    instance
  }
} 
Example 14
Source File: AkkaManagementModule.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.javadsl.server

import akka.actor.ActorSystem
import akka.actor.CoordinatedShutdown
import com.lightbend.lagom.internal.akka.management.AkkaManagementTrigger
import com.typesafe.config.Config
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
import play.api.inject.Binding
import play.api.inject.Module
import play.api.Configuration
import play.api.Environment
import play.api.Mode

import scala.concurrent.ExecutionContext

private[lagom] class AkkaManagementModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = {
    // The trigger must be eager because it's often not required by anyone as a dependency to
    // be injected and yet it must be started anyway
    Seq(bind[AkkaManagementTrigger].toProvider[AkkaManagementProvider].eagerly())
  }
}

@Singleton
private[lagom] class AkkaManagementProvider @Inject() (
    config: Config,
    actorSystem: ActorSystem,
    coordinatedShutdown: CoordinatedShutdown,
    environment: Environment,
    executionContext: ExecutionContext
) extends Provider[AkkaManagementTrigger] {
  override def get(): AkkaManagementTrigger = {
    val instance = new AkkaManagementTrigger(config, actorSystem, coordinatedShutdown)(executionContext)
    if (environment.mode == Mode.Prod) {
      instance.start()
    }
    instance
  }
} 
Example 15
Source File: Application.scala    From scalajs-spa-tutorial   with Apache License 2.0 5 votes vote down vote up
package controllers

import java.nio.ByteBuffer

import boopickle.Default._
import com.google.inject.Inject
import play.api.{Configuration, Environment}
import play.api.mvc._
import services.ApiService
import spatutorial.shared.Api

import scala.concurrent.ExecutionContext.Implicits.global

object Router extends autowire.Server[ByteBuffer, Pickler, Pickler] {
  override def read[R: Pickler](p: ByteBuffer) = Unpickle[R].fromBytes(p)
  override def write[R: Pickler](r: R) = Pickle.intoBytes(r)
}

class Application @Inject() (implicit val config: Configuration, env: Environment) extends Controller {
  val apiService = new ApiService()

  def index = Action {
    Ok(views.html.index("SPA tutorial"))
  }

  def autowireApi(path: String) = Action.async(parse.raw) {
    implicit request =>
      println(s"Request path: $path")

      // get the request body as ByteString
      val b = request.body.asBytes(parse.UNLIMITED).get

      // call Autowire route
      Router.route[Api](apiService)(
        autowire.Core.Request(path.split("/"), Unpickle[Map[String, ByteBuffer]].fromBytes(b.asByteBuffer))
      ).map(buffer => {
        val data = Array.ofDim[Byte](buffer.remaining())
        buffer.get(data)
        Ok(data)
      })
  }

  def logging = Action(parse.anyContent) {
    implicit request =>
      request.body.asJson.foreach { msg =>
        println(s"CLIENT - $msg")
      }
      Ok("")
  }
} 
Example 16
Source File: ClusterComponents.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.scaladsl.cluster

import akka.actor.ActorSystem
import akka.cluster.Cluster
import com.lightbend.lagom.internal.cluster.JoinClusterImpl
import com.lightbend.lagom.scaladsl.cluster.typed.ClusterShardingTypedComponents
import com.lightbend.lagom.scaladsl.playjson.RequiresJsonSerializerRegistry
import com.lightbend.lagom.scaladsl.server.AkkaManagementComponents
import play.api.Environment


trait ClusterComponents
    extends RequiresJsonSerializerRegistry
    with AkkaManagementComponents
    with ClusterShardingTypedComponents {
  def actorSystem: ActorSystem
  def environment: Environment

  // eager initialization
  val cluster: Cluster = {
    JoinClusterImpl.join(actorSystem, environment, akkaManagementTrigger)
    Cluster(actorSystem)
  }
} 
Example 17
Source File: JoinCluster.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.javadsl.cluster

import akka.actor.ActorSystem
import com.lightbend.lagom.internal.akka.management.AkkaManagementTrigger
import com.lightbend.lagom.internal.cluster.JoinClusterImpl
import javax.inject.Inject
import play.api.Configuration
import play.api.Environment
import play.api.inject.Binding
import play.api.inject.Module

class JoinClusterModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = Seq(
    bind[JoinCluster].toSelf.eagerly()
  )
}

private[lagom] class JoinCluster @Inject() (
    system: ActorSystem,
    environment: Environment,
    akkaManagementTrigger: AkkaManagementTrigger
) {
  JoinClusterImpl.join(system, environment, akkaManagementTrigger)
} 
Example 18
Source File: ClusterShardingTypedModule.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.javadsl.cluster.typed

import akka.actor.ActorSystem
import akka.cluster.sharding.typed.javadsl.ClusterSharding
import javax.inject.Inject
import javax.inject.Provider
import play.api.Configuration
import play.api.Environment
import play.api.inject.Binding
import play.api.inject.Module

class ClusterShardingTypedModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = Seq(
    bind[ClusterSharding].toProvider[ClusterShardingTypedProvider]
  )
}

private[lagom] class ClusterShardingTypedProvider @Inject() (system: ActorSystem) extends Provider[ClusterSharding] {
  private val instance: ClusterSharding = {
    import akka.actor.typed.scaladsl.adapter._
    val actorSystemTyped = system.toTyped
    ClusterSharding.get(actorSystemTyped)
  }

  override def get(): ClusterSharding = instance
} 
Example 19
Source File: SlickOffsetStoreSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.persistence.jdbc

import akka.cluster.Cluster
import akka.pattern.AskTimeoutException
import com.lightbend.lagom.persistence.ActorSystemSpec
import play.api.Configuration
import play.api.Environment
import slick.jdbc.meta.MTable

import scala.concurrent.Await
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.duration._

class SlickOffsetStoreSpec extends ActorSystemSpec(Configuration.load(Environment.simple()).underlying) {
  import system.dispatcher

  private lazy val slick = new SlickProvider(system, coordinatedShutdown)

  private lazy val offsetStore = new SlickOffsetStore(
    system,
    slick,
    TestOffsetStoreConfiguration()
  )

  protected override def beforeAll(): Unit = {
    super.beforeAll()
    // Trigger database to be loaded and registered to JNDI
    SlickDbTestProvider.buildAndBindSlickDb(system.name, coordinatedShutdown)
  }

  "SlickOffsetStoreSpec" when {
    "auto-creating tables is enabled" should {
      // Regression test for https://github.com/lagom/lagom/issues/1336
      "allow prepare to be retried after a failure" in {
        val exception = Await.result(offsetStore.prepare("test_read_side", "TestTag").failed, 10.seconds)
        exception shouldBe a[AskTimeoutException]

        // Join ourselves - needed because we're using cluster singleton to create tables
        val cluster = Cluster(system)
        cluster.join(cluster.selfAddress)

        Await.result(offsetStore.prepare("test_read_side", "TestTag"), 20.seconds)

        val tables = Await.result(slick.db.run(MTable.getTables("test_read_side_offsets_tbl")), 5.seconds)
        (tables should have).length(1)
      }

      
      "creates the read-side offset table when preparing" in pending
      "allows prepare to be called multiple times" in pending
      "uses configured column names" in pending
      "returns an offset DAO with the last stored offset" in pending
    }

    "auto-creating tables is disabled" in pending
  }

  private case class TestOffsetStoreConfiguration(
      tableName: String = "test_read_side_offsets_tbl",
      schemaName: Option[String] = None,
      idColumnName: String = "test_read_side_id_col",
      tagColumnName: String = "test_tag_col",
      sequenceOffsetColumnName: String = "test_sequence_offset_col",
      timeUuidOffsetColumnName: String = "test_time_uuid_offset_col",
      minBackoff: FiniteDuration = 1.second,
      maxBackoff: FiniteDuration = 1.second,
      randomBackoffFactor: Double = 0,
      globalPrepareTimeout: FiniteDuration = 5.seconds,
      role: Option[String] = None
  ) extends SlickOffsetStoreConfiguration
} 
Example 20
Source File: JdbcPersistenceSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.scaladsl.persistence.jdbc

import akka.actor.setup.ActorSystemSetup
import akka.actor.ActorSystem
import akka.actor.BootstrapSetup
import akka.cluster.Cluster
import com.lightbend.lagom.internal.persistence.ReadSideConfig
import com.lightbend.lagom.internal.persistence.jdbc.SlickDbTestProvider
import com.lightbend.lagom.internal.persistence.jdbc.SlickOffsetStore
import com.lightbend.lagom.internal.persistence.jdbc.SlickProvider
import com.lightbend.lagom.internal.persistence.testkit.AwaitPersistenceInit.awaitPersistenceInit
import com.lightbend.lagom.internal.scaladsl.persistence.jdbc.JdbcReadSideImpl
import com.lightbend.lagom.internal.scaladsl.persistence.jdbc.OffsetTableConfiguration
import com.lightbend.lagom.persistence.ActorSystemSpec
import com.lightbend.lagom.persistence.PersistenceSpec
import com.lightbend.lagom.scaladsl.playjson.JsonSerializerRegistry
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import play.api.Configuration
import play.api.Environment

import scala.concurrent.Await
import scala.concurrent.duration._

abstract class JdbcPersistenceSpec private (actorSystemFactory: () => ActorSystem)
    extends ActorSystemSpec(actorSystemFactory) {
  def this(testName: String, config: Config, registry: JsonSerializerRegistry) =
    this(
      () =>
        ActorSystem(
          testName,
          ActorSystemSetup(
            BootstrapSetup(
              config.withFallback(Configuration.load(Environment.simple()).underlying)
            ),
            JsonSerializerRegistry.serializationSetupFor(registry)
          )
        )
    )

  def this(config: Config, registry: JsonSerializerRegistry) =
    this(PersistenceSpec.testNameFromCallStack(classOf[JdbcPersistenceSpec]), config, registry)

  def this(registry: JsonSerializerRegistry) = this(ConfigFactory.empty(), registry)

  import system.dispatcher

  protected lazy val slick = new SlickProvider(system, coordinatedShutdown)
  protected lazy val jdbcReadSide: JdbcReadSide = new JdbcReadSideImpl(
    slick,
    new SlickOffsetStore(
      system,
      slick,
      new OffsetTableConfiguration(system.settings.config, ReadSideConfig())
    )
  )

  override def beforeAll(): Unit = {
    super.beforeAll()

    // Join ourselves - needed because we're using cluster singleton to create tables
    val cluster = Cluster(system)
    cluster.join(cluster.selfAddress)

    // Trigger database to be loaded and registered to JNDI
    SlickDbTestProvider.buildAndBindSlickDb(system.name, coordinatedShutdown)

    // Trigger tables to be created
    Await.ready(slick.ensureTablesCreated(), 20.seconds)

    awaitPersistenceInit(system)
  }
} 
Example 21
Source File: SlickPersistenceSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.scaladsl.persistence.slick

import akka.actor.setup.ActorSystemSetup
import akka.actor.ActorSystem
import akka.actor.BootstrapSetup
import akka.cluster.Cluster
import com.lightbend.lagom.internal.persistence.ReadSideConfig
import com.lightbend.lagom.internal.persistence.jdbc.SlickDbTestProvider
import com.lightbend.lagom.internal.persistence.jdbc.SlickOffsetStore
import com.lightbend.lagom.internal.persistence.jdbc.SlickProvider
import com.lightbend.lagom.internal.persistence.testkit.AwaitPersistenceInit.awaitPersistenceInit
import com.lightbend.lagom.internal.scaladsl.persistence.jdbc.OffsetTableConfiguration
import com.lightbend.lagom.internal.scaladsl.persistence.slick.SlickReadSideImpl
import com.lightbend.lagom.persistence.ActorSystemSpec
import com.lightbend.lagom.persistence.PersistenceSpec
import com.lightbend.lagom.scaladsl.playjson.JsonSerializerRegistry
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import play.api.Configuration
import play.api.Environment

import scala.concurrent.Await
import scala.concurrent.duration._

abstract class SlickPersistenceSpec private (actorSystemFactory: () => ActorSystem)
    extends ActorSystemSpec(actorSystemFactory) {
  def this(testName: String, config: Config, registry: JsonSerializerRegistry) =
    this(
      () =>
        ActorSystem(
          testName,
          ActorSystemSetup(
            BootstrapSetup(
              config.withFallback(Configuration.load(Environment.simple()).underlying)
            ),
            JsonSerializerRegistry.serializationSetupFor(registry)
          )
        )
    )

  def this(config: Config, registry: JsonSerializerRegistry) =
    this(PersistenceSpec.testNameFromCallStack(classOf[SlickPersistenceSpec]), config, registry)

  def this(registry: JsonSerializerRegistry) =
    this(ConfigFactory.empty(), registry)

  import system.dispatcher

  protected lazy val slick = new SlickProvider(system, coordinatedShutdown)
  protected lazy val slickReadSide: SlickReadSide = {
    val offsetStore =
      new SlickOffsetStore(
        system,
        slick,
        new OffsetTableConfiguration(system.settings.config, ReadSideConfig())
      )
    new SlickReadSideImpl(slick, offsetStore)
  }

  override def beforeAll(): Unit = {
    super.beforeAll()

    // Join ourselves - needed because we're using cluster singleton to create tables
    val cluster = Cluster(system)
    cluster.join(cluster.selfAddress)

    // Trigger database to be loaded and registered to JNDI
    SlickDbTestProvider.buildAndBindSlickDb(system.name, coordinatedShutdown)

    // Trigger tables to be created
    Await.ready(slick.ensureTablesCreated(), 20.seconds)

    awaitPersistenceInit(system)
  }
} 
Example 22
Source File: SlickClusteredPersistentEntitySpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.scaladsl.persistence.slick

import akka.actor.ActorSystem
import akka.actor.CoordinatedShutdown
import akka.stream.Materializer
import akka.stream.SystemMaterializer
import com.lightbend.lagom.scaladsl.persistence.TestEntity.Evt
import com.lightbend.lagom.scaladsl.persistence.multinode.AbstractClusteredPersistentEntityConfig
import com.lightbend.lagom.scaladsl.persistence.multinode.AbstractClusteredPersistentEntitySpec
import com.lightbend.lagom.scaladsl.persistence.ReadSideProcessor
import com.lightbend.lagom.scaladsl.persistence.TestEntitySerializerRegistry
import com.lightbend.lagom.scaladsl.persistence.multinode.AbstractClusteredPersistentEntitySpec.Ports
import com.lightbend.lagom.scaladsl.playjson.JsonSerializerRegistry
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import org.h2.tools.Server
import play.api.Configuration
import play.api.Environment
import play.api.db.HikariCPComponents
import play.api.inject.ApplicationLifecycle
import play.api.inject.DefaultApplicationLifecycle

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

object SlickClusteredPersistentEntityConfig extends AbstractClusteredPersistentEntityConfig {

  override def specPorts: Ports.SpecPorts = Ports.slickSpecPorts

  override def additionalCommonConfig: Config = ConfigFactory.parseString(
    s"""
      db.default.driver=org.h2.Driver
      db.default.url="jdbc:h2:tcp://localhost:${specPorts.database}/mem:JdbcClusteredPersistentEntitySpec"
    """
  )
}

class SlickClusteredPersistentEntitySpecMultiJvmNode1 extends SlickClusteredPersistentEntitySpec
class SlickClusteredPersistentEntitySpecMultiJvmNode2 extends SlickClusteredPersistentEntitySpec
class SlickClusteredPersistentEntitySpecMultiJvmNode3 extends SlickClusteredPersistentEntitySpec

class SlickClusteredPersistentEntitySpec
    extends AbstractClusteredPersistentEntitySpec(SlickClusteredPersistentEntityConfig) {
  import SlickClusteredPersistentEntityConfig._

  var h2: Server = _

  protected override def atStartup(): Unit = {
    runOn(node1) {
      h2 = Server.createTcpServer("-tcpPort", specPorts.database.toString, "-ifNotExists").start()
    }
    enterBarrier("h2-started")
    super.atStartup()
  }

  protected override def afterTermination(): Unit = {
    super.afterTermination()
    Await.ready(defaultApplicationLifecycle.stop(), shutdownTimeout)
    Option(h2).foreach(_.stop())
  }

  lazy val defaultApplicationLifecycle = new DefaultApplicationLifecycle

  override lazy val components: SlickPersistenceComponents =
    new SlickPersistenceComponents with HikariCPComponents {
      override def actorSystem: ActorSystem                 = SlickClusteredPersistentEntitySpec.this.system
      override def executionContext: ExecutionContext       = system.dispatcher
      override def coordinatedShutdown: CoordinatedShutdown = CoordinatedShutdown(actorSystem)

      override lazy val materializer: Materializer                 = SystemMaterializer(actorSystem).materializer
      override lazy val configuration: Configuration               = Configuration(system.settings.config)
      override def environment: Environment                        = SlickClusteredPersistentEntityConfig.environment
      override lazy val applicationLifecycle: ApplicationLifecycle = defaultApplicationLifecycle
      override def jsonSerializerRegistry: JsonSerializerRegistry  = TestEntitySerializerRegistry
    }

  lazy val jdbcTestEntityReadSide: SlickTestEntityReadSide =
    new SlickTestEntityReadSide(
      components.db,
      components.profile
    )(components.executionContext)

  protected override def getAppendCount(id: String): Future[Long] =
    jdbcTestEntityReadSide.getAppendCount(id)

  protected override def readSideProcessor: () => ReadSideProcessor[Evt] = { () =>
    new SlickTestEntityReadSide.TestEntityReadSideProcessor(
      components.slickReadSide,
      components.db,
      components.profile
    )(components.executionContext)
  }
} 
Example 23
Source File: JdbcClusteredPersistentEntitySpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.scaladsl.persistence.jdbc

import akka.actor.ActorSystem
import akka.actor.CoordinatedShutdown
import akka.stream.Materializer
import akka.stream.SystemMaterializer
import com.lightbend.lagom.scaladsl.persistence.TestEntity.Evt
import com.lightbend.lagom.scaladsl.persistence.multinode.AbstractClusteredPersistentEntityConfig
import com.lightbend.lagom.scaladsl.persistence.multinode.AbstractClusteredPersistentEntitySpec
import com.lightbend.lagom.scaladsl.persistence.ReadSideProcessor
import com.lightbend.lagom.scaladsl.persistence.TestEntitySerializerRegistry
import com.lightbend.lagom.scaladsl.persistence.multinode.AbstractClusteredPersistentEntitySpec.Ports
import com.lightbend.lagom.scaladsl.playjson.JsonSerializerRegistry
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import org.h2.tools.Server
import play.api.Configuration
import play.api.Environment
import play.api.db.HikariCPComponents
import play.api.inject.ApplicationLifecycle
import play.api.inject.DefaultApplicationLifecycle

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

object JdbcClusteredPersistentEntityConfig extends AbstractClusteredPersistentEntityConfig {

  override def specPorts: Ports.SpecPorts = Ports.jdbcSpecPorts

  override def additionalCommonConfig: Config = ConfigFactory.parseString(
    s"""
      db.default.driver=org.h2.Driver
      db.default.url="jdbc:h2:tcp://localhost:${specPorts.database}/mem:JdbcClusteredPersistentEntitySpec"
    """
  )
}

class JdbcClusteredPersistentEntitySpecMultiJvmNode1 extends JdbcClusteredPersistentEntitySpec
class JdbcClusteredPersistentEntitySpecMultiJvmNode2 extends JdbcClusteredPersistentEntitySpec
class JdbcClusteredPersistentEntitySpecMultiJvmNode3 extends JdbcClusteredPersistentEntitySpec

class JdbcClusteredPersistentEntitySpec
    extends AbstractClusteredPersistentEntitySpec(JdbcClusteredPersistentEntityConfig) {
  import JdbcClusteredPersistentEntityConfig._

  var h2: Server = _

  protected override def atStartup(): Unit = {
    runOn(node1) {
      h2 = Server.createTcpServer("-tcpPort", specPorts.database.toString, "-ifNotExists").start()
    }

    enterBarrier("h2-started")
    super.atStartup()
  }

  protected override def afterTermination(): Unit = {
    super.afterTermination()
    Await.ready(defaultApplicationLifecycle.stop(), shutdownTimeout)
    Option(h2).foreach(_.stop())
  }

  lazy val defaultApplicationLifecycle = new DefaultApplicationLifecycle

  override lazy val components: JdbcPersistenceComponents =
    new JdbcPersistenceComponents with HikariCPComponents {
      override def actorSystem: ActorSystem                 = JdbcClusteredPersistentEntitySpec.this.system
      override def executionContext: ExecutionContext       = system.dispatcher
      override def coordinatedShutdown: CoordinatedShutdown = CoordinatedShutdown(actorSystem)

      override lazy val materializer: Materializer                 = SystemMaterializer(actorSystem).materializer
      override lazy val configuration: Configuration               = Configuration(system.settings.config)
      override def environment: Environment                        = JdbcClusteredPersistentEntityConfig.environment
      override lazy val applicationLifecycle: ApplicationLifecycle = defaultApplicationLifecycle
      override def jsonSerializerRegistry: JsonSerializerRegistry  = TestEntitySerializerRegistry
    }

  lazy val jdbcTestEntityReadSide: JdbcTestEntityReadSide =
    new JdbcTestEntityReadSide(components.jdbcSession)

  protected override def getAppendCount(id: String): Future[Long] =
    jdbcTestEntityReadSide.getAppendCount(id)

  protected override def readSideProcessor: () => ReadSideProcessor[Evt] = { () =>
    new JdbcTestEntityReadSide.TestEntityReadSideProcessor(components.jdbcReadSide)
  }
} 
Example 24
Source File: JdbcPersistenceSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.javadsl.persistence.jdbc

import akka.actor.ActorSystem
import akka.cluster.Cluster
import com.lightbend.lagom.internal.javadsl.persistence.jdbc._
import com.lightbend.lagom.internal.persistence.ReadSideConfig
import com.lightbend.lagom.internal.persistence.jdbc.SlickDbTestProvider
import com.lightbend.lagom.internal.persistence.testkit.AwaitPersistenceInit.awaitPersistenceInit
import com.lightbend.lagom.persistence.ActorSystemSpec
import com.lightbend.lagom.persistence.PersistenceSpec
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import play.api.Configuration
import play.api.Environment

import scala.concurrent.Await
import scala.concurrent.duration._

abstract class JdbcPersistenceSpec private (actorSystemFactory: () => ActorSystem)
    extends ActorSystemSpec(actorSystemFactory) {
  def this(testName: String, config: Config) = {
    this(() => ActorSystem(testName, config.withFallback(Configuration.load(Environment.simple()).underlying)))
  }

  def this(config: Config) = this(PersistenceSpec.testNameFromCallStack(classOf[JdbcPersistenceSpec]), config)

  def this() = this(ConfigFactory.empty())

  import system.dispatcher

  protected lazy val slick = new SlickProvider(system, coordinatedShutdown)

  protected lazy val offsetStore =
    new JavadslJdbcOffsetStore(
      slick,
      system,
      new OffsetTableConfiguration(
        system.settings.config,
        ReadSideConfig()
      ),
      ReadSideConfig()
    )
  protected lazy val jdbcReadSide: JdbcReadSide = new JdbcReadSideImpl(slick, offsetStore)

  override def beforeAll(): Unit = {
    super.beforeAll()

    // Join ourselves - needed because we're using cluster singleton to create tables
    val cluster = Cluster(system)
    cluster.join(cluster.selfAddress)

    // Trigger database to be loaded and registered to JNDI
    SlickDbTestProvider.buildAndBindSlickDb(system.name, coordinatedShutdown)

    // Trigger tables to be created
    Await.ready(slick.ensureTablesCreated(), 20.seconds)

    awaitPersistenceInit(system)
  }
} 
Example 25
Source File: JdbcPersistenceModule.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.javadsl.persistence.jdbc

import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
import akka.actor.ActorSystem
import akka.actor.CoordinatedShutdown
import com.lightbend.lagom.internal.javadsl.persistence.jdbc._
import com.lightbend.lagom.internal.persistence.jdbc.SlickDbProvider
import com.lightbend.lagom.internal.persistence.jdbc.SlickOffsetStore
import com.lightbend.lagom.javadsl.persistence.PersistentEntityRegistry
import com.lightbend.lagom.spi.persistence.OffsetStore
import play.api.Configuration
import play.api.Environment
import play.api.db.DBApi
import play.api.inject.Binding
import play.api.inject.Module

import scala.concurrent.ExecutionContext

class JdbcPersistenceModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = Seq(
    bind[SlickProvider].toProvider[GuiceSlickProvider],
    bind[JdbcReadSide].to[JdbcReadSideImpl],
    bind[PersistentEntityRegistry].to[JdbcPersistentEntityRegistry],
    bind[JdbcSession].to[JdbcSessionImpl],
    bind[SlickOffsetStore].to[JavadslJdbcOffsetStore],
    bind[OffsetStore].to(bind[SlickOffsetStore])
  )
}

@Singleton
class GuiceSlickProvider @Inject() (
    dbApi: DBApi,
    actorSystem: ActorSystem,
    coordinatedShutdown: CoordinatedShutdown
)(
    implicit ec: ExecutionContext
) extends Provider[SlickProvider] {
  lazy val get = {
    // Ensures JNDI bindings are made before we build the SlickProvider
    SlickDbProvider.buildAndBindSlickDatabases(
      dbApi,
      actorSystem.settings.config,
      coordinatedShutdown
    )
    new SlickProvider(actorSystem, coordinatedShutdown)
  }
} 
Example 26
Source File: CassandraPersistenceModule.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.javadsl.persistence.cassandra

import java.net.URI

import scala.concurrent.Future
import akka.actor.ActorSystem
import com.lightbend.lagom.internal.javadsl.persistence.cassandra._
import com.lightbend.lagom.internal.persistence.cassandra.CassandraOffsetStore
import com.lightbend.lagom.internal.persistence.cassandra.CassandraReadSideSettings
import com.lightbend.lagom.internal.persistence.cassandra.ServiceLocatorAdapter
import com.lightbend.lagom.internal.persistence.cassandra.ServiceLocatorHolder
import com.lightbend.lagom.javadsl.api.ServiceLocator
import com.lightbend.lagom.javadsl.persistence.PersistentEntityRegistry
import com.lightbend.lagom.spi.persistence.OffsetStore
import javax.annotation.PostConstruct
import javax.inject.Inject
import play.api.Configuration
import play.api.Environment
import play.api.inject._

import scala.util.Try


class CassandraPersistenceModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = Seq(
    bind[CassandraPersistenceModule.InitServiceLocatorHolder].toSelf.eagerly(),
    bind[PersistentEntityRegistry].to[CassandraPersistentEntityRegistry],
    bind[CassandraSession].toSelf,
    bind[CassandraReadSide].to[CassandraReadSideImpl],
    bind[CassandraReadSideSettings].toSelf,
    bind[CassandraOffsetStore].to[JavadslCassandraOffsetStore],
    bind[OffsetStore].to(bind[CassandraOffsetStore])
  )
}

private[lagom] object CassandraPersistenceModule {
  class InitServiceLocatorHolder @Inject() (system: ActorSystem, injector: Injector) {
    // Guice doesn't support this, but other DI frameworks do.
    @PostConstruct
    def init(): Unit = {
      Try(injector.instanceOf[ServiceLocator]).foreach { locator =>
        ServiceLocatorHolder(system).setServiceLocator(new ServiceLocatorAdapter {
          override def locateAll(name: String): Future[List[URI]] = {
            import system.dispatcher
            import scala.compat.java8.FutureConverters._
            import scala.collection.JavaConverters._
            locator.locateAll(name).toScala.map(_.asScala.toList)
          }
        })
      }
    }
  }
} 
Example 27
Source File: SecurityModule.scala    From asura   with MIT License 5 votes vote down vote up
package asura.app.modules

import asura.app.api.auth._
import asura.play.actions.SecurityHttpActionAdapter
import com.google.inject.{AbstractModule, Provides}
import org.pac4j.core.client.Clients
import org.pac4j.core.config.Config
import org.pac4j.http.client.direct.{DirectBasicAuthClient, DirectFormClient, HeaderClient}
import org.pac4j.jwt.config.signature.SecretSignatureConfiguration
import org.pac4j.jwt.credentials.authenticator.JwtAuthenticator
import org.pac4j.play.LogoutController
import org.pac4j.play.scala.{DefaultSecurityComponents, SecurityComponents}
import org.pac4j.play.store.{PlayCacheSessionStore, PlaySessionStore}
import play.api.{Configuration, Environment}

class SecurityModule(environment: Environment, configuration: Configuration) extends AbstractModule {

  override def configure(): Unit = {
    bind(classOf[PlaySessionStore]).to(classOf[PlayCacheSessionStore])
    // logout
    val logoutController = new LogoutController()
    logoutController.setDestroySession(true)
    logoutController.setLocalLogout(true)
    logoutController.setDefaultUrl("/")
    bind(classOf[LogoutController]).toInstance(logoutController)
    // security components used in controllers
    bind(classOf[SecurityComponents]).to(classOf[DefaultSecurityComponents])
  }

  @Provides
  def directFormClient: DirectFormClient = {
    val client = if (configuration.getOptional[Boolean]("asura.ldap.enabled").getOrElse(false)) {
      new DirectFormClient(LdapAuthenticator(configuration))
    } else {
      new DirectFormClient(new SimpleTestUsernamePasswordAuthenticator(configuration))
    }
    // client.addAuthorizationGenerator(new RoleAdminAuthGenerator(configuration.get[Seq[String]]("asura.admin")))
    client
  }

  @Provides
  def directBasicAuthClient: DirectBasicAuthClient = {
    val client = if (configuration.getOptional[Boolean]("asura.ldap.enabled").getOrElse(false)) {
      new DirectBasicAuthClient(LdapAuthenticator(configuration))
    } else {
      new DirectBasicAuthClient(new SimpleTestUsernamePasswordAuthenticator(configuration))
    }
    // client.addAuthorizationGenerator(new RoleAdminAuthGenerator(configuration.get[Seq[String]]("asura.admin")))
    client
  }

  @Provides
  def headerClient: HeaderClient = {
    val jwtAuthenticator = new JwtAuthenticator()
    jwtAuthenticator.addSignatureConfiguration(new SecretSignatureConfiguration(configuration.get[String]("asura.jwt.secret")))
    val client = new HeaderClient("Authorization", "Bearer ", jwtAuthenticator)
    // client.addAuthorizationGenerator(new RoleAdminAuthGenerator(configuration.get[Seq[String]]("asura.admin")))
    client
  }

  @Provides
  def provideConfig(directFormClient: DirectFormClient, headerClient: HeaderClient, directBasicAuthClient: DirectBasicAuthClient): Config = {
    val clients = new Clients(directFormClient, headerClient, directBasicAuthClient)
    val config = new Config(clients)
    config.setHttpActionAdapter(new SecurityHttpActionAdapter())
    // config.addAuthorizer(Authorizer.ADMIN, new RequireAnyRoleAuthorizer(Role.ADMIN))
    config
  }
} 
Example 28
Source File: Env.scala    From izanami   with Apache License 2.0 5 votes vote down vote up
package env

import akka.actor.ActorSystem
import com.codahale.metrics.MetricRegistry
import controllers.AssetsFinder
import libs.logs.IzanamiLogger
import play.api.libs.ws.WSClient
import play.api.{Environment, Mode}
import cats._
import cats.implicits._

import scala.util.Random

object ModeEq {
  implicit val eqMode: Eq[Mode] = Eq.fromUniversalEquals
}

case class Env(
    izanamiConfig: IzanamiConfig,
    environment: Environment,
//    actorSystem: ActorSystem,
    assetsFinder: AssetsFinder
) {

  import ModeEq._

  val env: Mode = IzanamiConfig.mode(izanamiConfig, environment.mode)

  def isPlayDevMode = environment.mode === Mode.Dev

  IzanamiLogger.info(s"Starting izanami with $env mode")
//  val sharedKey: String = izanamiConfig.claim.sharedKey

  def hash = Random.nextInt(100000)

  def getFile(path: String) = environment.getFile(path)

  val cookieName: String = Option(izanamiConfig.filter)
    .collect { case Default(config) => config.cookieClaim }
    .getOrElse("Izanami")

  val contextPath: String = if (izanamiConfig.contextPath.endsWith("/")) {
    izanamiConfig.contextPath.dropRight(1)
  } else {
    izanamiConfig.contextPath
  }
  val baseURL: String = if (izanamiConfig.baseURL.endsWith("/")) {
    izanamiConfig.baseURL.dropRight(1)
  } else {
    izanamiConfig.baseURL
  }
} 
Example 29
Source File: Config.scala    From sundial   with MIT License 5 votes vote down vote up
package config

import javax.inject.Inject
import com.google.inject.{AbstractModule, Provides, Singleton}
import dao.SundialDaoFactory
import dto.DisplayModels
import org.lyranthe.prometheus.client.{DefaultRegistry, Registry, jmx}
import play.api.libs.ws.WSClient
import play.api.{Configuration, Environment, Logging}
import service._
import service.notifications.{
  DevelopmentEmailNotifications,
  EmailNotifications,
  Notification,
  PagerdutyNotifications
}
import software.amazon.awssdk.services.batch.BatchClient
import software.amazon.awssdk.services.cloudformation.CloudFormationClient
import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient
import software.amazon.awssdk.services.ec2.Ec2Client
import software.amazon.awssdk.services.emr.EmrClient
import software.amazon.awssdk.services.s3.S3Client
import software.amazon.awssdk.services.ses.SesClient

@Singleton
class PrometheusJmxInstrumentation @Inject()(implicit val registry: Registry) {
  jmx.register
}

class Config(environment: Environment, configuration: Configuration)
    extends AbstractModule
    with Logging {

  override def configure(): Unit = {

    logger.info(s" *** Starting Sundial *** ")

    logger.info("Env Variables:")
    sys.env.foreach {
      case (key, value) => logger.info(s"Key($key), Value($value)")
    }

    logger.info("Sundial Configuration:")
    configuration.entrySet.foreach { entry =>
      logger.info(s"Key(${entry._1}), Value[${entry._2.toString}]")
    }

    bind(classOf[Registry]).toInstance(DefaultRegistry())

    // AWS Clients
    bind(classOf[BatchClient]).toInstance(BatchClient.create())
    bind(classOf[S3Client]).toInstance(S3Client.create())
    bind(classOf[CloudWatchLogsClient])
      .toInstance(CloudWatchLogsClient.create())
    bind(classOf[Ec2Client]).toInstance(Ec2Client.create())
    bind(classOf[EmrClient]).toInstance(EmrClient.create())
    bind(classOf[CloudFormationClient])
      .toInstance(CloudFormationClient.create())
    bind(classOf[SesClient])
      .toInstance(SesClient.create())

    bind(classOf[PrometheusJmxInstrumentation]).asEagerSingleton()

    bind(classOf[Sundial]).asEagerSingleton()

  }

  @Provides
  @Singleton
  def notifications(wsClient: WSClient,
                    daoFactory: SundialDaoFactory,
                    displayModels: DisplayModels,
                    sesClient: SesClient): Seq[Notification] = {
    configuration.getOptional[String]("notifications.mode") match {
      case Some("browser") =>
        Seq(
          new DevelopmentEmailNotifications(daoFactory,
                                            displayModels,
                                            sesClient))
      case Some("email") =>
        Seq(
          new EmailNotifications(
            daoFactory,
            configuration.get[String]("notifications.from"),
            displayModels,
            sesClient))
      case Some("all") =>
        Seq(
          new EmailNotifications(
            daoFactory,
            configuration.get[String]("notifications.from"),
            displayModels,
            sesClient),
          new PagerdutyNotifications(wsClient, daoFactory)
        )
      case _ => Seq.empty
    }
  }

} 
Example 30
Source File: DevelopmentConfig.scala    From sundial   with MIT License 5 votes vote down vote up
package config

import javax.inject.Named

import com.google.inject.{AbstractModule, Provides, Singleton}
import play.api.{Configuration, Environment}

class DevelopmentConfig(environment: Environment, configuration: Configuration)
    extends AbstractModule {

  override def configure() = {}

  @Provides
  @Named("cfnStackName")
  @Singleton
  def cfnStackName: String = "dumm-stack-name"

  @Provides
  @Named("s3Bucket")
  @Singleton
  def s3Bucket: String = configuration.get[String]("s3.bucket")

  @Provides
  @Named("sdbDomain")
  @Singleton
  def sdbDomain: String = "dummy-sdb-domain"

  @Provides
  @Named("sundialUrl")
  @Singleton
  def sundialUrl: String = "http://localhost:9000"

} 
Example 31
Source File: SpringInjector.scala    From play-spring-loader   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.play.spring

import org.springframework.beans.BeanInstantiationException
import org.springframework.beans.factory.config.{ AutowireCapableBeanFactory, BeanDefinition }
import org.springframework.beans.factory.{ BeanCreationException, NoSuchBeanDefinitionException }
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
import org.springframework.beans.factory.support.{ GenericBeanDefinition, DefaultListableBeanFactory }
import play.api.inject.{ BindingKey, Injector, Modules, Module }
import play.api.{ PlayException, Configuration, Environment }

import scala.reflect.ClassTag

class SpringInjector(factory: DefaultListableBeanFactory) extends Injector {

  private val bpp = new AutowiredAnnotationBeanPostProcessor()
  bpp.setBeanFactory(factory)

  def instanceOf[T](implicit ct: ClassTag[T]) = instanceOf(ct.runtimeClass).asInstanceOf[T]

  def instanceOf[T](clazz: Class[T]) = {
    getBean(clazz)
  }

  def getBean[T](clazz: Class[T]): T = {
    try {
      factory.getBean(clazz)
    } catch {

      case e: NoSuchBeanDefinitionException =>
        // if the class is a concrete type, attempt to create a just in time binding
        if (!clazz.isInterface 
  def springable(module: Any): Module = module match {
    case playModule: Module => playModule
    //    case bin
    case unknown => throw new PlayException(
      "Unknown module type",
      s"Module [$unknown] is not a Play module")
  }
} 
Example 32
Source File: Filters.scala    From theGardener   with Apache License 2.0 5 votes vote down vote up
package filters

import akka.stream.Materializer
import javax.inject.Inject
import play.api.http.HttpFilters
import play.api.mvc.{EssentialFilter, RequestHeader, Result}
import play.api.{Environment, Mode}
import play.filters.cors.CORSFilter
import play.filters.gzip.GzipFilter

class Filters @Inject()(environment: Environment, corsFilter: CORSFilter)(implicit mat: Materializer) extends HttpFilters {

  
  private def shouldGzip = (requestHeader: RequestHeader, response: Result) => {
    val responseIsJavascript = response.body.contentType.exists(_.startsWith("application/javascript"))
    val requestPathShouldBeGzipped = requestHeader.path.contains("/api/")
    responseIsJavascript || requestPathShouldBeGzipped
  }

  private val gzipFilter = new GzipFilter(shouldGzip = shouldGzip)

  override val filters: Seq[EssentialFilter] = environment.mode match {
    case Mode.Dev =>
      // CORSFilter only for DEV mode: allow Angular app to call API on different port
      Seq(gzipFilter, corsFilter)
    case _ =>
      Seq(gzipFilter)
  }

} 
Example 33
Source File: ScalinguaPlugin.scala    From scalingua   with Apache License 2.0 5 votes vote down vote up
package ru.makkarpov.scalingua.play

import javax.inject.Inject

import play.api.{Application, BuiltInComponentsFromContext, Configuration, Environment}
import play.api.inject.{Binding, Module}
import ru.makkarpov.scalingua.Messages

trait ScalinguaComponents {
  def configuration: Configuration
  def environment: Environment

  lazy val messages = new MessagesProvider(new ScalinguaConfigProvider(configuration).get(), environment).get()
}

class ScalinguaModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = Seq(
    bind[ScalinguaConfig].toProvider[ScalinguaConfigProvider],
    bind[Messages].toProvider[MessagesProvider]
  )
} 
Example 34
Source File: WorkspaceController.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.my

import com.mohiva.play.silhouette.api.Silhouette
import controllers.{BaseController, Security, HasPrettyPrintJSON}
import javax.inject.{Inject, Singleton}
import services.contribution.{Contribution, ContributionService}
import services.user.{User, UserService}
import org.webjars.play.WebJarsUtil
import play.api.{Configuration, Environment}
import play.api.i18n.I18nSupport
import play.api.libs.json.Json
import play.api.mvc.{ControllerComponents, RequestHeader}
import services.document.DocumentService
import scala.concurrent.{ExecutionContext, Future}

@Singleton
class WorkspaceController @Inject() (
  val components: ControllerComponents,
  val contributions: ContributionService,
  val users: UserService,
  val config: Configuration,
  val silhouette: Silhouette[Security.Env],
  implicit val documents: DocumentService,
  implicit val ctx: ExecutionContext,
  implicit val env: Environment,
  implicit val webjars: WebJarsUtil
) extends BaseController(components, config, users) with I18nSupport with HasPrettyPrintJSON {

  
  def workspace(usernameInPath: String) = silhouette.UserAwareAction.async { implicit request =>    
    // If the user is logged in & the name in the path == username it's the profile owner
    val isProfileOwner = request.identity match {
      case Some(userWithRoles) => userWithRoles.username.equalsIgnoreCase(usernameInPath)
      case None => false
    }
    
    if (isProfileOwner)
      Future.successful(Ok(views.html.my.workspace()))
    else
      renderPublicProfile(usernameInPath, request.identity)
  }

  def activityFeed(usernameInPath: String) = silhouette.UserAwareAction.async { implicit request =>
    val loggedInAs = request.identity.map(_.username)
    contributions.getUserActivityFeed(Seq(usernameInPath), loggedInAs).map { response => 
      jsonOk(Json.toJson(response))
    } 
  }
  
} 
Example 35
Source File: MaintenanceController.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.admin.maintenance

import com.mohiva.play.silhouette.api.Silhouette
import controllers.{BaseAuthController, Security, HasPrettyPrintJSON}
import java.io.File
import javax.inject.{Inject, Singleton}
import org.joda.time.DateTime
import org.webjars.play.WebJarsUtil
import play.api.{Configuration, Environment}
import play.api.mvc.ControllerComponents
import play.api.libs.json._
import play.api.libs.functional.syntax._
import scala.concurrent.ExecutionContext
import services.announcement.AnnouncementService
import services.document.DocumentService
import services.generated.tables.records.UploadRecord
import services.upload.UploadService
import services.user.UserService
import services.user.Roles._
import services.HasDate
import storage.es.ES
import storage.uploads.Uploads

@Singleton
class MaintenanceController @Inject()(
  val announcements: AnnouncementService,
  val components: ControllerComponents, 
  val config: Configuration,
  val documents: DocumentService,
  val env: Environment,
  val es: ES,
  val silhouette: Silhouette[Security.Env],
  val uploadService: UploadService,
  val uploadStorage: Uploads,
  val users: UserService,
  implicit val ctx: ExecutionContext,
  implicit val webJarsUtil: WebJarsUtil
) extends BaseAuthController(components, config, documents, users) with HasPrettyPrintJSON with HasDate {

  implicit val uploadRecordWrites: Writes[UploadRecord] = (
    (JsPath \ "owner").write[String] and
    (JsPath \ "title").write[String] and
    (JsPath \ "created_at").write[DateTime]
  )(upload => (
    upload.getOwner,
    upload.getTitle,
    new DateTime(upload.getCreatedAt)
  ))
  
  def index = silhouette.SecuredAction(Security.WithRole(Admin)).async { implicit request =>
    uploadService.listPendingUploads().map { uploads =>
      Ok(views.html.admin.maintenance())
    }
  }

  
  def insertBroadcast = silhouette.SecuredAction(Security.WithRole(Admin)).async { implicit request =>
    announcements.insertBroadcastAnnouncement(
    """# Like Recogito? Vote for us!

We are excited that Recogito has been nominated for the [Digital Humanities Awards](http://dhawards.org/dhawards2018/voting/) this year. 
If you like Recogito, do consider voting for us.

Many thanks & happy annotating!
    """).map(_ => Ok)
  }
  
  def deleteAllServiceAnnouncements = silhouette.SecuredAction(Security.WithRole(Admin)).async { implicit request =>
    announcements.clearAll().map { success =>
      if (success) Ok
      else InternalServerError
    }
  }
  
} 
Example 36
Source File: HelpController.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.help

import controllers.HasVisitLogging
import javax.inject.{Inject, Singleton}
import services.visit.VisitService
import org.webjars.play.WebJarsUtil
import play.api.{Configuration, Environment}
import play.api.mvc.{Action, AbstractController, ControllerComponents, RequestHeader}
import play.twirl.api.HtmlFormat
import scala.concurrent.ExecutionContext
import scala.io.Source
import scala.util.Try
import services.entity.{AuthorityFileService, EntityType}

@Singleton
class HelpController @Inject() (
  val authorities: AuthorityFileService,
  val components: ControllerComponents,
  val config: Configuration,
  val env: Environment,
  implicit val ctx: ExecutionContext,
  implicit val visits: VisitService,
  implicit val webjars: WebJarsUtil
) extends AbstractController(components) with HasVisitLogging {

  private val adminEmail = config.get[String]("admin.email")
  private val imprint =
    Try(Source.fromFile(env.getFile("conf/imprint"))).toOption.map { _.getLines.mkString("\n") }

  private def result(template: HtmlFormat.Appendable)(implicit request: RequestHeader) = {
    logPageView()
    Ok(template)
  }

  def localizedTutorial(lang: String) = Action { implicit request =>
    lang.toUpperCase match {
      case "DE" => result(views.html.help.tutorial.tutorial_de())
      case "ES" => result(views.html.help.tutorial.tutorial_es())
      case "FA" => result(views.html.help.tutorial.tutorial_fa())
      case "FR" => result(views.html.help.tutorial.tutorial_fr())
      case "IT" => result(views.html.help.tutorial.tutorial_it())
      case "NL" => result(views.html.help.tutorial.tutorial_nl())
      case "TR" => result(views.html.help.tutorial.tutorial_tr())
      case _ => NotFound(views.html.error404())
    }
  }

  def faq = Action.async { implicit request => 
    authorities.listAll(Some(EntityType.PLACE)).map { gazetteers =>
      result(views.html.help.faq(gazetteers)) 
    }
  }

  def index = Action { implicit request => result(views.html.help.index()) }

  def about        = Action { implicit request => result(views.html.help.general.about(imprint, adminEmail)) }
  def privacy      = Action { implicit request => result(views.html.help.general.privacy(adminEmail)) }
  def relations    = Action { implicit request => result(views.html.help.relations()) }
  def cloning      = Action { implicit request => result(views.html.help.cloning()) }
  def sharingLinks = Action { implicit request => result(views.html.help.sharing_links()) }
  def terms        = Action { implicit request => result(views.html.help.general.terms()) }
  def tutorial     = Action { implicit request => result(views.html.help.tutorial.tutorial()) }
  def workspace    = Action { implicit request => result(views.html.help.workspace()) }

  def swaggerUi = Action {
    Redirect(url = "/webjars/swagger-ui/2.2.0/index.html", queryString = Map("url" -> Seq("/swagger.json")))
  }

} 
Example 37
Source File: ErrorHandler.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
import javax.inject.{ Inject, Provider }
import play.api.{ Configuration, Environment, Logger, OptionalSourceMapper, UsefulException }
import play.api.http.DefaultHttpErrorHandler
import play.api.mvc.RequestHeader
import play.api.mvc.Results._
import play.api.routing.Router
import scala.concurrent.Future

class ErrorHandler @Inject() (
    env: Environment,
    config: Configuration,
    sourceMapper: OptionalSourceMapper,
    router: Provider[Router]
  ) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {

  override def onProdServerError(request: RequestHeader, exception: UsefulException) =
    Future.successful(InternalServerError(s"An error occurred: ${exception.getMessage}"))

  override def onClientError(request: RequestHeader, statusCode: Int, message: String) = {
    if (statusCode == 413) // Request entity too large
      Future.successful(EntityTooLarge("Could not upload the file - too large"))
    else if (statusCode == 404) // Not Found
      Future.successful(NotFound(views.html.error404()))
    else
      super.onClientError(request, statusCode, message)
  }

} 
Example 38
Source File: PrometheusModule.scala    From play-prometheus-filters   with MIT License 5 votes vote down vote up
package com.github.stijndehaes.playprometheusfilters

import io.prometheus.client.CollectorRegistry
import io.prometheus.client.hotspot._
import org.slf4j.LoggerFactory
import play.api.inject.{Binding, Module}
import play.api.{Configuration, Environment}

object PrometheusModule {
  val defaultExportsKey = "play-prometheus-filters.register-default-hotspot-collectors"
}

class PrometheusModule extends Module {
  import PrometheusModule._

  private val logger = LoggerFactory.getLogger(classOf[PrometheusModule])

  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = {
    CollectorRegistry.defaultRegistry.clear()

    configuration.getOptional[Boolean](defaultExportsKey).foreach { enabled =>
      if (enabled) {
        logger.info("Default exports are enabled")
        DefaultExports.initialize()
        logger.info("Default exports registered")
      } else {
        logger.info("Default exports are disabled")
      }
    }

    Seq(
      bind[CollectorRegistry].to(CollectorRegistry.defaultRegistry)
    )
  }
} 
Example 39
Source File: MockServices.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.scaladsl.server.mocks

import java.util.concurrent.atomic.AtomicInteger

import akka.NotUsed
import akka.stream.scaladsl.Source
import com.lightbend.lagom.scaladsl.api.Service.pathCall
import com.lightbend.lagom.scaladsl.api.Service.named
import com.lightbend.lagom.scaladsl.api.Service.restCall
import com.lightbend.lagom.scaladsl.api.Descriptor
import com.lightbend.lagom.scaladsl.api.Service
import com.lightbend.lagom.scaladsl.api.ServiceCall
import com.lightbend.lagom.scaladsl.api.deser.DefaultExceptionSerializer
import com.lightbend.lagom.scaladsl.api.transport.Method
import play.api.Environment
import play.api.Mode

object PathProvider {
  val PATH = "/some-path"
}


trait SimpleStreamedService extends Service {
  override def descriptor: Descriptor =
    named("simple-streamed")
      .withCalls(pathCall(PathProvider.PATH, streamed _))
      .withExceptionSerializer(new DefaultExceptionSerializer(Environment.simple(mode = Mode.Dev)))

  def streamed(): ServiceCall[Source[String, NotUsed], Source[String, NotUsed]]
} 
Example 40
Source File: BasicSecurityModule.scala    From asura   with MIT License 5 votes vote down vote up
package asura.play.module

import com.google.inject.AbstractModule
import org.pac4j.play.LogoutController
import org.pac4j.play.scala.{DefaultSecurityComponents, SecurityComponents}
import org.pac4j.play.store.{PlayCacheSessionStore, PlaySessionStore}
import play.api.{Configuration, Environment}

class BasicSecurityModule(environment: Environment, configuration: Configuration) extends AbstractModule {
  override def configure(): Unit = {
    bind(classOf[PlaySessionStore]).to(classOf[PlayCacheSessionStore])
    // logout
    val logoutController = new LogoutController()
    logoutController.setDestroySession(true)
    logoutController.setLocalLogout(true)
    logoutController.setDefaultUrl("/")
    bind(classOf[LogoutController]).toInstance(logoutController)
    // security components used in controllers
    bind(classOf[SecurityComponents]).to(classOf[DefaultSecurityComponents])
  }
} 
Example 41
Source File: Module.scala    From elastiknn   with Apache License 2.0 5 votes vote down vote up
import java.util.concurrent.{ExecutorService, Executors, ThreadFactory}

import com.google.common.util.concurrent.ThreadFactoryBuilder
import com.google.inject.{AbstractModule, TypeLiteral}
import com.klibisz.elastiknn.client.{ElastiknnClient, ElastiknnFutureClient}
import javax.inject.Provider
import play.api.{Configuration, Environment}

import scala.concurrent.ExecutionContext

class Module(environment: Environment, configuration: Configuration) extends AbstractModule {

  val eknnProvider = new Provider[ElastiknnFutureClient] {
    override def get(): ElastiknnFutureClient = {
      val tfac: ThreadFactory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("elastiknn-%d").build()
      val exec: ExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime.availableProcessors(), tfac)
      implicit val ec: ExecutionContext = ExecutionContext.fromExecutor(exec)
      val host = configuration.underlying.getString("elastiknn.elasticsearch.host")
      val port = configuration.underlying.getInt("elastiknn.elasticsearch.port")
      ElastiknnClient.futureClient(host, port)
    }
  }

  override def configure(): Unit = {
    // Weird that you have to use this constructor, but it works.
    bind(new TypeLiteral[ElastiknnFutureClient]() {}).toProvider(eknnProvider)
  }
} 
Example 42
Source File: PlayJavaModuleSpec.scala    From play-grpc   with Apache License 2.0 5 votes vote down vote up
package play.grpc

import java.io.File

import example.myapp.helloworld.grpc.GreeterServiceClient
import example.myapp.helloworld.grpc.GreeterServiceClientProvider
import play.api.inject.ProviderConstructionTarget
import play.api.Configuration
import play.api.Environment
import play.api.Mode
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

class PlayJavaModuleSpec extends AnyWordSpec with Matchers {

  "The generated module" should {

    "provide all clients" in {
      // module in longest common package for the two services
      val module = new example.myapp.helloworld.grpc.AkkaGrpcClientModule()

      val bindings =
        module.bindings(Environment(new File("./"), getClass.getClassLoader, Mode.Prod), Configuration.empty)

      // both clients should be in there
      bindings should have size (1)

      bindings.map(_.key.clazz).toSet should ===(Set(classOf[GreeterServiceClient]))

      // not super useful assertions but let's keep for good measure
      bindings.map(_.target.get.asInstanceOf[ProviderConstructionTarget[_]].provider).toSet should ===(
        Set(classOf[GreeterServiceClientProvider]),
      )
    }

  }

} 
Example 43
Source File: PlayScalaModuleSpec.scala    From play-grpc   with Apache License 2.0 5 votes vote down vote up
package play.grpc

import java.io.File

import example.myapp.helloworld.grpc.helloworld.GreeterServiceClient
import example.myapp.helloworld.grpc.helloworld.GreeterServiceClientProvider
import play.api.inject.ProviderConstructionTarget
import play.api.Configuration
import play.api.Environment
import play.api.Mode
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

class PlayScalaModuleSpec extends AnyWordSpec with Matchers {

  "The generated module" should {

    "provide all clients" in {
      // module in longest common package for the two services
      val module = new example.myapp.helloworld.grpc.helloworld.AkkaGrpcClientModule()

      val bindings =
        module.bindings(Environment(new File("./"), getClass.getClassLoader, Mode.Prod), Configuration.empty)

      // both clients should be in there
      bindings should have size (1)

      bindings.map(_.key.clazz).toSet should ===(Set(classOf[GreeterServiceClient]))

      // not super useful assertions but let's keep for good measure
      bindings.map(_.target.get.asInstanceOf[ProviderConstructionTarget[_]].provider).toSet should ===(
        Set(classOf[GreeterServiceClientProvider]),
      )
    }

  }

} 
Example 44
Source File: ApplicationController.scala    From monix-sample   with Apache License 2.0 5 votes vote down vote up
package controllers

import akka.actor.ActorSystem
import akka.stream.Materializer
import engine.{BackPressuredWebSocketActor, DataProducer, SimpleWebSocketActor}
import monix.execution.Scheduler.Implicits.global
import play.api.Environment
import play.api.libs.json.JsValue
import play.api.libs.streams.ActorFlow
import play.api.mvc._
import scala.concurrent.duration._

class ApplicationController()
  (implicit env: Environment, as: ActorSystem, m: Materializer)
  extends Controller with JSONFormats {

  def index = Action {
    Ok(views.html.index(env))
  }

  def backPressuredStream(periodMillis: Int, seed: Long) =
    WebSocket.accept[JsValue, JsValue] { request =>
      val obs = new DataProducer(periodMillis.millis, seed)
      ActorFlow.actorRef(out => BackPressuredWebSocketActor.props(obs, out))
    }

  def simpleStream(periodMillis: Int, seed: Long) =
    WebSocket.accept[JsValue, JsValue] { request =>
      val obs = new DataProducer(periodMillis.millis, seed)
      ActorFlow.actorRef(out => SimpleWebSocketActor.props(obs, out))
    }
} 
Example 45
Source File: TLSFilter.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.utils

import akka.stream.Materializer
import javax.inject.Inject
import play.api.Environment
import play.api.mvc._

import scala.concurrent.{ ExecutionContext, Future }

class TLSFilter @Inject() (
    implicit
    val mat: Materializer, ec: ExecutionContext, env: Environment) extends Filter {
  def apply(nextFilter: RequestHeader => Future[Result])(requestHeader: RequestHeader): Future[Result] = {
    if (requestHeader.headers.get("X-Forwarded-Proto").getOrElse("http") != "https" && env.mode == play.api.Mode.Prod) {
      if (requestHeader.method == "GET") {
        Future.successful(Results.MovedPermanently("https://" + requestHeader.host + requestHeader.uri))
      }
      else {
        Future.successful(Results.BadRequest("This service requires strict transport security"))
      }
    }
    else {
      nextFilter(requestHeader).map(_.withHeaders("Strict-Transport-Security" -> "max-age=31536000"))
    }
  }
} 
Example 46
Source File: HatServerProviderModule.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.modules

import akka.actor.ActorSystem
import com.google.inject.{ AbstractModule, Provides }
import net.codingwell.scalaguice.ScalaModule
import org.hatdex.hat.api.service.RemoteExecutionContext
import org.hatdex.hat.api.service.applications.{ TrustedApplicationProvider, TrustedApplicationProviderDex }
import org.hatdex.hat.resourceManagement._
import org.hatdex.hat.resourceManagement.actors.{ HatServerActor, HatServerProviderActor }
import play.api.cache.AsyncCacheApi
import play.api.cache.ehcache._
import play.api.inject.ApplicationLifecycle
import play.api.libs.concurrent.AkkaGuiceSupport
import play.api.{ Configuration, Environment }

class HatServerProviderModule extends AbstractModule with ScalaModule with AkkaGuiceSupport {

  override def configure() = {
    bindActor[HatServerProviderActor]("hatServerProviderActor")
    bindActorFactory[HatServerActor, HatServerActor.Factory]

    bind[HatDatabaseProvider].to[HatDatabaseProviderMilliner]
    bind[HatKeyProvider].to[HatKeyProviderMilliner]
    bind[HatServerProvider].to[HatServerProviderImpl]

    bind[TrustedApplicationProvider].to[TrustedApplicationProviderDex]
    ()
  }

  @Provides @play.cache.NamedCache("hatserver-cache")
  def provideHatServerCache(env: Environment, config: Configuration, lifecycle: ApplicationLifecycle, system: ActorSystem)(implicit ec: RemoteExecutionContext): AsyncCacheApi = {
    val cacheComponents = new EhCacheComponents {
      def environment: Environment = env
      def configuration: Configuration = config.get[Configuration]("hat.serverProvider")
      def applicationLifecycle: ApplicationLifecycle = lifecycle
      def actorSystem: ActorSystem = system
      implicit def executionContext = ec
    }
    cacheComponents.cacheApi("hatserver-cache", create = true)
  }

} 
Example 47
Source File: HatTestServerProviderModule.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.modules

import akka.actor.ActorSystem
import com.google.inject.{ AbstractModule, Provides }
import net.codingwell.scalaguice.ScalaModule
import org.hatdex.hat.api.service.RemoteExecutionContext
import org.hatdex.hat.api.service.applications.{ TrustedApplicationProvider, TrustedApplicationProviderDex }
import org.hatdex.hat.resourceManagement._
import org.hatdex.hat.resourceManagement.actors.{ HatServerActor, HatServerProviderActor }
import play.api.cache.AsyncCacheApi
import play.api.cache.ehcache.EhCacheComponents
import play.api.inject.ApplicationLifecycle
import play.api.libs.concurrent.AkkaGuiceSupport
import play.api.{ Configuration, Environment }

class HatTestServerProviderModule extends AbstractModule with ScalaModule with AkkaGuiceSupport {

  override def configure() = {
    bindActor[HatServerProviderActor]("hatServerProviderActor")
    bindActorFactory[HatServerActor, HatServerActor.Factory]

    bind[HatDatabaseProvider].to[HatDatabaseProviderConfig]
    bind[HatKeyProvider].to[HatKeyProviderConfig]
    bind[HatServerProvider].to[HatServerProviderImpl]

    bind[TrustedApplicationProvider].to[TrustedApplicationProviderDex]
    ()
  }

  @Provides @play.cache.NamedCache("hatserver-cache")
  def provideHatServerCache(env: Environment, config: Configuration, lifecycle: ApplicationLifecycle, system: ActorSystem)(implicit ec: RemoteExecutionContext): AsyncCacheApi = {
    val cacheComponents = new EhCacheComponents {
      def environment: Environment = env
      def configuration: Configuration = config.get[Configuration]("hat.serverProvider")
      def applicationLifecycle: ApplicationLifecycle = lifecycle
      def actorSystem: ActorSystem = system
      implicit def executionContext = ec
    }
    cacheComponents.cacheApi("hatserver-cache", create = true)
  }

} 
Example 48
Source File: OnlyHttpsFilter.scala    From get-you-a-license   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package filters

import akka.stream.Materializer
import play.api.{Environment, Mode}
import play.api.http.HeaderNames
import play.api.mvc.{Filter, RequestHeader, Result, Results}

import scala.concurrent.{ExecutionContext, Future}

class OnlyHttpsFilter(environment: Environment)(implicit val mat: Materializer, ec: ExecutionContext) extends Filter {
  def apply(nextFilter: (RequestHeader) => Future[Result])(requestHeader: RequestHeader): Future[Result] = {
    nextFilter(requestHeader).map { result =>
      if (requestHeader.secure || environment.mode == Mode.Dev) {
        result
      }
      else {
        Results.MovedPermanently("https://" + requestHeader.host + requestHeader.uri)
      }
    }
  }
} 
Example 49
Source File: HoconMessagesApi.scala    From play-i18n-hocon   with Apache License 2.0 5 votes vote down vote up
package com.marcospereira.play.i18n

import java.net.URL
import java.util.Properties
import javax.inject.{ Inject, Singleton }

import com.typesafe.config.ConfigFactory
import play.api.http.HttpConfiguration
import play.api.i18n._
import play.api.inject.Module
import play.api.{ Configuration, Environment }
import play.utils.Resources

import scala.collection.JavaConverters._

@Singleton
class HoconMessagesApiProvider @Inject() (
  environment: Environment,
  config: Configuration,
  langs: Langs,
  httpConfiguration: HttpConfiguration
)
    extends DefaultMessagesApiProvider(environment, config, langs, httpConfiguration) {

  override lazy val get: MessagesApi = {
    new DefaultMessagesApi(
      loadAllMessages,
      langs,
      langCookieName = langCookieName,
      langCookieSecure = langCookieSecure,
      langCookieHttpOnly = langCookieHttpOnly,
      httpConfiguration = httpConfiguration
    )
  }

  override protected def loadMessages(file: String): Map[String, String] = {
    getResources(file)
      .filterNot(url => Resources.isDirectory(environment.classLoader, url)).reverse
      .map(getMessages)
      .foldLeft(Map.empty[String, String]) { _ ++ _ }
  }

  override protected def loadAllMessages: Map[String, Map[String, String]] = {
    langs.availables.map(_.code).map { lang =>
      (lang, loadMessages(s"messages.$lang.conf"))
    }.toMap ++ Map(
      "default" -> loadMessages("messages.conf"),
      "default.play" -> loadMessages("messages.default")
    )
  }

  override protected def joinPaths(first: Option[String], second: String) = first match {
    case Some(parent) => new java.io.File(parent, second).getPath
    case None => second
  }

  private def getResources(file: String): List[URL] = {
    environment.classLoader.getResources(joinPaths(messagesPrefix, file)).asScala.toList
  }

  private def getMessages(url: URL): Map[String, String] = {
    // messages.default is bundled with play and it is a properties file
    val config = if (url.toString.endsWith("messages.default")) {
      ConfigFactory.parseProperties(getProperties(url))
    } else {
      ConfigFactory.parseURL(url)
    }

    config.resolve().entrySet().asScala
      .map(e => e.getKey -> String.valueOf(e.getValue.unwrapped()))
      .toMap
  }

  private def getProperties(url: URL): Properties = {
    val properties = new Properties()
    val input = url.openStream()
    try {
      properties.load(input)
    } finally {
      input.close()
    }
    properties
  }
}


trait HoconI18nComponents extends I18nComponents {

  def environment: Environment
  def configuration: Configuration
  def httpConfiguration: HttpConfiguration
  def langs: Langs

  override lazy val messagesApi: MessagesApi = new HoconMessagesApiProvider(environment, configuration, langs, httpConfiguration).get
} 
Example 50
Source File: Application.scala    From ProductWebUI   with Apache License 2.0 5 votes vote down vote up
package controllers

import java.nio.ByteBuffer

import boopickle.Default._
import com.google.inject.Inject
import play.api.mvc._
import play.api.{Configuration, Environment}
import play.api.Environment._
import services.ApiService
import shared.Api

import scala.concurrent.ExecutionContext.Implicits.global

object Router extends autowire.Server[ByteBuffer, Pickler, Pickler] {
  override def read[R: Pickler](p: ByteBuffer) = Unpickle[R].fromBytes(p)

  override def write[R: Pickler](r: R) = Pickle.intoBytes(r)
}

class Application @Inject()(implicit val config: Configuration, env: Environment) extends Controller {
  val apiService = new ApiService()

  def index = Action {

    Ok(views.html.index("LivelyGig"))
    //    Ok(views.html.index("Welcome to Synereo - the decentralized and distributed social network"))
  }

  def logging = Action(parse.anyContent) {
    implicit request =>
      request.body.asJson.foreach { msg =>
        println(s"Application - CLIENT - $msg")
      }
      Ok("")
  }

  def autowireApi(path: String) = Action.async(parse.raw) {
    implicit request =>
      println(s"Request path: $path")

      // get the request body as ByteString
      val b = request.body.asBytes(parse.UNLIMITED).get

      // call Autowire route
      Router.route[Api](apiService)(
        autowire.Core.Request(path.split("/"), Unpickle[Map[String, ByteBuffer]].fromBytes(b.asByteBuffer))
      ).map(buffer => {
        val data = Array.ofDim[Byte](buffer.remaining())
        buffer.get(data)
        Ok(data)
      })
  }
} 
Example 51
Source File: PdfGeneratorConnector.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package connectors

import com.google.inject.{ImplementedBy, Inject, Singleton}
import play.api.Mode
import play.api.libs.ws.{WSClient, WSResponse}
import play.api.{Configuration, Environment}
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig

import scala.concurrent.Future

@ImplementedBy(classOf[FrontendPdfGeneratorConnector])
trait PdfGeneratorConnector {
  val serviceURL: String
  def getWsClient: WSClient

  def generatePdf(html: String): Future[WSResponse] =
    getWsClient.url(serviceURL).post(Map("html" -> Seq(html)))
}

@Singleton
class FrontendPdfGeneratorConnector @Inject()(
  environment: Environment,
  runModeConfiguration: Configuration,
  wsClient: WSClient,
  servicesConfig: ServicesConfig)
    extends PdfGeneratorConnector {
  val mode: Mode = environment.mode
  val pdfServiceUrl: String = servicesConfig.baseUrl("pdf-generator-service")
  val serviceURL = pdfServiceUrl + "/pdf-generator-service/generate"

  override def getWsClient: WSClient = wsClient
} 
Example 52
Source File: Application.scala    From checkers   with Apache License 2.0 5 votes vote down vote up
package controllers

import com.google.inject.Inject
import play.api.{Configuration, Environment}
import play.api.mvc._

class Application @Inject()(implicit val config: Configuration, env: Environment) extends Controller {

  def index = Action {
    Ok(views.html.index("Checkers"))
  }

  def benchmarks = Action {
    Ok(views.html.benchmarks("Benchmarks"))
  }

  def logging = Action(parse.anyContent) {
    implicit request =>
      request.body.asJson.foreach { msg =>
        println(s"CLIENT - $msg")
      }
      Ok("")
  }
} 
Example 53
Source File: ParSeqTraceRenderer.scala    From play-parseq   with Apache License 2.0 5 votes vote down vote up
package com.linkedin.playparseq.trace.s.renderers

import com.linkedin.parseq.trace.{ShallowTrace, Trace, TraceRelationship}
import com.linkedin.playparseq.s.stores.ParSeqTaskStore
import com.linkedin.playparseq.trace.utils.ParSeqTraceBaseVisualizer
import javax.inject.{Inject, Singleton}
import play.api.Environment
import play.api.http.HttpConfiguration
import play.api.mvc.{RequestHeader, Result, Results}
import scala.collection.JavaConverters._
import scala.concurrent.{ExecutionContext, Future}



  override def render(parSeqTaskStore: ParSeqTaskStore)(implicit requestHeader: RequestHeader): Future[Result] =
    Future {
      val traces: Set[Trace] = parSeqTaskStore.get.map(_.getTrace)
      val traceMap: Map[java.lang.Long, ShallowTrace] = traces.foldLeft(Map[java.lang.Long, ShallowTrace]())(_ ++ _.getTraceMap.asScala)
      val relationships: Set[TraceRelationship] = traces.foldLeft(Set[TraceRelationship]())(_ ++ _.getRelationships.asScala)
      // Generate Result of ParSeq Trace
      Option(showTrace(new Trace(traceMap.asJava, relationships.asJava), environment, httpConfiguration)).map(Results.Ok(_).as("text/html"))
        .getOrElse(Results.InternalServerError("Can't show Trace."))
    }

} 
Example 54
Source File: ParSeqTraceBaseVisualizer.scala    From play-parseq   with Apache License 2.0 5 votes vote down vote up
package com.linkedin.playparseq.trace.utils

import com.linkedin.parseq.trace.Trace
import com.linkedin.parseq.trace.codec.json.JsonTraceCodec
import java.io.File
import play.api.Environment
import play.api.http.HttpConfiguration
import scala.collection.immutable.ListMap
import scala.io.Source



  protected[this] def showTrace(trace: Trace, environment: Environment, httpConfiguration: HttpConfiguration): String = {
    // Get Trace JSON
    val traceJson = new JsonTraceCodec().encode(trace)
    // Generate pre-fill script for onload Trace JSON
    val preFillScript =
      """
        |<base href="%s">
        |<script>
        |  var ESC_FLAGS = "gi";
        |  var EMBED_ESCAPES = __EMBED_ESCAPES__;
        |  var unescapeForEmbedding = function (str) {
        |    for (var key in EMBED_ESCAPES) {
        |      if (EMBED_ESCAPES.hasOwnProperty(key)) {
        |        str = str.replace(new RegExp(EMBED_ESCAPES[key], ESC_FLAGS), key);
        |      }
        |    }
        |    return str;
        |  };
        |  var getEmbeddedContent = function(id) {
        |    var contentElem = document.getElementById(id);
        |    var innerContent = contentElem.firstChild.nodeValue;
        |    return JSON.parse(unescapeForEmbedding(innerContent));
        |  };
        |  window.onload = function() {
        |    var json = getEmbeddedContent('injected-json');
        |    // The renderTrace method does not yet support normal JS objects, but expects stringified JSON
        |    renderTrace(JSON.stringify(json));
        |  }
        |</script>
      """.stripMargin.format(httpConfiguration.context.stripSuffix("/") + TracevisRoot + "/")
    // Generate injected JSON placeholder
    val injectedJson = """<code id="injected-json"><!--__JSON__--></code>"""
    // Build HTML page
    environment.resourceAsStream(new File(TracevisRoot, TraceName).getPath).map(stream => {
      // Escape script and JSON
      val script = preFillScript.replace("__EMBED_ESCAPES__", """{"&":"&amp;","-":"&dsh;"}""")
      val json = injectedJson.replace("__JSON__", ListMap("&" -> "&amp;", "-" -> "&dsh;").foldLeft(traceJson)((acc, escape) => acc.replaceAll(escape._1, escape._2)))
      // Inject script and JSON
      Source.fromInputStream(stream).mkString.replace("<title>", script + "\n<title>").replace("</style>", "</style>\n" + json)
    }).orNull
  }

} 
Example 55
Source File: AppConfig.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package it.gov.daf.catalogmanager.utilities


private class AppConfig @Inject()(playConfig: Configuration) {
  val userIdHeader: Option[String] = playConfig.getString("app.userid.header")
  val ckanHost: Option[String] = playConfig.getString("app.ckan.url")
  val dbHost: Option[String] = playConfig.getString("mongo.host")
  val dbPort: Option[Int] = playConfig.getInt("mongo.port")
  val userName :Option[String] = playConfig.getString("mongo.username")
  val password :Option[String] = playConfig.getString("mongo.password")
  val database :Option[String] = playConfig.getString("mongo.database")
  val localUrl :Option[String] = playConfig.getString("app.local.url")
  val securityManHost :Option[String] = playConfig.getString("security.manager.host")
  val cookieExpiration :Option[Long] = playConfig.getLong("cookie.expiration")
  val ingestionUrl :Option[String] = playConfig.getString("ingestion.url")
  val kyloUrl: Option[String] = playConfig.getString("kylo.url")
  val kyloUser: Option[String] = playConfig.getString("kylo.user")
  val kyloPwd: Option[String] = playConfig.getString("kylo.pwd")
  val kafkaProxyUrl: Option[String] = playConfig.getString("kafkaProxy.url")

}



object ConfigReader {

  private val config = new AppConfig(Configuration.load(Environment.simple()))

  require(config.kyloUrl.nonEmpty, "A kylo url must be specified")
  require(config.kyloUser.nonEmpty, "A kylo user must be specified")
  require(config.kyloPwd.nonEmpty, "A kylo password must be specified")

  def userIdHeader: String = config.userIdHeader.getOrElse("userid")
  def getCkanHost: String = config.ckanHost.getOrElse("localhost")
  def getDbHost: String = config.dbHost.getOrElse("localhost")
  def getDbPort: Int = config.dbPort.getOrElse(27017)
  def database :String = config.database.getOrElse("catalog_manager")
  def password :String = config.password.getOrElse("")
  def userName :String = config.userName.getOrElse("")
  def localUrl :String = config.localUrl.getOrElse("http://localhost:9001")
  def securityManHost :String = config.securityManHost.getOrElse("http://localhost:9002/security-manager")
  def cookieExpiration:Long = config.cookieExpiration.getOrElse(30L)// 30 min by default
  def ingestionUrl :String = config.ingestionUrl.getOrElse("http://localhost:9003")
  def kyloUrl: String = config.kyloUrl.get
  def kyloUser: String = config.kyloUser.get
  def kyloPwd: String = config.kyloPwd.get
  def kafkaProxyUrl: String = config.kafkaProxyUrl.getOrElse("")

} 
Example 56
Source File: CkanService.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package it.gov.daf.catalogmanager.service



trait CkanServiceComponent {
  this: CkanRepositoryComponent =>
  val ckanService: CkanService

  class CkanService {

    def getMongoUser(name:String, callingUserid :MetadataCat ): JsResult[User]  = {
      ckanRepository.getMongoUser(name, callingUserid)
    }

    def verifyCredentials(credentials: Credentials):Boolean = {
      ckanRepository.verifyCredentials(credentials: Credentials)
    }
    def updateOrganization(orgId: String, jsonOrg: JsValue, callingUserid :MetadataCat ): Future[String] = {
      ckanRepository.updateOrganization(orgId,jsonOrg, callingUserid)
    }
    def patchOrganization(orgId: String, jsonOrg: JsValue, callingUserid :MetadataCat ): Future[String] = {
      ckanRepository.patchOrganization(orgId,jsonOrg, callingUserid)
    }

    def createUser(jsonUser: JsValue, callingUserid :MetadataCat): Future[String] = {
      ckanRepository.createUser(jsonUser, callingUserid)
    }
    def getUserOrganizations(userName :String, callingUserid :MetadataCat) : Future[JsResult[Seq[Organization]]] = {
      ckanRepository.getUserOrganizations(userName, callingUserid)
    }

    def createDataset(jsonDataset: JsValue, callingUserid :MetadataCat): Future[String] = {
      ckanRepository.createDataset(jsonDataset,callingUserid)
    }
    def createOrganization(jsonDataset: JsValue, callingUserid :MetadataCat): Future[String] = {
      ckanRepository.createOrganization(jsonDataset,callingUserid)
    }
    def dataset(datasetId: String, callingUserid :MetadataCat): JsValue = {
      ckanRepository.dataset(datasetId,callingUserid)
    }

    def getOrganization(orgId :String, callingUserid :MetadataCat) : Future[JsResult[Organization]] = {
      ckanRepository.getOrganization(orgId,callingUserid)
    }

    def getOrganizations(callingUserid :MetadataCat) : Future[JsValue] = {
      ckanRepository.getOrganizations(callingUserid)
    }

    def getDatasets(callingUserid :MetadataCat) : Future[JsValue] = {
      ckanRepository.getDatasets(callingUserid)
    }

    def searchDatasets( input: (MetadataCat, MetadataCat, ResourceSize, ResourceSize), callingUserid :MetadataCat) : Future[JsResult[Seq[Dataset]]] = {
      ckanRepository.searchDatasets(input, callingUserid)
    }
    def autocompleteDatasets( input: (MetadataCat, ResourceSize), callingUserid :MetadataCat) : Future[JsResult[Seq[AutocompRes]]] = {
      ckanRepository.autocompleteDatasets(input, callingUserid)
    }

    def getDatasetsWithRes( input: (ResourceSize, ResourceSize),callingUserid :MetadataCat ) : Future[JsResult[Seq[Dataset]]] = {
      ckanRepository.getDatasetsWithRes(input, callingUserid)
    }

    def testDataset(datasetId :String, callingUserid :MetadataCat) : Future[JsResult[Dataset]] = {
      ckanRepository.testDataset(datasetId, callingUserid)
    }

  }
}


object CkanRegistry extends
  CkanServiceComponent with
  CkanRepositoryComponent {
  val conf = Configuration.load(Environment.simple())
  val app: String = conf.getString("app.type").getOrElse("dev")
  val ckanRepository =  CkanRepository(app)
  val ckanService = new CkanService
} 
Example 57
Source File: TestAbstractModule.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package controllers.modules

import akka.stream.Materializer
import daf.util.TestCache
import org.pac4j.play.store.{ PlayCacheSessionStore, PlaySessionStore }
import play.api.{ Configuration, Environment }
import play.api.inject.Module
import play.api.libs.ws.WSClient
import play.api.libs.ws.ahc.AhcWSClient
import play.api.mvc.BodyParsers
import play.cache.{ CacheApi, DefaultCacheApi }
import play.api.cache.{ CacheApi => ApiCacheApi }
import play.api.inject.guice.GuiceInjectorBuilder

abstract class TestAbstractModule extends Module {

  private lazy val injector = new GuiceInjectorBuilder().bindings(this).injector()

  private lazy val sessionStoreInstance: PlaySessionStore = injector.instanceOf { classOf[PlaySessionStore] }
  private lazy val wsClientInstance: WSClient = injector.instanceOf { classOf[WSClient] }
  private lazy val bodyParsersInstance: BodyParsers = BodyParsers

  final def sessionStore: PlaySessionStore = sessionStoreInstance
  final def ws: WSClient = wsClientInstance
  final def bodyParsers: BodyParsers = bodyParsersInstance

  protected implicit def materializer: Materializer

  override def bindings(environment: Environment, configuration: Configuration) = Seq(
    bind(classOf[ApiCacheApi]).to(classOf[TestCache]),
    bind(classOf[CacheApi]).to(classOf[DefaultCacheApi]),
    bind(classOf[PlaySessionStore]).to(classOf[PlayCacheSessionStore]),
    bind(classOf[BodyParsers]).to(BodyParsers),
    bind(classOf[WSClient]).toInstance(AhcWSClient())
  )
} 
Example 58
Source File: KBModule.scala    From daf-semantics   with Apache License 2.0 5 votes vote down vote up
package modules

import javax.inject._

import play.api.inject.ApplicationLifecycle
import play.api.mvc._

import scala.concurrent.Future
import com.google.inject.ImplementedBy
import play.api.Play
import play.api.Application
import play.api.Environment
import play.api.Configuration
import scala.concurrent.ExecutionContext
import play.api.Logger
import it.almawave.linkeddata.kb.utils.ConfigHelper
import it.almawave.linkeddata.kb.repo._
import scala.concurrent.ExecutionContext.Implicits.global
import java.nio.file.Paths
import play.api.Mode
import java.io.File
import it.almawave.linkeddata.kb.repo.RDFRepository
import com.typesafe.config.ConfigFactory

@ImplementedBy(classOf[KBModuleBase])
trait KBModule

@Singleton
class KBModuleBase @Inject() (lifecycle: ApplicationLifecycle) extends KBModule {

  // TODO: SPI per dev / prod
  val kbrepo = RDFRepository.memory()

  val logger = Logger.underlyingLogger

  // when application starts...
  @Inject
  def onStart(
    env: Environment,
    configuration: Configuration)(implicit ec: ExecutionContext) {

    // get configs
    val app_type = configuration.underlying.getString("app.type")

    val data_dir = app_type match {
      case "dev"  => "./dist/data"
      case "prod" => "./data"
    }
    logger.debug(s"app_type: ${app_type}")
    logger.debug(s"data_dir: ${data_dir}")

    // starting VocabularyAPI service
    var conf_voc = ConfigFactory.parseFile(new File("./conf/semantic_repository.conf").getAbsoluteFile)
    conf_voc = ConfigHelper.injectParameters(conf_voc, ("data_dir", data_dir))

    kbrepo.configuration(conf_voc)

    logger.info("KBModule.START....")
    logger.debug("KBModule using configuration:\n" + ConfigHelper.pretty(conf_voc))

    println("KBModule using configuration:\n" + ConfigHelper.pretty(conf_voc))

    // this is needed for ensure proper connection(s) etc
    kbrepo.start()

    

    // CHECK the initial (total) triples count
    var triples = kbrepo.store.size()

    logger.info(s"KBModule> ${triples} triples loaded")

  }

  // when application stops...
  lifecycle.addStopHook({ () =>

    Future.successful {

      // this is useful for saving files, closing connections, release indexes, etc
      kbrepo.stop()
      logger.info("KBModule.STOP....")

    }

  })

} 
Example 59
Source File: ClientsModule.scala    From daf-semantics   with Apache License 2.0 5 votes vote down vote up
package modules

import com.google.inject.ImplementedBy
import play.api.inject.ApplicationLifecycle
import javax.inject.Singleton
import javax.inject.Inject
import play.api.libs.ws.WSClient
import play.api.Application
import play.api.Environment
import play.api.Configuration
import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import play.Logger
import clients.OntonetHubClient
import com.typesafe.config.ConfigFactory
import com.typesafe.config.ConfigRenderOptions

@ImplementedBy(classOf[ClientsModuleBase])
trait ClientsModule

@Singleton
class ClientsModuleBase @Inject() (lifecycle: ApplicationLifecycle,
                                   ws: WSClient,
                                   configuration: Configuration) extends ClientsModule {

  val conf_clients = configuration.underlying
    .getConfig("clients")

  val ontonethub_config = conf_clients.getConfig("ontonethub")

  // TODO: verify if default configurations are needed here
  val ontonethub = new OntonetHubClient(ws, ontonethub_config)

  // TESTING ................................................
  val options = ConfigRenderOptions.concise()
    .setComments(false).setOriginComments(false)
    .setFormatted(true).setJson(true)
  val json = ontonethub_config.root().render(options)
  // TESTING ................................................

  // when application starts...
  @Inject
  def onStart(
    app: Application,
    env: Environment)(implicit ec: ExecutionContext) {

    Logger.info("ClientsModuleBase START")

    println("\n\n\n\n\n\n")
    println(json)

  }

  // when application stops...
  lifecycle.addStopHook({ () =>

    Future.successful {

      Logger.info("ClientsModuleBase STOP")

    }

  })

} 
Example 60
Source File: ConfigDecoratorSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package config

import java.net.{MalformedURLException, URL}

import play.api.i18n.Langs
import play.api.{Configuration, Environment}
import uk.gov.hmrc.domain.SaUtrGenerator
import uk.gov.hmrc.play.bootstrap.config.{RunMode, ServicesConfig}
import util.BaseSpec

class ConfigDecoratorSpec extends BaseSpec {
  val saUtr = new SaUtrGenerator().nextSaUtr.utr

  "Converting urls to sso" should {

    trait LocalSetup {

      lazy val configDecorator = new ConfigDecorator(
        injected[Environment],
        injected[Configuration],
        injected[RunMode],
        injected[Langs],
        injected[ServicesConfig]) {
        override lazy val portalBaseUrl = "http://portal.service"
        override lazy val companyAuthFrontendHost = "http://company-auth-frontend.service"
      }
    }

    "return a properly encoded sso url when calling transformUrlForSso" in new LocalSetup {

      configDecorator.transformUrlForSso(new URL("http://example.com/some/path?key=val")) shouldBe
        "http://company-auth-frontend.service/ssoout/non-digital?continue=http%3A%2F%2Fexample.com%2Fsome%2Fpath%3Fkey%3Dval"
    }

    "return a properly formatted sa302 url when calling sa302Url" in new LocalSetup {

      configDecorator.sa302Url(saUtr, "1516") shouldBe
        s"/self-assessment-file/1516/ind/$saUtr/return/viewYourCalculation/reviewYourFullCalculation"
    }

    "return a properly formatted SA Account Summary Url url when calling ssoToSaAccountSummaryUrl" in new LocalSetup {

      configDecorator.ssoToSaAccountSummaryUrl(saUtr, "1516") shouldBe
        s"http://company-auth-frontend.service/ssoout/non-digital?continue=http%3A%2F%2Fportal.service%2Fself-assessment%2Find%2F$saUtr%2Ftaxreturn%2F1516%2Foptions"
    }
  }

  "Calling toPortalUrl" should {

    trait LocalSetup {

      def portalBaseUrlToTest: Option[String]

      lazy val configDecorator = new ConfigDecorator(
        injected[Environment],
        injected[Configuration],
        injected[RunMode],
        injected[Langs],
        injected[ServicesConfig]) {
        override lazy val portalBaseUrl = portalBaseUrlToTest.getOrElse("")
      }
    }

    "return a URL if portalBaseUrl is present and fully qualified" in new LocalSetup {

      val portalBaseUrlToTest = Some("http://portal.service")

      configDecorator.toPortalUrl("/some/path").toString shouldBe "http://portal.service/some/path"
    }

    "fail with a MalformedURLException if portalBaseUrl is not present" in new LocalSetup {

      val portalBaseUrlToTest = None

      a[MalformedURLException] should be thrownBy {
        configDecorator.toPortalUrl("/some/path")
      }
    }

    "fail with a MalformedURLException if portalBaseUrl is not fully qualified" in new LocalSetup {

      val portalBaseUrlToTest = Some("/")

      a[MalformedURLException] should be thrownBy {
        configDecorator.toPortalUrl("/some/path")
      }
    }

    "fail with a MalformedURLException if portalBaseUrl is protocol-relative" in new LocalSetup {

      val portalBaseUrlToTest = Some("//portal.service")

      a[MalformedURLException] should be thrownBy {
        configDecorator.toPortalUrl("/some/path")
      }
    }

  }
} 
Example 61
Source File: IdentityVerificationFrontendServiceSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import com.codahale.metrics.Timer
import com.kenshoo.play.metrics.Metrics
import org.mockito.Matchers._
import org.mockito.Mockito._
import org.scalatestplus.mockito.MockitoSugar
import play.api.http.Status._
import play.api.libs.json.Json
import play.api.{Configuration, Environment}
import services.http.FakeSimpleHttp
import uk.gov.hmrc.http.HttpResponse
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import util.BaseSpec

class IdentityVerificationFrontendServiceSpec extends BaseSpec {

  trait SpecSetup {
    def httpResponse: HttpResponse
    def simulateIdentityVerificationFrontendIsDown: Boolean

    val anException = new RuntimeException("Any")
    val metricId = "get-iv-journey-status"

    lazy val (service, metrics, timer) = {
      val fakeSimpleHttp = {
        if (simulateIdentityVerificationFrontendIsDown) new FakeSimpleHttp(Right(anException))
        else new FakeSimpleHttp(Left(httpResponse))
      }

      val serviceConfig = app.injector.instanceOf[ServicesConfig]
      val timer = MockitoSugar.mock[Timer.Context]
      val identityVerificationFrontendService: IdentityVerificationFrontendService =
        new IdentityVerificationFrontendService(
          injected[Environment],
          injected[Configuration],
          fakeSimpleHttp,
          MockitoSugar.mock[Metrics],
          serviceConfig) {

          override val metricsOperator: MetricsOperator = MockitoSugar.mock[MetricsOperator]
          when(metricsOperator.startTimer(any())) thenReturn timer
        }

      (identityVerificationFrontendService, identityVerificationFrontendService.metricsOperator, timer)
    }
  }

  "Calling IdentityVerificationFrontend.getIVJourneyStatus" should {

    "return an IdentityVerificationSuccessResponse containing a journey status object when called with a journeyId" in new SpecSetup {
      override lazy val httpResponse = HttpResponse(OK, Some(Json.obj("token" -> "1234", "result" -> "LockedOut")))
      override lazy val simulateIdentityVerificationFrontendIsDown = false

      val r = service.getIVJourneyStatus("1234")

      await(r) shouldBe IdentityVerificationSuccessResponse("LockedOut")
      verify(metrics, times(1)).startTimer(metricId)
      verify(metrics, times(1)).incrementSuccessCounter(metricId)
      verify(timer, times(1)).stop()
    }

    "return IdentityVerificationNotFoundResponse when called with a journeyId that causes a NOT FOUND response" in new SpecSetup {
      override lazy val httpResponse = HttpResponse(NOT_FOUND)
      override lazy val simulateIdentityVerificationFrontendIsDown = false

      val r = service.getIVJourneyStatus("4321")

      await(r) shouldBe IdentityVerificationNotFoundResponse
      verify(metrics, times(1)).startTimer(metricId)
      verify(metrics, times(1)).incrementFailedCounter(metricId)
      verify(timer, times(1)).stop()
    }

    "return TaxCalculationUnexpectedResponse when an unexpected status is returned" in new SpecSetup {
      val seeOtherResponse = HttpResponse(SEE_OTHER)
      override lazy val httpResponse = seeOtherResponse
      override lazy val simulateIdentityVerificationFrontendIsDown = false

      val r = service.getIVJourneyStatus("1234")

      await(r) shouldBe IdentityVerificationUnexpectedResponse(seeOtherResponse)
      verify(metrics, times(1)).startTimer(metricId)
      verify(metrics, times(1)).incrementFailedCounter(metricId)
      verify(timer, times(1)).stop()
    }

    "return IdentityVerificationErrorResponse when called and service is down" in new SpecSetup {
      override lazy val httpResponse = ???
      override lazy val simulateIdentityVerificationFrontendIsDown = true

      val r = service.getIVJourneyStatus("1234")

      await(r) shouldBe IdentityVerificationErrorResponse(anException)
      verify(metrics, times(1)).startTimer(metricId)
      verify(metrics, times(1)).incrementFailedCounter(metricId)
      verify(timer, times(1)).stop()
    }

  }
} 
Example 62
Source File: FormPartialServiceSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import com.codahale.metrics.Timer
import com.kenshoo.play.metrics.Metrics
import config.ConfigDecorator
import org.mockito.Matchers._
import org.mockito.Mockito._
import org.scalatestplus.mockito.MockitoSugar
import play.api.{Configuration, Environment}
import play.twirl.api.Html
import services.partials.FormPartialService
import uk.gov.hmrc.crypto.ApplicationCrypto
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import uk.gov.hmrc.play.bootstrap.filters.frontend.crypto.SessionCookieCrypto
import uk.gov.hmrc.play.bootstrap.http.DefaultHttpClient
import uk.gov.hmrc.play.partials.HtmlPartial
import util.BaseSpec
import util.Fixtures._

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

class FormPartialServiceSpec extends BaseSpec {

  trait LocalSetup {
    val servicesConfig = app.injector.instanceOf[ServicesConfig]
    val timer = MockitoSugar.mock[Timer.Context]
    val formPartialService: FormPartialService = new FormPartialService(
      injected[Environment],
      injected[Configuration],
      MockitoSugar.mock[DefaultHttpClient],
      MockitoSugar.mock[Metrics],
      MockitoSugar.mock[ConfigDecorator],
      injected[SessionCookieCrypto],
      servicesConfig
    ) {
      override val metricsOperator: MetricsOperator = MockitoSugar.mock[MetricsOperator]
      when(metricsOperator.startTimer(any())) thenReturn timer
    }
  }

  "Calling FormPartialServiceSpec" should {

    "return form list for National insurance" in new LocalSetup {

      when(formPartialService.http.GET[HtmlPartial](any())(any(), any(), any())) thenReturn
        Future.successful[HtmlPartial](HtmlPartial.Success(Some("Title"), Html("<title/>")))

      formPartialService.getNationalInsurancePartial(buildFakeRequestWithAuth("GET")).map(p => p shouldBe "<title/>")
      verify(formPartialService.http, times(1)).GET[Html](any())(any(), any(), any())
    }

    "return form list for Self-assessment" in new LocalSetup {

      when(formPartialService.http.GET[HtmlPartial](any())(any(), any(), any())) thenReturn
        Future.successful[HtmlPartial](HtmlPartial.Success(Some("Title"), Html("<title/>")))

      formPartialService.getSelfAssessmentPartial(buildFakeRequestWithAuth("GET")).map(p => p shouldBe "<title/>")
      verify(formPartialService.http, times(1)).GET[Html](any())(any(), any(), any())
    }

  }

} 
Example 63
Source File: IntegrationBaseSpec.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package support

import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach}
import org.scalatestplus.play.guice.GuiceOneServerPerSuite
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.json.{JsValue, Json}
import play.api.libs.ws.{WSClient, WSRequest, WSResponse}
import play.api.{Application, Environment, Mode}

trait IntegrationBaseSpec extends UnitSpec with WireMockHelper with GuiceOneServerPerSuite
  with BeforeAndAfterEach with BeforeAndAfterAll {

  val mockHost: String = WireMockHelper.host
  val mockPort: String = WireMockHelper.wireMockPort.toString

  lazy val client: WSClient = app.injector.instanceOf[WSClient]

  def servicesConfig: Map[String, Any] = Map(
    "microservice.services.des.host" -> mockHost,
    "microservice.services.des.port" -> mockPort,
    "microservice.services.auth.host" -> mockHost,
    "microservice.services.auth.port" -> mockPort,
    "auditing.consumer.baseUri.port" -> mockPort,
    "microservice.services.non-repudiation.host" -> mockHost,
    "microservice.services.non-repudiation.port" -> mockPort,
    "feature-switch.refactor.enabled" -> true,
    "feature-switch.refactor.prod.enabled" -> false,
    "microservice.services.non-repudiation.maxTimeout" -> 5000
  )

  override implicit lazy val app: Application = new GuiceApplicationBuilder()
    .in(Environment.simple(mode = Mode.Dev))
    .configure(servicesConfig)
    .build()

  override def beforeAll(): Unit = {
    super.beforeAll()
    startWireMock()
  }

  override def afterAll(): Unit = {
    stopWireMock()
    super.afterAll()
  }

  def buildRequest(path: String): WSRequest = client.url(s"http://localhost:$port$path").withFollowRedirects(false)

  def document(response: WSResponse): JsValue = Json.parse(response.body)
} 
Example 64
Source File: LocalTemplateRenderer.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package config

import com.google.inject.Inject
import play.api.Mode.Mode
import play.api.{Configuration, Environment}
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import uk.gov.hmrc.play.bootstrap.http.HttpClient
import uk.gov.hmrc.renderer.TemplateRenderer

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

class LocalTemplateRenderer @Inject()(
  environment: Environment,
  configuration: Configuration,
  wsHttp: HttpClient,
  servicesConfig: ServicesConfig)(implicit executionContext: ExecutionContext)
    extends TemplateRenderer {

  val mode: Mode = environment.mode
  val runModeConfiguration: Configuration = configuration
  override lazy val templateServiceBaseUrl = servicesConfig.baseUrl("frontend-template-provider")
  override lazy val refreshAfter: Duration =
    runModeConfiguration.getInt("template.refreshInterval").getOrElse(600) seconds

  private implicit val hc = HeaderCarrier()

  override def fetchTemplate(path: String): Future[String] =
    wsHttp.GET(path).map(_.body)
} 
Example 65
Source File: PaperlessPreferencesController.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers

import com.google.inject.Inject
import config.ConfigDecorator
import controllers.auth._
import controllers.auth.requests.UserRequest
import play.api.Mode.Mode
import play.api.i18n.{Messages, MessagesApi}
import play.api.mvc.{Action, AnyContent, MessagesControllerComponents}
import services.partials.PreferencesFrontendPartialService
import play.api.mvc.{Action, AnyContent}
import play.api.{Configuration, Environment}
import uk.gov.hmrc.renderer.{ActiveTabMessages, TemplateRenderer}
import util.{LocalPartialRetriever, Tools}

import scala.concurrent.{ExecutionContext, Future}

class PaperlessPreferencesController @Inject()(
  val preferencesFrontendPartialService: PreferencesFrontendPartialService,
  authJourney: AuthJourney,
  withActiveTabAction: WithActiveTabAction,
  withBreadcrumbAction: WithBreadcrumbAction,
  cc: MessagesControllerComponents,
  tools: Tools)(
  implicit partialRetriever: LocalPartialRetriever,
  configDecorator: ConfigDecorator,
  templateRenderer: TemplateRenderer,
  ec: ExecutionContext)
    extends PertaxBaseController(cc) {

  def managePreferences: Action[AnyContent] =
    (authJourney.authWithPersonalDetails andThen withActiveTabAction
      .addActiveTab(ActiveTabMessages) andThen withBreadcrumbAction.addBreadcrumb(baseBreadcrumb)).async {
      implicit request: UserRequest[_] =>
        if (request.isVerify) {
          Future.successful(
            BadRequest(
              views.html.error(
                "global.error.BadRequest.title",
                Some("global.error.BadRequest.heading"),
                List("global.error.BadRequest.message"))))
        } else {
          Future.successful(
            Redirect(
              getManagePreferencesUrl(configDecorator.pertaxFrontendHomeUrl, Messages("label.back_to_account_home"))))
        }
    }

  private def getManagePreferencesUrl(returnUrl: String, returnLinkText: String): String =
    s"${configDecorator.preferencesFrontendService}/paperless/check-settings?returnUrl=${tools.encryptAndEncode(returnUrl)}&returnLinkText=${tools
      .encryptAndEncode(returnLinkText)}"
} 
Example 66
Source File: FormPartialService.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services.partials

import com.google.inject.{Inject, Singleton}
import com.kenshoo.play.metrics.Metrics
import config.ConfigDecorator
import metrics.HasMetrics
import play.api.Mode.Mode
import play.api.mvc.RequestHeader
import play.api.{Configuration, Environment}
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import uk.gov.hmrc.play.bootstrap.filters.frontend.crypto.SessionCookieCrypto
import uk.gov.hmrc.play.bootstrap.http.HttpClient
import uk.gov.hmrc.play.partials.HtmlPartial
import util.EnhancedPartialRetriever

import scala.concurrent.{ExecutionContext, Future}

@Singleton
class FormPartialService @Inject()(
  environment: Environment,
  runModeConfiguration: Configuration,
  override val http: HttpClient,
  val metrics: Metrics,
  val configDecorator: ConfigDecorator,
  sessionCookieCrypto: SessionCookieCrypto,
  servicesConfig: ServicesConfig)(implicit executionContext: ExecutionContext)
    extends EnhancedPartialRetriever(sessionCookieCrypto) with HasMetrics {

  val mode: Mode = environment.mode
  def getNationalInsurancePartial(implicit request: RequestHeader): Future[HtmlPartial] =
    loadPartial(configDecorator.nationalInsuranceFormPartialLinkUrl)

  def getSelfAssessmentPartial(implicit request: RequestHeader): Future[HtmlPartial] =
    loadPartial(configDecorator.selfAssessmentFormPartialLinkUrl)

} 
Example 67
Source File: PreferencesFrontendPartialService.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services.partials

import com.google.inject.{Inject, Singleton}
import com.kenshoo.play.metrics.Metrics
import metrics.HasMetrics
import play.api.Mode.Mode
import play.api.mvc.RequestHeader
import play.api.{Configuration, Environment}
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import uk.gov.hmrc.play.bootstrap.filters.frontend.crypto.SessionCookieCrypto
import uk.gov.hmrc.play.bootstrap.http.HttpClient
import uk.gov.hmrc.play.partials.HtmlPartial
import util.{EnhancedPartialRetriever, Tools}

import scala.concurrent.{ExecutionContext, Future}

@Singleton
class PreferencesFrontendPartialService @Inject()(
  environment: Environment,
  runModeConfiguration: Configuration,
  val http: HttpClient,
  val metrics: Metrics,
  sessionCookieCrypto: SessionCookieCrypto,
  val tools: Tools,
  servicesConfig: ServicesConfig)(implicit executionContext: ExecutionContext)
    extends EnhancedPartialRetriever(sessionCookieCrypto) with HasMetrics {

  val mode: Mode = environment.mode
  val preferencesFrontendUrl = servicesConfig.baseUrl("preferences-frontend")

  def getManagePreferencesPartial(returnUrl: String, returnLinkText: String)(
    implicit request: RequestHeader): Future[HtmlPartial] =
    loadPartial(s"$preferencesFrontendUrl/paperless/manage?returnUrl=${tools
      .encryptAndEncode(returnUrl)}&returnLinkText=${tools.encryptAndEncode(returnLinkText)}")

} 
Example 68
Source File: MessageFrontendService.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services.partials

import com.google.inject.{Inject, Singleton}
import com.kenshoo.play.metrics.Metrics
import metrics.HasMetrics
import models.MessageCount
import play.api.Mode.Mode
import play.api.mvc.RequestHeader
import play.api.{Configuration, Environment, Logger}
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import uk.gov.hmrc.play.bootstrap.filters.frontend.crypto.SessionCookieCrypto
import uk.gov.hmrc.play.bootstrap.http.HttpClient
import uk.gov.hmrc.play.partials.HtmlPartial
import util.EnhancedPartialRetriever

import scala.concurrent.{ExecutionContext, Future}

@Singleton
class MessageFrontendService @Inject()(
  environment: Environment,
  runModeConfiguration: Configuration,
  override val http: HttpClient,
  val metrics: Metrics,
  val sessionCookieCrypto: SessionCookieCrypto,
  servicesConfig: ServicesConfig)(implicit executionContext: ExecutionContext)
    extends EnhancedPartialRetriever(sessionCookieCrypto) with HasMetrics {

  val mode: Mode = environment.mode

  lazy val messageFrontendUrl: String = servicesConfig.baseUrl("message-frontend")

  def getMessageListPartial(implicit request: RequestHeader): Future[HtmlPartial] =
    loadPartial(messageFrontendUrl + "/messages")

  def getMessageDetailPartial(messageToken: String)(implicit request: RequestHeader): Future[HtmlPartial] =
    loadPartial(messageFrontendUrl + "/messages/" + messageToken)

  def getMessageInboxLinkPartial(implicit request: RequestHeader): Future[HtmlPartial] =
    loadPartial(
      messageFrontendUrl + "/messages/inbox-link?messagesInboxUrl=" + controllers.routes.MessageController
        .messageList())

  def getUnreadMessageCount(implicit request: RequestHeader): Future[Option[Int]] =
    loadJson(messageFrontendUrl + "/messages/count?read=No").map(_.map(_.count))

  private def loadJson(url: String)(implicit hc: HeaderCarrier): Future[Option[MessageCount]] =
    withMetricsTimer("load-json") { t =>
      http.GET[Option[MessageCount]](url) recover {
        case e =>
          t.completeTimerAndIncrementFailedCounter()
          Logger.warn(s"Failed to load json", e)
          None
      }
    }
} 
Example 69
Source File: SaPartialService.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services.partials

import com.google.inject.{Inject, Singleton}
import com.kenshoo.play.metrics.Metrics
import config.ConfigDecorator
import metrics.HasMetrics
import play.api.Mode.Mode
import play.api.mvc.RequestHeader
import play.api.{Configuration, Environment}
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import uk.gov.hmrc.play.bootstrap.filters.frontend.crypto.SessionCookieCrypto
import uk.gov.hmrc.play.bootstrap.http.HttpClient
import uk.gov.hmrc.play.partials.HtmlPartial
import util.{EnhancedPartialRetriever, Tools}

import scala.concurrent.{ExecutionContext, Future}
@Singleton
class SaPartialService @Inject()(
  environment: Environment,
  runModeConfiguration: Configuration,
  override val http: HttpClient,
  val metrics: Metrics,
  val configDecorator: ConfigDecorator,
  sessionCookieCrypto: SessionCookieCrypto,
  val tools: Tools,
  servicesConfig: ServicesConfig)(implicit executionContext: ExecutionContext)
    extends EnhancedPartialRetriever(sessionCookieCrypto) with HasMetrics {

  val mode: Mode = environment.mode
  private val returnUrl = configDecorator.pertaxFrontendHomeUrl
  private val returnLinkText = configDecorator.saPartialReturnLinkText

  def getSaAccountSummary(implicit request: RequestHeader): Future[HtmlPartial] =
    loadPartial(
      configDecorator.businessTaxAccountService + s"/business-account/partial/sa/account-summary?returnUrl=${tools
        .urlEncode(returnUrl)}&returnLinkText=${tools.urlEncode(returnLinkText)}")

} 
Example 70
Source File: TaiService.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import com.kenshoo.play.metrics.Metrics
import com.google.inject.{Inject, Singleton}
import metrics._
import models._
import play.api.Mode.Mode
import play.api.http.Status._
import play.api.{Configuration, Environment, Logger}
import services.http.SimpleHttp
import uk.gov.hmrc.domain.Nino
import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse}
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig

import scala.concurrent.Future

sealed trait TaxComponentsResponse
case class TaxComponentsSuccessResponse(taxComponents: TaxComponents) extends TaxComponentsResponse
case object TaxComponentsUnavailableResponse extends TaxComponentsResponse
case class TaxComponentsUnexpectedResponse(r: HttpResponse) extends TaxComponentsResponse
case class TaxComponentsErrorResponse(cause: Exception) extends TaxComponentsResponse
@Singleton
class TaiService @Inject()(
  environment: Environment,
  runModeConfiguration: Configuration,
  val simpleHttp: SimpleHttp,
  val metrics: Metrics,
  servicesConfig: ServicesConfig)
    extends HasMetrics {

  val mode: Mode = environment.mode
  lazy val taiUrl = servicesConfig.baseUrl("tai")

  
  def taxComponents(nino: Nino, year: Int)(implicit hc: HeaderCarrier): Future[TaxComponentsResponse] =
    withMetricsTimer("get-tax-components") { t =>
      simpleHttp.get[TaxComponentsResponse](s"$taiUrl/tai/$nino/tax-account/$year/tax-components")(
        onComplete = {
          case r if r.status >= 200 && r.status < 300 =>
            t.completeTimerAndIncrementSuccessCounter()
            TaxComponentsSuccessResponse(TaxComponents.fromJsonTaxComponents(r.json))

          case r if r.status == NOT_FOUND | r.status == BAD_REQUEST =>
            t.completeTimerAndIncrementSuccessCounter()
            Logger.warn("Unable to find tax components from the tai-service")
            TaxComponentsUnavailableResponse

          case r =>
            t.completeTimerAndIncrementFailedCounter()
            Logger.warn(s"Unexpected ${r.status} response getting tax components from the tai-service")
            TaxComponentsUnexpectedResponse(r)
        },
        onError = {
          case e =>
            t.completeTimerAndIncrementFailedCounter()
            Logger.error("Error getting tax components from the tai-service", e)
            TaxComponentsErrorResponse(e)
        }
      )
    }
} 
Example 71
Source File: LifetimeAllowanceService.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import com.kenshoo.play.metrics.Metrics
import com.google.inject.{Inject, Singleton}
import metrics.HasMetrics
import models.LtaProtections
import play.api.Mode.Mode
import play.api.{Configuration, Environment, Logger}
import services.http.SimpleHttp
import uk.gov.hmrc.domain.Nino
import uk.gov.hmrc.http.{HeaderCarrier, HttpReads}
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
@Singleton
class LifetimeAllowanceService @Inject()(
  environment: Environment,
  configuration: Configuration,
  val simpleHttp: SimpleHttp,
  val metrics: Metrics,
  servicesConfig: ServicesConfig)
    extends HasMetrics {

  val mode: Mode = environment.mode
  val runModeConfiguration: Configuration = configuration
  lazy val lifetimeAllowanceUrl = servicesConfig.baseUrl("pensions-lifetime-allowance")

  def getCount(nino: Nino)(implicit hc: HeaderCarrier, rds: HttpReads[LtaProtections]): Future[Option[Int]] =
    withMetricsTimer("has-lta-response") { t =>
      simpleHttp.get[Option[Int]](
        lifetimeAllowanceUrl + s"/protect-your-lifetime-allowance/individuals/$nino/protections/count")(
        onComplete = {
          case r if r.status >= 200 && r.status < 300 =>
            t.completeTimerAndIncrementSuccessCounter()
            Some((r.json.as[LtaProtections]).count)

          case r =>
            t.completeTimerAndIncrementFailedCounter()
            Logger.warn(
              s"Unexpected ${r.status} response getting lifetime allowance protections count from LTA service")
            None
        },
        onError = {
          case e =>
            t.completeTimerAndIncrementFailedCounter()
            Logger.warn("Error getting lifetime allowance protections count from LTA service", e)
            None
        }
      )
    }

  def hasLtaProtection(nino: Nino)(implicit hc: HeaderCarrier, rds: HttpReads[LtaProtections]): Future[Boolean] =
    getCount(nino) map {
      case (Some(0) | None) => false
      case _                => true
    }
} 
Example 72
Source File: IdentityVerificationFrontendService.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import com.kenshoo.play.metrics.Metrics
import com.google.inject.{Inject, Singleton}
import metrics.HasMetrics
import play.api.Mode.Mode
import play.api.http.Status._
import play.api.{Configuration, Environment, Logger}
import services.http.SimpleHttp
import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse}
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig

import scala.concurrent.Future

trait IdentityVerificationResponse
case class IdentityVerificationSuccessResponse(result: String) extends IdentityVerificationResponse
case object IdentityVerificationNotFoundResponse extends IdentityVerificationResponse
case class IdentityVerificationUnexpectedResponse(r: HttpResponse) extends IdentityVerificationResponse
case class IdentityVerificationErrorResponse(cause: Exception) extends IdentityVerificationResponse

object IdentityVerificationSuccessResponse {
  val Success = "Success"
  val Incomplete = "Incomplete"
  val FailedMatching = "FailedMatching"
  val InsufficientEvidence = "InsufficientEvidence"
  val LockedOut = "LockedOut"
  val UserAborted = "UserAborted"
  val Timeout = "Timeout"
  val TechnicalIssue = "TechnicalIssue"
  val PrecondFailed = "PreconditionFailed"
}
@Singleton
class IdentityVerificationFrontendService @Inject()(
  environment: Environment,
  configuration: Configuration,
  val simpleHttp: SimpleHttp,
  val metrics: Metrics,
  servicesConfig: ServicesConfig)
    extends HasMetrics {

  val mode: Mode = environment.mode
  val runModeConfiguration: Configuration = configuration
  lazy val identityVerificationFrontendUrl: String = servicesConfig.baseUrl("identity-verification-frontend")

  def getIVJourneyStatus(journeyId: String)(implicit hc: HeaderCarrier): Future[IdentityVerificationResponse] =
    withMetricsTimer("get-iv-journey-status") { t =>
      simpleHttp.get[IdentityVerificationResponse](
        s"$identityVerificationFrontendUrl/mdtp/journey/journeyId/$journeyId")(
        onComplete = {
          case r if r.status >= 200 && r.status < 300 =>
            t.completeTimerAndIncrementSuccessCounter()
            val result = List((r.json \ "journeyResult").asOpt[String], (r.json \ "result").asOpt[String]).flatten.head //FIXME - dont use head
            IdentityVerificationSuccessResponse(result)

          case r if r.status == NOT_FOUND =>
            t.completeTimerAndIncrementFailedCounter()
            Logger.warn("Unable to get IV journey status from identity-verification-frontend-service")
            IdentityVerificationNotFoundResponse

          case r =>
            t.completeTimerAndIncrementFailedCounter()
            Logger.warn(
              s"Unexpected ${r.status} response getting IV journey status from identity-verification-frontend-service")
            IdentityVerificationUnexpectedResponse(r)
        },
        onError = {
          case e =>
            t.completeTimerAndIncrementFailedCounter()
            Logger.warn("Error getting IV journey status from identity-verification-frontend-service", e)
            IdentityVerificationErrorResponse(e)
        }
      )

    }
} 
Example 73
Source File: TaxCalculationService.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import com.kenshoo.play.metrics.Metrics
import com.google.inject.{Inject, Singleton}
import metrics._
import models.{TaxCalculation, TaxYearReconciliation}
import play.api.Mode.Mode
import play.api.http.Status._
import play.api.{Configuration, Environment, Logger}
import services.http.SimpleHttp
import uk.gov.hmrc.domain.Nino
import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse}
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import uk.gov.hmrc.play.bootstrap.http.HttpClient

import scala.concurrent.{ExecutionContext, Future}
import scala.util.control.NonFatal

sealed trait TaxCalculationResponse
case class TaxCalculationSuccessResponse(taxCalculation: TaxCalculation) extends TaxCalculationResponse
case object TaxCalculationNotFoundResponse extends TaxCalculationResponse
case class TaxCalculationUnexpectedResponse(r: HttpResponse) extends TaxCalculationResponse
case class TaxCalculationErrorResponse(cause: Exception) extends TaxCalculationResponse
@Singleton
class TaxCalculationService @Inject()(
  environment: Environment,
  configuration: Configuration,
  val simpleHttp: SimpleHttp,
  val metrics: Metrics,
  val http: HttpClient,
  servicesConfig: ServicesConfig)(implicit ec: ExecutionContext)
    extends HasMetrics {
  val mode: Mode = environment.mode
  val runModeConfiguration: Configuration = configuration
  lazy val taxCalcUrl = servicesConfig.baseUrl("taxcalc")

  
  def getTaxCalculation(nino: Nino, year: Int)(implicit hc: HeaderCarrier): Future[TaxCalculationResponse] =
    withMetricsTimer("get-taxcalc-summary") { t =>
      simpleHttp.get[TaxCalculationResponse](s"$taxCalcUrl/taxcalc/$nino/taxSummary/$year")(
        onComplete = {

          case r if r.status >= 200 && r.status < 300 =>
            Logger.debug(r.body)
            t.completeTimerAndIncrementSuccessCounter()
            TaxCalculationSuccessResponse(r.json.as[TaxCalculation])

          case r if r.status == NOT_FOUND =>
            Logger.debug(r.body)
            t.completeTimerAndIncrementSuccessCounter()
            TaxCalculationNotFoundResponse

          case r =>
            Logger.debug(r.body)
            t.completeTimerAndIncrementFailedCounter()
            Logger.debug(s"Unexpected ${r.status} response getting tax calculation from tax-calculation-service")
            TaxCalculationUnexpectedResponse(r)
        },
        onError = { e =>
          Logger.debug(e.toString)
          t.completeTimerAndIncrementFailedCounter()
          Logger.warn("Error getting tax calculation from tax-calculation-service", e)
          TaxCalculationErrorResponse(e)
        }
      )
    }

  def getTaxYearReconciliations(nino: Nino)(
    implicit headerCarrier: HeaderCarrier): Future[List[TaxYearReconciliation]] =
    http
      .GET[List[TaxYearReconciliation]](s"$taxCalcUrl/taxcalc/$nino/reconciliations")
      .recover {
        case NonFatal(e) =>
          Logger.debug(s"An exception was thrown by taxcalc reconciliations: ${e.getMessage}")
          Nil
      }
} 
Example 74
Source File: LocalSessionCache.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import com.google.inject.{Inject, Singleton}
import config.ConfigDecorator
import javax.inject.Named
import play.api.{Configuration, Environment}
import uk.gov.hmrc.http.cache.client.SessionCache
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import uk.gov.hmrc.play.bootstrap.http.HttpClient

@Singleton
class LocalSessionCache @Inject()(
  environment: Environment,
  configuration: Configuration,
  val appNameConfiguration: Configuration,
  override val http: HttpClient,
  configDecorator: ConfigDecorator,
  servicesConfig: ServicesConfig,
  @Named("appName") appName: String)
    extends SessionCache {
  override lazy val defaultSource = appName
  override lazy val baseUri = servicesConfig.baseUrl("cachable.session-cache")
  override lazy val domain = servicesConfig.getConfString("cachable.session-cache.domain", "keystore")
} 
Example 75
Source File: Module.scala    From Cortex   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.thp.cortex

import java.lang.reflect.Modifier

import com.google.inject.AbstractModule
import net.codingwell.scalaguice.{ScalaModule, ScalaMultibinder}
import play.api.libs.concurrent.AkkaGuiceSupport
import play.api.{Configuration, Environment, Logger, Mode}
import scala.collection.JavaConverters._

import com.google.inject.name.Names
import org.reflections.Reflections
import org.reflections.scanners.SubTypesScanner
import org.reflections.util.ConfigurationBuilder
import org.thp.cortex.models.{AuditedModel, Migration}
import org.thp.cortex.services._

import org.elastic4play.models.BaseModelDef
import org.elastic4play.services.auth.MultiAuthSrv
import org.elastic4play.services.{UserSrv ā‡’ EUserSrv, AuthSrv, MigrationOperations}
import org.thp.cortex.controllers.{AssetCtrl, AssetCtrlDev, AssetCtrlProd}
import services.mappers.{MultiUserMapperSrv, UserMapper}

class Module(environment: Environment, configuration: Configuration) extends AbstractModule with ScalaModule with AkkaGuiceSupport {

  private lazy val logger = Logger(s"module")

  override def configure(): Unit = {
    val modelBindings        = ScalaMultibinder.newSetBinder[BaseModelDef](binder)
    val auditedModelBindings = ScalaMultibinder.newSetBinder[AuditedModel](binder)
    val reflectionClasses = new Reflections(
      new ConfigurationBuilder()
        .forPackages("org.elastic4play")
        .addClassLoader(getClass.getClassLoader)
        .addClassLoader(environment.getClass.getClassLoader)
        .forPackages("org.thp.cortex")
        .setExpandSuperTypes(false)
        .setScanners(new SubTypesScanner(false))
    )

    reflectionClasses
      .getSubTypesOf(classOf[BaseModelDef])
      .asScala
      .filterNot(c ā‡’ Modifier.isAbstract(c.getModifiers))
      .foreach { modelClass ā‡’
        logger.info(s"Loading model $modelClass")
        modelBindings.addBinding.to(modelClass)
        if (classOf[AuditedModel].isAssignableFrom(modelClass)) {
          auditedModelBindings.addBinding.to(modelClass.asInstanceOf[Class[AuditedModel]])
        }
      }

    val authBindings = ScalaMultibinder.newSetBinder[AuthSrv](binder)
    reflectionClasses
      .getSubTypesOf(classOf[AuthSrv])
      .asScala
      .filterNot(c ā‡’ Modifier.isAbstract(c.getModifiers) || c.isMemberClass)
      .filterNot(c ā‡’ c == classOf[MultiAuthSrv] || c == classOf[CortexAuthSrv])
      .foreach { authSrvClass ā‡’
        logger.info(s"Loading authentication module $authSrvClass")
        authBindings.addBinding.to(authSrvClass)
      }

    val ssoMapperBindings = ScalaMultibinder.newSetBinder[UserMapper](binder)
    reflectionClasses
      .getSubTypesOf(classOf[UserMapper])
      .asScala
      .filterNot(c ā‡’ Modifier.isAbstract(c.getModifiers) || c.isMemberClass)
      .filterNot(c ā‡’ c == classOf[MultiUserMapperSrv])
      .foreach(mapperCls ā‡’ ssoMapperBindings.addBinding.to(mapperCls))

    if (environment.mode == Mode.Prod)
      bind[AssetCtrl].to[AssetCtrlProd]
    else
      bind[AssetCtrl].to[AssetCtrlDev]

    bind[EUserSrv].to[UserSrv]
    bind[Int].annotatedWith(Names.named("databaseVersion")).toInstance(models.modelVersion)
    bind[UserMapper].to[MultiUserMapperSrv]

    bind[AuthSrv].to[CortexAuthSrv]
    bind[MigrationOperations].to[Migration]
    bindActor[AuditActor]("audit")
  }
} 
Example 76
Source File: ScaladslWebSocketClient.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.scaladsl.client

import com.lightbend.lagom.internal.client.WebSocketClient
import com.lightbend.lagom.internal.client.WebSocketClientConfig
import com.typesafe.config.Config
import io.netty.channel.EventLoopGroup
import play.api.Environment
import play.api.inject.ApplicationLifecycle

import scala.concurrent.ExecutionContext

private[lagom] class ScaladslWebSocketClient(
    environment: Environment,
    config: WebSocketClientConfig,
    eventLoop: EventLoopGroup,
    lifecycle: ApplicationLifecycle
)(implicit ec: ExecutionContext)
    extends WebSocketClient(environment, config, eventLoop, lifecycle)
    with ScaladslServiceApiBridge {
  // Constructor that manages its own event loop
  def this(environment: Environment, config: WebSocketClientConfig, applicationLifecycle: ApplicationLifecycle)(
      implicit ec: ExecutionContext
  ) = {
    this(environment, config, WebSocketClient.createEventLoopGroup(applicationLifecycle), applicationLifecycle)
  }
} 
Example 77
Source File: JavadslWebSocketClient.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.javadsl.client

import javax.inject.Inject
import javax.inject.Singleton

import com.lightbend.lagom.internal.client.WebSocketClient
import com.lightbend.lagom.internal.client.WebSocketClientConfig
import com.typesafe.config.Config
import io.netty.channel.EventLoopGroup
import play.api.Environment
import play.api.inject.ApplicationLifecycle

import scala.concurrent.ExecutionContext

@Singleton
class JavadslWebSocketClient(
    environment: Environment,
    config: WebSocketClientConfig,
    eventLoop: EventLoopGroup,
    lifecycle: ApplicationLifecycle
)(implicit ec: ExecutionContext)
    extends WebSocketClient(environment, config, eventLoop, lifecycle)
    with JavadslServiceApiBridge {
  // Constructor that manages its own event loop
  @Inject
  def this(environment: Environment, config: Config, applicationLifecycle: ApplicationLifecycle)(
      implicit ec: ExecutionContext
  ) = {
    this(
      environment,
      WebSocketClientConfig(config),
      WebSocketClient.createEventLoopGroup(applicationLifecycle),
      applicationLifecycle
    )
  }
} 
Example 78
Source File: ServiceClientLoader.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.javadsl.client

import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
import com.lightbend.lagom.internal.javadsl.api.JacksonPlaceholderExceptionSerializer
import com.lightbend.lagom.internal.javadsl.api.JacksonPlaceholderSerializerFactory
import com.lightbend.lagom.internal.javadsl.api.ServiceReader
import com.lightbend.lagom.javadsl.api.Service
import com.lightbend.lagom.javadsl.jackson.JacksonExceptionSerializer
import com.lightbend.lagom.javadsl.jackson.JacksonSerializerFactory
import play.api.Environment

@Singleton
class ServiceClientLoader @Inject() (
    jacksonSerializerFactory: JacksonSerializerFactory,
    jacksonExceptionSerializer: JacksonExceptionSerializer,
    environment: Environment,
    implementor: JavadslServiceClientImplementor
) {
  def loadServiceClient[T](interface: Class[T]): T = {
    if (classOf[Service].isAssignableFrom(interface)) {
      val descriptor = ServiceReader.readServiceDescriptor(
        environment.classLoader,
        interface.asSubclass(classOf[Service])
      )
      val resolved = ServiceReader.resolveServiceDescriptor(
        descriptor,
        environment.classLoader,
        Map(JacksonPlaceholderSerializerFactory   -> jacksonSerializerFactory),
        Map(JacksonPlaceholderExceptionSerializer -> jacksonExceptionSerializer)
      )
      implementor.implement(interface, resolved)
    } else {
      throw new IllegalArgumentException("Don't know how to load services that don't implement Service")
    }
  }
}

@Singleton
class ServiceClientProvider[T](interface: Class[T]) extends Provider[T] {
  @Inject private var loader: ServiceClientLoader = _
  lazy val get                                    = loader.loadServiceClient(interface)
} 
Example 79
Source File: CircuitBreakerModule.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.javadsl.client

import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
import akka.actor.ActorSystem
import com.lightbend.lagom.internal.client.CircuitBreakerConfig
import com.lightbend.lagom.internal.client.CircuitBreakerMetricsProviderImpl
import com.lightbend.lagom.internal.client.CircuitBreakerMetricsProviderProvider
import com.lightbend.lagom.internal.spi.CircuitBreakerMetricsProvider
import com.lightbend.lagom.javadsl.client.CircuitBreakersPanel
import play.api.inject.Binding
import play.api.inject.Module
import play.api.Configuration
import play.api.Environment

class CircuitBreakerModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = {
    Seq(
      bind[CircuitBreakersPanel].to[CircuitBreakersPanelImpl],
      bind[CircuitBreakerMetricsProvider].toProvider[CircuitBreakerMetricsProviderProvider],
      bind[CircuitBreakerConfig].toSelf,
      bind[CircuitBreakerMetricsProviderImpl].toSelf
    )
  }
} 
Example 80
Source File: ServiceSupport.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.it

import java.util.Collections
import java.util.function.{ Function => JFunction }

import akka.stream.Materializer
import akka.stream.scaladsl.Source
import org.scalatest.Inside
import play.api.Application
import play.api.Configuration
import play.api.Environment
import play.inject.guice.GuiceApplicationBuilder

import scala.concurrent.Await
import scala.concurrent.duration._
import scala.reflect.ClassTag
import akka.japi.function.Procedure
import com.google.inject.Binder
import com.google.inject.Module
import com.google.inject.TypeLiteral
import com.lightbend.lagom.javadsl.testkit.ServiceTest
import com.lightbend.lagom.javadsl.testkit.ServiceTest.TestServer
import play.api.routing.Router
import java.util

import com.lightbend.lagom.internal.testkit.EmptyAdditionalRoutersModule
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

sealed trait HttpBackend {
  final val provider: String = s"play.core.server.${codeName}ServerProvider"
  val codeName: String
}

case object AkkaHttp extends HttpBackend {
  val codeName = "AkkaHttp"
}

case object Netty extends HttpBackend {
  val codeName = "Netty"
}

trait ServiceSupport extends AnyWordSpecLike with Matchers with Inside {
  def withServer(
      configureBuilder: GuiceApplicationBuilder => GuiceApplicationBuilder
  )(block: Application => Unit)(implicit httpBackend: HttpBackend): Unit = {
    val jConfigureBuilder = new JFunction[GuiceApplicationBuilder, GuiceApplicationBuilder] {
      override def apply(b: GuiceApplicationBuilder): GuiceApplicationBuilder = {
        configureBuilder(b)
          .overrides(EmptyAdditionalRoutersModule)
          .configure("play.server.provider", httpBackend.provider)
      }
    }
    val jBlock = new Procedure[TestServer] {
      override def apply(server: TestServer): Unit = {
        block(server.app.asScala())
      }
    }
    val setup = ServiceTest.defaultSetup.configureBuilder(jConfigureBuilder).withCluster(false)
    ServiceTest.withServer(setup, jBlock)
  }

  def withClient[T: ClassTag](
      configureBuilder: GuiceApplicationBuilder => GuiceApplicationBuilder
  )(block: Application => T => Unit)(implicit httpBackend: HttpBackend): Unit = {
    withServer(configureBuilder) { application =>
      val client = application.injector.instanceOf[T]
      block(application)(client)
    }
  }

  implicit def materializer(implicit app: Application): Materializer = app.materializer

  def consume[T](source: Source[T, _])(implicit mat: Materializer): List[T] = {
    Await.result(source.runFold(List.empty[T])((list, t) => t :: list), 10.seconds).reverse
  }
} 
Example 81
Source File: ProjectionRegistryModule.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.javadsl.projection

import java.util.concurrent.CompletionStage

import akka.actor.ActorSystem
import akka.annotation.ApiMayChange
import akka.annotation.InternalApi
import com.lightbend.lagom.internal.projection.ProjectionRegistry
import com.lightbend.lagom.internal.projection.ProjectionRegistryActor.WorkerCoordinates
import com.lightbend.lagom.projection.State
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
import play.api.Configuration
import play.api.Environment
import play.api.inject.Binding
import play.api.inject.Module

import scala.compat.java8.FutureConverters
import scala.concurrent.ExecutionContext


private class ProjectionsImpl @Inject() (registry: ProjectionRegistry)(
    implicit executionContext: ExecutionContext
) extends Projections {
  import FutureConverters._

  override def getStatus(): CompletionStage[State] =
    registry.getState().toJava

  override def stopAllWorkers(projectionName: String): Unit =
    registry.stopAllWorkers(projectionName)

  override def stopWorker(projectionName: String, tagName: String): Unit =
    registry.stopWorker(WorkerCoordinates(projectionName, tagName))

  override def startAllWorkers(projectionName: String): Unit =
    registry.startAllWorkers(projectionName)

  override def startWorker(projectionName: String, tagName: String): Unit =
    registry.startWorker(WorkerCoordinates(projectionName, tagName))
} 
Example 82
Source File: LagomDevModeSSLHolder.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.devmode.ssl

import java.io.File
import java.security.KeyStore

import com.typesafe.sslconfig.ssl.FakeKeyStore
import com.typesafe.sslconfig.ssl.FakeSSLTools
import com.typesafe.sslconfig.util.NoopLogger
import com.typesafe.sslconfig.{ ssl => sslconfig }
import javax.net.ssl._
import play.api.Environment


case class KeyStoreMetadata(
    storeFile: File,
    storeType: String,
    storePassword: Array[Char]
)

class LagomDevModeSSLHolder(val rootLagomProjectFolder: File) {
  def this(env: Environment) = {
    this(env.rootPath)
  }

  private val fakeKeysStore = new sslconfig.FakeKeyStore(NoopLogger.factory())
  val keyStore: KeyStore    = fakeKeysStore.createKeyStore(rootLagomProjectFolder)

  val keyStoreMetadata: KeyStoreMetadata = KeyStoreMetadata(
    fakeKeysStore.getKeyStoreFilePath(rootLagomProjectFolder),
    FakeKeyStore.KeystoreSettings.KeystoreType,
    FakeKeyStore.KeystoreSettings.keystorePassword
  )
  val trustStoreMetadata: KeyStoreMetadata = keyStoreMetadata

  val (sslContext: SSLContext, trustManager: X509TrustManager) = FakeSSLTools.buildContextAndTrust(keyStore)
} 
Example 83
Source File: LagomPlayModule.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.play

import java.util.{ List => JList }
import java.util.Optional
import javax.inject.Inject

import com.lightbend.lagom.internal.javadsl.registry.ServiceRegistry
import com.lightbend.lagom.internal.javadsl.registry.ServiceRegistryService
import com.lightbend.lagom.devmode.internal.registry.serviceDnsRecords
import com.lightbend.lagom.javadsl.api.ServiceAcl
import com.lightbend.lagom.javadsl.api.ServiceInfo
import com.lightbend.lagom.javadsl.api.transport.Method
import com.typesafe.config.Config
import play.api.inject.ApplicationLifecycle
import play.api.inject.Binding
import play.api.inject.Module
import play.api.Configuration
import play.api.Environment
import play.api.Logger

import scala.collection.JavaConverters._
import scala.compat.java8.FutureConverters._
import scala.util.Success
import scala.util.Try

class LagomPlayModule extends Module {
  private val logger = Logger(this.getClass)

  override def bindings(environment: Environment, config: Configuration): Seq[Binding[_]] = {
    val maybeServiceInfoBinding: Option[Binding[ServiceInfo]] = prepareServiceInfoBinding(config.underlying)
    val playRegistry                                          = bind[PlayRegisterWithServiceRegistry].toSelf.eagerly()

    Seq(
      playRegistry
    ) ++ maybeServiceInfoBinding.toList
  }

  private def prepareServiceInfoBinding(config: Config) = {
    val triedServiceName                   = Try(config.getString("lagom.play.service-name"))
    val triedAcls: Try[JList[_ <: Config]] = Try(config.getConfigList("lagom.play.acls"))

    val warning = "Service setup via 'application.conf' is deprecated. Remove 'lagom.play.service-name' and/or " +
      "'lagom.play.acls' and use 'bindServiceInfo' on your Guice's Module class."

    val maybeServiceInfoBinding = (triedServiceName, triedAcls) match {
      case (Success(serviceName), Success(aclList)) => {
        logger.warn(warning)
        // create a ServiceInfo in case user doesn't see the warning
        val acls = parseAclList(aclList)
        Some(bind[ServiceInfo].toInstance(ServiceInfo.of(serviceName, acls: _*)))
      }
      case (Success(serviceName), _) => {
        logger.warn(warning)
        // create a ServiceInfo in case user doesn't see the warning
        Some(bind[ServiceInfo].toInstance(ServiceInfo.of(serviceName)))
      }
      case (_, Success(_)) => {
        logger.warn(warning)
        // can't create a ServiceInfo because service-name is missing
        None
      }
      case _ => None
    }
    maybeServiceInfoBinding
  }

  private def parseAclList(aclList: JList[_ <: Config]): Seq[ServiceAcl] = {
    aclList.asScala.map { aclConfig =>
      val method = if (aclConfig.hasPath("method")) {
        Optional.of(new Method(aclConfig.getString("method")))
      } else Optional.empty[Method]
      val pathRegex = if (aclConfig.hasPath("path-regex")) {
        Optional.of(aclConfig.getString("path-regex"))
      } else Optional.empty[String]
      new ServiceAcl(method, pathRegex)
    }.toSeq
  }
}

class PlayRegisterWithServiceRegistry @Inject() (
    config: Config,
    serviceInfo: ServiceInfo,
    serviceRegistry: ServiceRegistry,
    applicationLifecycle: ApplicationLifecycle
) {
  val uris = serviceDnsRecords(config)

  private val serviceAcls = serviceInfo.getAcls
  private val service     = ServiceRegistryService.of(uris.asJava, serviceAcls)
  // TODO: fix -> this register operation is registering all ACLs under the microservice name, not under each locatable service name. Will lead to unlocatable.
  serviceRegistry.register(serviceInfo.serviceName()).invoke(service)

  applicationLifecycle.addStopHook(() => serviceRegistry.unregister(serviceInfo.serviceName()).invoke().toScala)
} 
Example 84
Source File: ServiceRegistrationModule.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.server

import java.net.URI
import java.util.function.{ Function => JFunction }

import akka.actor.CoordinatedShutdown
import akka.Done
import akka.NotUsed
import com.lightbend.lagom.internal.javadsl.registry.ServiceRegistry
import com.lightbend.lagom.internal.javadsl.registry.ServiceRegistryService
import com.lightbend.lagom.internal.javadsl.server.ResolvedServices
import com.lightbend.lagom.devmode.internal.registry.serviceDnsRecords
import com.typesafe.config.Config
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
import play.api.inject.Binding
import play.api.inject.Module
import play.api.Configuration
import play.api.Environment
import play.api.Logger

import scala.compat.java8.FutureConverters.CompletionStageOps
import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import scala.collection.JavaConverters._
import scala.collection.immutable

class ServiceRegistrationModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = Seq(
    bind[ServiceRegistrationModule.RegisterWithServiceRegistry].toSelf.eagerly(),
    bind[ServiceRegistrationModule.ServiceConfig].toProvider[ServiceRegistrationModule.ServiceConfigProvider]
  )
}

object ServiceRegistrationModule {
  class ServiceConfigProvider @Inject() (config: Config) extends Provider[ServiceConfig] {
    override lazy val get = ServiceConfig(serviceDnsRecords(config))
  }

  case class ServiceConfig(uris: immutable.Seq[URI])

  
  @Singleton
  private class RegisterWithServiceRegistry @Inject() (
      coordinatedShutdown: CoordinatedShutdown,
      resolvedServices: ResolvedServices,
      config: ServiceConfig,
      registry: ServiceRegistry
  )(implicit ec: ExecutionContext) {
    private lazy val logger: Logger = Logger(this.getClass())

    private val locatableServices = resolvedServices.services.filter(_.descriptor.locatableService)

    coordinatedShutdown.addTask(
      CoordinatedShutdown.PhaseBeforeServiceUnbind,
      "unregister-services-from-service-locator-javadsl"
    ) { () =>
      Future
        .sequence(locatableServices.map { service =>
          registry.unregister(service.descriptor.name).invoke().toScala
        })
        .map(_ => Done)
    }

    locatableServices.foreach { service =>
      val c = ServiceRegistryService.of(config.uris.asJava, service.descriptor.acls)
      registry
        .register(service.descriptor.name)
        .invoke(c)
        .exceptionally(new JFunction[Throwable, NotUsed] {
          def apply(t: Throwable) = {
            logger
              .error(s"Service name=[${service.descriptor.name}] couldn't register itself to the service locator.", t)
            NotUsed.getInstance()
          }
        })
    }
  }
} 
Example 85
Source File: Bindings.scala    From dependency   with MIT License 5 votes vote down vote up
package io.flow.dependency.api.lib

import play.api.inject.Module
import play.api.{Configuration, Environment, Mode}

class GithubModule extends Module {

  def bindings(env: Environment, conf: Configuration) = {
    env.mode match {
      case Mode.Prod | Mode.Dev => Seq(
        bind[Github].to[DefaultGithub]
      )
      case Mode.Test => Seq(
        bind[Github].to[MockGithub]
      )
    }
  }

} 
Example 86
Source File: Bindings.scala    From dependency   with MIT License 5 votes vote down vote up
package io.flow.dependency.www.lib

import play.api.{Configuration, Environment, Mode}
import play.api.inject.Module

class DependencyClientProviderModule extends Module {

  def bindings(env: Environment, conf: Configuration) = {
    env.mode match {
      case Mode.Prod | Mode.Dev => Seq(
        bind[DependencyClientProvider].to[DefaultDependencyClientProvider]
      )
      case Mode.Test => Seq(
        // TODO: Add mock
        bind[DependencyClientProvider].to[DependencyClientProvider]
      )
    }
  }

} 
Example 87
Source File: AddressLookupService.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import com.kenshoo.play.metrics.Metrics
import config.ConfigDecorator
import com.google.inject.{Inject, Singleton}
import metrics._
import models.addresslookup.RecordSet
import play.api.Mode.Mode
import play.api.{Configuration, Environment, Logger}
import services.http.SimpleHttp
import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse}
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import util._

import scala.concurrent.Future

sealed trait AddressLookupResponse

final case class AddressLookupSuccessResponse(addressList: RecordSet) extends AddressLookupResponse
final case class AddressLookupUnexpectedResponse(r: HttpResponse) extends AddressLookupResponse
final case class AddressLookupErrorResponse(cause: Exception) extends AddressLookupResponse

@Singleton
class AddressLookupService @Inject()(
  environment: Environment,
  configuration: Configuration,
  configDecorator: ConfigDecorator,
  val simpleHttp: SimpleHttp,
  val metrics: Metrics,
  val tools: Tools,
  servicesConfig: ServicesConfig)
    extends HasMetrics {

  val mode: Mode = environment.mode
  val runModeConfiguration: Configuration = configuration
  lazy val addressLookupUrl = servicesConfig.baseUrl("address-lookup")

  def lookup(postcode: String, filter: Option[String] = None)(
    implicit hc: HeaderCarrier): Future[AddressLookupResponse] =
    withMetricsTimer("address-lookup") { t =>
      val hn = tools.urlEncode(filter.getOrElse(""))
      val pc = postcode.replaceAll(" ", "")
      val newHc = hc.withExtraHeaders("X-Hmrc-Origin" -> configDecorator.origin)

      simpleHttp.get[AddressLookupResponse](s"$addressLookupUrl/v1/gb/addresses.json?postcode=$pc&filter=$hn")(
        onComplete = {
          case r if r.status >= 200 && r.status < 300 =>
            t.completeTimerAndIncrementSuccessCounter()
            AddressLookupSuccessResponse(RecordSet.fromJsonAddressLookupService(r.json))

          case r =>
            t.completeTimerAndIncrementFailedCounter()
            Logger.warn(s"Unexpected ${r.status} response getting address record from address lookup service")
            AddressLookupUnexpectedResponse(r)
        },
        onError = {
          case e =>
            t.completeTimerAndIncrementFailedCounter()
            Logger.warn("Error getting address record from address lookup service", e)
            AddressLookupErrorResponse(e)
        }
      )(newHc)
    }
} 
Example 88
Source File: AssetCtrl.scala    From Cortex   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.thp.cortex.controllers

import javax.inject.{Inject, Singleton}
import play.api.http.{FileMimeTypes, HttpErrorHandler}
import play.api.mvc.{Action, AnyContent}
import controllers.{Assets, AssetsMetadata, ExternalAssets}
import play.api.Environment

import scala.concurrent.ExecutionContext

trait AssetCtrl {
  def get(file: String): Action[AnyContent]
}

@Singleton
class AssetCtrlProd @Inject()(errorHandler: HttpErrorHandler, meta: AssetsMetadata) extends Assets(errorHandler, meta) with AssetCtrl {
  def get(file: String): Action[AnyContent] = at("/www", file)
}

@Singleton
class AssetCtrlDev @Inject()(environment: Environment)(implicit ec: ExecutionContext, fileMimeTypes: FileMimeTypes)
    extends ExternalAssets(environment)
    with AssetCtrl {
  def get(file: String): Action[AnyContent] = at("www/dist", file)
} 
Example 89
Source File: LoginControllerSpec.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers

import model.json.LoginJson
import model.{Computer, Role, User}
import org.mockito.Matchers._
import org.mockito.Mockito._
import play.api.Environment
import play.api.i18n.MessagesApi
import services.state.ActionState
import services.{UserService, state}
import test.ControllerTest

import scala.concurrent.{ExecutionContext, Future}


  def mockUserService(actionState: ActionState): UserService = {
    // Mock the computer service
    lazy val userService = mock[UserService]

    val user = if(actionState == state.ActionCompleted){
      Some(userToBeUsed)
    } else {
      None
    }

    // This state will be used for methods that don't have other states that ActionCompleted and Failed
    val alternativeState = if(actionState!=state.ActionCompleted){
      state.Failed
    } else {
      actionState
    }

    when(userService.checkAndGet(any[LoginJson])) thenReturn(Future.successful(user))
    when(userService.checkAndGet(any[String],any[String])) thenReturn(Future.successful(user))
    when(userService.add(any[User])) thenReturn(Future.successful(actionState))
    when(userService.get(any[String])) thenReturn(Future.successful(user))
    when(userService.listAll) thenReturn(Future.successful(userList))

    userService
  }
} 
Example 90
Source File: LaboratoryControllerSuccessfulSpec.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers.admin

import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import org.mockito.Matchers.any
import org.mockito.Mockito.when
import com.google.inject.ImplementedBy
import com.google.inject.Inject
import jp.t2v.lab.play2.auth.test.Helpers.AuthFakeRequest
import model.Laboratory
import model.Role
import model.User
import model.form.LaboratoryForm
import model.form.data.LaboratoryFormData
import model.json.{LaboratoryJson, LoginJson}
import play.api.Environment
import play.api.i18n.MessagesApi
import play.api.libs.json.Json
import play.api.test.FakeRequest
import play.test.WithApplication
import services.LaboratoryService
import services.RoomService
import services.UserService
import services.impl.LaboratoryServiceImpl
import services.state
import services.state.ActionState
import test.ControllerTest


class LaboratoryControllerSuccessfulSpec extends LaboratoryControllerSpec {
  val labService: LaboratoryService = mockLaboratoryService(state.ActionCompleted)
  // Controller to be tested, with the dependencies
  lazy val controller = new LaboratoryController(labService, messagesApi)(userService, executionContext, environment)

  "Laboratory Controller on successful operations" should {
    "return Ok <200> status on receiving an edited laboratory" in {
      import laboratory._
      val laboratoryData = LaboratoryFormData(name, location, administration)
      val laboratoryForm = LaboratoryForm.form.fill(laboratoryData)
      val result = controller.update.apply {
        FakeRequest()
          .withLoggedIn(controller)(loggedInUser)
          .withJsonBody(Json.toJson(laboratory))
      }
      assertFutureResultStatus(result, 200)
    }

    "return Ok <200> status on deleting a laboratory" in {
      val result = controller.delete(laboratory.id).apply {
        FakeRequest()
          .withLoggedIn(controller)(LoginJson("admin", "adminaton"))
      }
      assertFutureResultStatus(result, 200)
    }

    "return Ok <200> status on adding a new laboratory" in {
      import laboratory._
      val laboratoryData = LaboratoryJson(name, location, administration)
      val result = controller.add.apply {
        FakeRequest()
          .withLoggedIn(controller)(loggedInUser)
          .withJsonBody(Json.toJson(laboratoryData))
      }
      assertFutureResultStatus(result, 200)
    }

    "return Ok <200> status when listing all laboratories" in pending
    "return laboratory list json when listing all laboratories" in pending
  }
} 
Example 91
Source File: HomeController.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers

import akka.actor.{ActorRef, ActorSystem}
import com.google.inject.name.Named
import com.google.inject.{Inject, Singleton}
import dao.{DatabaseInitializer, LaboratoryDAO, UserDAO}
import model.{Role, User}
import play.api.{Environment, Logger}
import play.api.i18n.MessagesApi
import services.{LaboratoryService, UserService}
import views.html._

import scala.concurrent.{Await, ExecutionContext}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._


@Singleton
class HomeController @Inject()(databaseInitializer: DatabaseInitializer, laboratoryService : LaboratoryService, @Named("computerChecker") computerChecker: ActorRef, actorSystem: ActorSystem)(implicit userService: UserService, executionContext: ExecutionContext, environment: Environment) extends ControllerWithNoAuthRequired {
  val logger = Logger("HomeController")

  play.Logger.debug("Configuring Computer Checker...")
  actorSystem.scheduler.schedule(0.microseconds,5.minutes, computerChecker,"Execute")
  play.Logger.debug("Computer Checker configured.")

  logger.debug("Initializing database")
  Await.result(databaseInitializer.initialize(), 2.seconds)
  logger.debug("Database initialized")

  def home = AsyncStack { implicit request =>
    play.Logger.debug("Logged user: " + loggedIn)
    implicit val (username: Option[String], isAdmin: Boolean) = loggedIn match {
      case Some(User(usernameString, password, Some(name), role)) => (Some(name), role == Role.Administrator)
      case Some(User(usernameString, password, None, role)) => (Some(usernameString), role == Role.Administrator)
      case _ => (None, false)
    }
    logger.debug("PeticiĆ³n de listar todos los laboratorios con el siguiente request recibida " + request)
    logger.debug("User: " + username + ", is admin: " + isAdmin)
    laboratoryService.listAll.map { _ =>
      Ok(index("Aton"))
    }
  }

  def about = StackAction { implicit request =>
    implicit val (username: Option[String], isAdmin: Boolean) = loggedIn match {
      case Some(User(usernameString, password, Some(name), role)) => (Some(name), role == Role.Administrator)
      case Some(User(usernameString, password, None, role)) => (Some(usernameString), role == Role.Administrator)
      case _ => (None, false)
    }

    Ok//(index(messagesApi("about"),views.html.about()))
  }
} 
Example 92
Source File: SuggestionController.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers

import java.sql.Timestamp
import java.util.Calendar

import com.google.inject.Inject
import model.form.SuggestionForm
import model.{Role, Suggestion}
import play.api.Environment
import play.api.i18n.MessagesApi
import services.{SuggestionService, UserService, state}
import views.html._

import scala.concurrent.{ExecutionContext, Future}


class SuggestionController @Inject()(suggestionService: SuggestionService, val messagesApi: MessagesApi)(implicit userService: UserService, executionContext: ExecutionContext, environment: Environment) extends ControllerWithNoAuthRequired {
  def home = AsyncStack { implicit request =>
    implicit val (username: Option[String], isAdmin: Boolean) = loggedIn match {
      case Some(user) => (Some(user.username), user.role == Role.Administrator)
      case _ => (None, false)
    }
    if (isAdmin) {
      suggestionService.listAll.map { suggestions =>
        Ok//(index(messagesApi("suggestion"), suggestionHome(SuggestionForm.form, suggestions)))
      }
    } else {
      Future.successful(Ok)//(index(messagesApi("suggestion"), suggestionHome(SuggestionForm.form, Seq.empty[Suggestion]))))
    }


  }

  def add = AsyncStack() { implicit request =>
    implicit val (username: Option[String], isAdmin: Boolean) = loggedIn match {
      case Some(user) => (Some(user.username), user.role == Role.Administrator)
      case _ => (None, false)
    }
    SuggestionForm.form.bindFromRequest().fold(
      errorForm => Future.successful(Ok(errorForm.toString)),
      data => {
        val text = data.suggestion
        val suggestion = Suggestion(0, text, now, username)
        suggestionService.add(suggestion).map {
          case state.ActionCompleted => Redirect(routes.SuggestionController.home())
          case _ => BadRequest
        }
      }
    )
  }

  private def now = new Timestamp(Calendar.getInstance().getTime.getTime)
} 
Example 93
Source File: LaboratoryController.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers

import com.google.inject.Inject
import model.Role
import play.api.Environment
import play.api.i18n.MessagesApi
import play.api.libs.json.Json
import play.api.mvc.{Action, AnyContent}
import services.{LaboratoryService, UserService}

import scala.concurrent.ExecutionContext


class LaboratoryController @Inject()(laboratoryService: LaboratoryService, val messagesApi: MessagesApi)(implicit userService: UserService, environment: Environment, executionContext: ExecutionContext) extends ControllerWithNoAuthRequired {

  def getAll: Action[AnyContent] = Action.async { implicit request=>
    laboratoryService.listAll.map(result => {
      Ok(Json.toJson(result))
    })
  }

  def get(id: Long) = AsyncStack { implicit request =>
    implicit val (username: Option[String], isAdmin: Boolean) = loggedIn match {
      case Some(user) => (Some(user.username), user.role == Role.Administrator)
      case _ => (None, false)
    }
    laboratoryService.get(id).map {
      case Some((laboratoryObject, roomsWithComputers)) => Ok(Json.toJson((laboratoryObject, roomsWithComputers)))
      case _ => NotImplemented//index(messagesApi("laboratory.notFound"),notImplemented(messagesApi("laboratory.notFound"))))
    }
  }

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

import com.google.inject.Inject
import controllers.{routes => normalroutes}
import model.json.{LaboratoryJson, ResultMessage}
import model.{Laboratory, Role}
import play.Logger
import play.api.Environment
import play.api.i18n.MessagesApi
import play.api.libs.json.{JsError, JsSuccess, Json}
import services.{LaboratoryService, UserService, state}

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


class LaboratoryController @Inject()(laboratoryService: LaboratoryService, val messagesApi: MessagesApi)(implicit userService: UserService, executionContext: ExecutionContext, environment: Environment) extends ControllerWithAuthRequired {

  def update = AuthRequiredAction { implicit request =>
    implicit val username = Some(loggedIn.username)
    implicit val isAdmin = loggedIn.role == Role.Administrator
    // TODO: Get id from json
    request.body.asJson match {
      case Some(json) => json.validate[Laboratory] match {
        case JsSuccess(laboratory, _) =>
          laboratoryService.update(laboratory).map {
            case state.ActionCompleted => Ok(Json.toJson(new ResultMessage("Laboratory updated")))
            case state.NotFound => NotFound(Json.toJson(ResultMessage("Laboratory not found",Seq(("id", laboratory.id.toString)))))
            case _ => BadRequest(Json.toJson(new ResultMessage("Could not add that laboratory")))
          }
        case JsError(errors) =>Future.successful(BadRequest(Json.toJson(ResultMessage.wrongJsonFormat(errors))))
      }
      case _ => Future.successful(BadRequest(Json.toJson(ResultMessage.inputWasNotAJson)))
    }
  }

  def add = AuthRequiredAction { implicit request =>
    Logger.debug("Adding laboratory... ")
    implicit val username = Some(loggedIn.username)
    implicit val isAdmin = loggedIn.role == Role.Administrator
    request.body.asJson match {
      case Some(json) => json.validate[LaboratoryJson] match {
        case JsSuccess(laboratory, _) =>
          val newLaboratory = Laboratory(0, laboratory.name, laboratory.location, laboratory.administration)
          laboratoryService.add(newLaboratory).map {
            case state.ActionCompleted => Ok(Json.toJson(new ResultMessage("Laboratory added")))
            case _ => BadRequest(Json.toJson(new ResultMessage("Could not add that laboratory")))

          }
        case JsError(errors) =>Future.successful(BadRequest(Json.toJson(ResultMessage.wrongJsonFormat(errors))))
      }
      case _ => Future.successful(BadRequest(Json.toJson(ResultMessage.inputWasNotAJson)))
    }
  }

  def delete(id: Long) = AuthRequiredAction { implicit request =>
    laboratoryService.delete(id) map {
      case state.ActionCompleted => Ok(Json.toJson(new ResultMessage("Laboratory deleted successfully")))
      case state.NotFound => NotFound(Json.toJson(new ResultMessage("Laboratory not found")))
      case _ => BadRequest(Json.toJson(new ResultMessage("A server problem occurred while trying to delete the laboratory")))
    }
  }
} 
Example 95
Source File: SSHOrderController.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers.admin

import com.google.inject.Inject
import controllers.{routes => normalroutes}
import dao.{SSHOrderDAO, UserDAO}
import play.api.Environment
import play.api.i18n.MessagesApi
import services.{SSHOrderService, UserService, state}
import views.html._

import scala.concurrent.ExecutionContext


class SSHOrderController @Inject()(sSHOrderService: SSHOrderService, val messagesApi: MessagesApi)(implicit executionContext: ExecutionContext, userService: UserService, environment: Environment) extends ControllerWithAuthRequired {

  def listAll = AuthRequiredAction { implicit request =>
    implicit val username = Some(loggedIn.username)
    sSHOrderService.listAll.map {res=>
      Ok//(index(messagesApi("sshorders"),sshOrders(res.take(20))))
    }
  }

  def get(id: Long) = AuthRequiredAction { implicit request =>
    implicit val username = Some(loggedIn.username)
    sSHOrderService.get(id).map {res=>
      Ok//(index(messagesApi("sshorder"),sshOrder(res)))
    }
  }

  def delete(id: Long) = AuthRequiredAction { implicit request =>
    implicit val username = Some(loggedIn.username)
    sSHOrderService.delete(id).map {
      case state.ActionCompleted => Ok("OK")
      case _ => BadRequest
    }
  }
} 
Example 96
Source File: RoomController.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers.admin

import com.google.inject.Inject
import controllers.{routes => normalroutes}
import model.Room
import model.json.ResultMessage
import play.Logger
import play.api.Environment
import play.api.i18n.MessagesApi
import play.api.libs.json.{JsError, JsSuccess, Json}
import services.{LaboratoryService, RoomService, UserService, state}

import scala.concurrent.{ExecutionContext, Future}


class RoomController @Inject()(roomService: RoomService, laboratoryService: LaboratoryService, val messagesApi: MessagesApi)(implicit userService: UserService, executionContext: ExecutionContext, environment: Environment) extends ControllerWithAuthRequired {

  def add = AuthRequiredAction { implicit request =>
    implicit val username = Some(loggedIn.username)
    Logger.debug("Adding room... ")
    request.body.asJson match {
      case Some(json) => json.validate[Room] match {
        case JsSuccess(room, _) => roomService.add(room).map {
          case state.ActionCompleted => Ok(Json.toJson(new ResultMessage("Room added")))
          case _ => BadRequest(Json.toJson(new ResultMessage("Could not add that room")))
        }
        case JsError(errors) => Future.successful(BadRequest(Json.toJson(ResultMessage.wrongJsonFormat(errors))))
      }
      case _ => Future.successful(BadRequest(Json.toJson(ResultMessage.inputWasNotAJson)))
    }
  }

  def update = AuthRequiredAction { implicit request =>
    implicit val username = Some(loggedIn.username)
    Logger.debug("Updating room... ")
    request.body.asJson match {
      case Some(json) => json.validate[Room] match {
        case JsSuccess(room, _) => roomService.update(room).map {
          case state.ActionCompleted => Ok(Json.toJson(new ResultMessage("Room updated")))
          case state.NotFound => NotFound(Json.toJson( ResultMessage("Room not found", Seq(("id", room.id.toString)))))
          case _ => BadRequest(Json.toJson(new ResultMessage("Could not update that room")))
        }
        case JsError(errors) => Future.successful(BadRequest(Json.toJson(ResultMessage.wrongJsonFormat(errors))))
      }
      case _ => Future.successful(BadRequest(Json.toJson(ResultMessage.inputWasNotAJson)))
    }
  }

  def delete(roomId: Long) = AuthRequiredAction { implicit request =>
    roomService.delete(roomId).map {
      case state.ActionCompleted => Redirect(normalroutes.HomeController.home())
      case state.NotFound => NotFound
      case _ => BadRequest
    }
  }

  def blockUser(roomId: Long) = AuthRequiredAction { implicit request =>
    // TODO: Processing Not Yet Implemented
    val results = for {
      roomResult <- roomService.get(roomId)
    } yield roomResult
    results.map { result: Option[Room] =>
      if (result.isDefined)
        Redirect(normalroutes.LaboratoryController.get(result.get.laboratoryID))
      else
        NotFound
    }
  }
} 
Example 97
Source File: DatabaseModule.scala    From dr-cla   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package modules

import com.github.mauricio.async.db.SSLConfiguration
import com.github.mauricio.async.db.pool.{PartitionedConnectionPool, PoolConfiguration}
import com.github.mauricio.async.db.postgresql.pool.PostgreSQLConnectionFactory
import com.github.mauricio.async.db.postgresql.util.URLParser
import io.getquill.{PostgresAsyncContext, SnakeCase}
import javax.inject.{Inject, Singleton}
import org.slf4j.LoggerFactory
import play.api.inject.{ApplicationLifecycle, Binding, Module}
import play.api.{Configuration, Environment}

import scala.concurrent.ExecutionContext

class DatabaseModule extends Module {
  def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = {
    Seq(
      bind[Database].to[DatabaseImpl]
    )
  }
}

trait Database {
  val ctx: PostgresAsyncContext[SnakeCase]
}

@Singleton
class DatabaseImpl @Inject()(lifecycle: ApplicationLifecycle, playConfig: Configuration) (implicit ec: ExecutionContext) extends Database {

  private val log = LoggerFactory.getLogger(this.getClass)

  private val maybeDbUrl = playConfig.getOptional[String]("db.default.url")

  private val config = maybeDbUrl.map(URLParser.parse(_)).getOrElse(URLParser.DEFAULT)

  private val configWithMaybeSsl = playConfig.getOptional[String]("db.default.sslmode").fold(config) { sslmode =>
    val sslConfig = SSLConfiguration(Map("sslmode" -> sslmode))
    config.copy(ssl = sslConfig)
  }

  private val connectionFactory = new PostgreSQLConnectionFactory(configWithMaybeSsl)

  private val defaultPoolConfig = PoolConfiguration.Default

  private val maxObjects = playConfig.getOptional[Int]("db.default.max-objects").getOrElse(defaultPoolConfig.maxObjects)
  private val maxIdleMillis = playConfig.getOptional[Long]("db.default.max-idle-millis").getOrElse(defaultPoolConfig.maxIdle)
  private val maxQueueSize = playConfig.getOptional[Int]("db.default.max-queue-size").getOrElse(defaultPoolConfig.maxQueueSize)
  private val validationInterval = playConfig.getOptional[Long]("db.default.max-queue-size").getOrElse(defaultPoolConfig.validationInterval)

  private val poolConfig = new PoolConfiguration(maxObjects, maxIdleMillis, maxQueueSize, validationInterval)

  private val numberOfPartitions = playConfig.getOptional[Int]("db.default.number-of-partitions").getOrElse(4)

  private val pool = new PartitionedConnectionPool(
    connectionFactory,
    poolConfig,
    numberOfPartitions,
    ec
  )

  lifecycle.addStopHook { () =>
    pool.close
  }

  val ctx = new PostgresAsyncContext(SnakeCase, pool)

} 
Example 98
Source File: ViewHelpers.scala    From dr-cla   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package helpers

import java.net.URL

import javax.inject.Inject
import play.api.{Configuration, Environment}

import scala.io.Source
import scala.util.Try

class ViewHelpers @Inject()
(configuration: Configuration, environment: Environment) {
  val organizationName = configuration.get[String]("app.organization.name")
  val maybeOrganizationLogoUrl = configuration.getOptional[String]("app.organization.logo-url")
  val maybeOrganizationUrl = configuration.getOptional[String]("app.organization.url")
  val maybeOrganizationClaUrl = configuration.getOptional[String]("app.organization.cla-url")

  val claText: String = {
    maybeOrganizationClaUrl
      .flatMap(claUrl => Try(new URL(claUrl)).toOption)
      .orElse(environment.resource("sample-cla.html"))
      .map { claUrl =>
        val text = Source.fromURL(claUrl)
        text.mkString
      } getOrElse {
        throw new Exception("You must set the ORG_CLA environment variable.")
      }
  }
}