play.api.libs.concurrent.Execution.Implicits.defaultContext Scala Examples
The following examples show how to use play.api.libs.concurrent.Execution.Implicits.defaultContext.
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: ServiceSpec.scala From daf with BSD 3-Clause "New" or "Revised" License | 5 votes |
import java.io.{IOException, File => JFile} import java.net.ServerSocket import java.util.Base64 import it.gov.daf.securitymanager.client.Security_managerClient import org.specs2.mutable.Specification import play.api.Application import play.api.inject.guice.GuiceApplicationBuilder import play.api.libs.ws.ahc.AhcWSClient import play.api.libs.ws.{WSAuthScheme, WSResponse} import play.api.test.{WithServer, WsTestClient} import scala.concurrent.Await import play.api.libs.concurrent.Execution.Implicits.defaultContext import scala.concurrent.duration.Duration //@SuppressWarnings(Array("org.wartremover.warts.NonUnitStatements", "org.wartremover.warts.Throw")) class ServiceSpec extends Specification { def getAvailablePort: Int = { try { val socket = new ServerSocket(0) try { socket.getLocalPort } finally { socket.close() } } catch { case e: IOException => throw new IllegalStateException(s"Cannot find available port: ${e.getMessage}", e) } } def application: Application = GuiceApplicationBuilder(). configure("pac4j.authenticator" -> "test"). build() "The security_manager" should { "manage user tokens correctly" in new WithServer(app = application, port = getAvailablePort) { private val token = WsTestClient.withClient { implicit client => val response: WSResponse = Await.result[WSResponse](client. url(s"http://localhost:$port/security-manager/v1/token"). withAuth("david", "david", WSAuthScheme.BASIC). execute, Duration.Inf) response.body } val ws: AhcWSClient = AhcWSClient() val plainCreds = "david:david" val plainCredsBytes = plainCreds.getBytes val base64CredsBytes = Base64.getEncoder.encode(plainCredsBytes) val base64Creds = new String(base64CredsBytes) val client = new Security_managerClient(ws)(s"http://localhost:$port") val token2 = Await.result(client.token(s"Basic $base64Creds"), Duration.Inf) s""""$token2"""" must be equalTo token Await.result(client.token(s"Bearer $token2").map(token => s""""$token""""), Duration.Inf) must be equalTo token } } }
Example 2
Source File: Schema.scala From play-silhouette-postgres-async-seed with Apache License 2.0 | 5 votes |
package services.database import jdub.async.Database import models.queries.ddl._ import play.api.Logger import play.api.libs.concurrent.Execution.Implicits.defaultContext import scala.concurrent.Future object Schema { val tables = Seq( "users" -> CreateUsersTable, "user_profiles" -> CreateUserProfilesTable, "password_info" -> CreatePasswordInfoTable, "oauth1_info" -> CreateOAuth1InfoTable, "oauth2_info" -> CreateOAuth2InfoTable, "openid_info" -> CreateOpenIdInfoTable, "session_info" -> CreateSessionInfoTable ) def update() = { tables.foldLeft(Future.successful(Unit)) { (f, t) => f.flatMap { u => Database.query(DdlQueries.DoesTableExist(t._1)).flatMap { exists => if (exists) { Future.successful(Unit) } else { Logger.info(s"Creating missing table [${t._1}].") val name = s"CreateTable-${t._1}" Database.raw(name, t._2.sql).map(x => Unit) } } } } } }
Example 3
Source File: PasswordInfoService.scala From play-silhouette-postgres-async-seed with Apache License 2.0 | 5 votes |
package services.user import com.mohiva.play.silhouette.api.LoginInfo import com.mohiva.play.silhouette.api.util.PasswordInfo import com.mohiva.play.silhouette.impl.daos.DelegableAuthInfoDAO import jdub.async.Database import models.queries.PasswordInfoQueries import play.api.libs.concurrent.Execution.Implicits.defaultContext import scala.concurrent.Future object PasswordInfoService extends DelegableAuthInfoDAO[PasswordInfo] { override def find(loginInfo: LoginInfo) = Database.query(PasswordInfoQueries.getById(Seq(loginInfo.providerID, loginInfo.providerKey))) override def save(loginInfo: LoginInfo, authInfo: PasswordInfo) = { Database.transaction { conn => Database.execute(PasswordInfoQueries.UpdatePasswordInfo(loginInfo, authInfo), Some(conn)).flatMap { rowsAffected => if (rowsAffected == 0) { Database.execute(PasswordInfoQueries.CreatePasswordInfo(loginInfo, authInfo), Some(conn)).map(x => authInfo) } else { Future.successful(authInfo) } } } } override def add(loginInfo: LoginInfo, authInfo: PasswordInfo): Future[PasswordInfo] = { Database.execute(PasswordInfoQueries.CreatePasswordInfo(loginInfo, authInfo)).map(x => authInfo) } override def update(loginInfo: LoginInfo, authInfo: PasswordInfo): Future[PasswordInfo] = { Database.execute(PasswordInfoQueries.UpdatePasswordInfo(loginInfo, authInfo)).map(x => authInfo) } override def remove(loginInfo: LoginInfo) = { Database.execute(PasswordInfoQueries.removeById(Seq(loginInfo.providerID, loginInfo.providerKey))).map(x => Unit) } }
Example 4
Source File: UserService.scala From play-silhouette-postgres-async-seed with Apache License 2.0 | 5 votes |
package services.user import java.util.UUID import com.github.mauricio.async.db.Connection import com.mohiva.play.silhouette.api.AuthInfo import com.mohiva.play.silhouette.impl.providers.CommonSocialProfile import jdub.async.Database import models.queries._ import models.user.User import org.slf4j.LoggerFactory import play.api.libs.concurrent.Execution.Implicits.defaultContext import scala.concurrent.Future object UserService { private[this] val log = LoggerFactory.getLogger(UserService.getClass) def create[A <: AuthInfo](currentUser: User, profile: CommonSocialProfile): Future[User] = { log.info(s"Saving profile [$profile].") UserSearchService.retrieve(profile.loginInfo).flatMap { case Some(existingUser) => if (existingUser.id == currentUser.id) { val u = existingUser.copy( profiles = existingUser.profiles.filterNot(_.providerID == profile.loginInfo.providerID) :+ profile.loginInfo ) save(u, update = true) } else { Future.successful(existingUser) } case None => // Link to currentUser Database.execute(ProfileQueries.insert(profile)).flatMap { x => val u = currentUser.copy( profiles = currentUser.profiles.filterNot(_.providerID == profile.loginInfo.providerID) :+ profile.loginInfo ) save(u, update = true) } } } def save(user: User, update: Boolean = false): Future[User] = { val statement = if (update) { log.info(s"Updating user [$user].") UserQueries.UpdateUser(user) } else { log.info(s"Creating new user [$user].") UserQueries.insert(user) } Database.execute(statement).map { i => user } } def remove(userId: UUID) = { val start = System.currentTimeMillis Database.transaction { conn => for { profiles <- removeProfiles(userId, Some(conn)).map(_.length) users <- Database.execute(UserQueries.removeById(Seq(userId)), Some(conn)) } yield Map( "users" -> users, "profiles" -> profiles, "timing" -> (System.currentTimeMillis - start).toInt ) } } private[this] def removeProfiles(userId: UUID, conn: Option[Connection]) = Database.query(ProfileQueries.FindProfilesByUser(userId)).flatMap { profiles => Future.sequence(profiles.map { profile => (profile.loginInfo.providerID match { case "credentials" => Database.execute(PasswordInfoQueries.removeById(Seq(profile.loginInfo.providerID, profile.loginInfo.providerKey)), conn) case "facebook" => Database.execute(OAuth2InfoQueries.removeById(Seq(profile.loginInfo.providerID, profile.loginInfo.providerKey)), conn) case "google" => Database.execute(OAuth2InfoQueries.removeById(Seq(profile.loginInfo.providerID, profile.loginInfo.providerKey)), conn) case "twitter" => Database.execute(OAuth1InfoQueries.removeById(Seq(profile.loginInfo.providerID, profile.loginInfo.providerKey)), conn) case p => throw new IllegalArgumentException(s"Unknown provider [$p].") }).flatMap { infoCount => Database.execute(ProfileQueries.remove(Seq(profile.loginInfo.providerID, profile.loginInfo.providerKey)), conn).map { i => profile } } }) } }
Example 5
Source File: UserSearchService.scala From play-silhouette-postgres-async-seed with Apache License 2.0 | 5 votes |
package services.user import java.util.UUID import com.mohiva.play.silhouette.api.LoginInfo import com.mohiva.play.silhouette.api.services.IdentityService import jdub.async.Database import models.queries.UserQueries import models.user.User import play.api.Logger import play.api.libs.concurrent.Execution.Implicits.defaultContext import scala.concurrent.Future object UserSearchService extends IdentityService[User] { def retrieve(id: UUID): Future[Option[User]] = Database.query(UserQueries.getById(Seq(id))) def retrieve(username: String): Future[Option[User]] = Database.query(UserQueries.FindUserByUsername(username)) override def retrieve(loginInfo: LoginInfo) = if (loginInfo.providerID == "anonymous") { Database.query(UserQueries.getById(Seq(UUID.fromString(loginInfo.providerKey)))).map { case Some(dbUser) => if (dbUser.profiles.nonEmpty) { Logger.warn(s"Attempt to authenticate as anonymous for user with profiles [${dbUser.profiles}].") None } else { Some(dbUser) } case None => None } } else { Database.query(UserQueries.FindUserByProfile(loginInfo)) } }
Example 6
Source File: OpenIdInfoService.scala From play-silhouette-postgres-async-seed with Apache License 2.0 | 5 votes |
package services.user import com.mohiva.play.silhouette.api.LoginInfo import com.mohiva.play.silhouette.impl.daos.DelegableAuthInfoDAO import com.mohiva.play.silhouette.impl.providers.OpenIDInfo import jdub.async.Database import models.queries.OpenIdInfoQueries import play.api.libs.concurrent.Execution.Implicits.defaultContext import scala.concurrent.Future object OpenIdInfoService extends DelegableAuthInfoDAO[OpenIDInfo] { override def find(loginInfo: LoginInfo) = Database.query(OpenIdInfoQueries.getById(Seq(loginInfo.providerID, loginInfo.providerKey))) override def save(loginInfo: LoginInfo, authInfo: OpenIDInfo) = { Database.transaction { conn => Database.execute(OpenIdInfoQueries.UpdateOpenIdInfo(loginInfo, authInfo), Some(conn)).flatMap { rowsAffected => if (rowsAffected == 0) { Database.execute(OpenIdInfoQueries.CreateOpenIdInfo(loginInfo, authInfo), Some(conn)).map(x => authInfo) } else { Future.successful(authInfo) } } } } override def add(loginInfo: LoginInfo, authInfo: OpenIDInfo) = { Database.execute(OpenIdInfoQueries.CreateOpenIdInfo(loginInfo, authInfo)).map(x => authInfo) } override def update(loginInfo: LoginInfo, authInfo: OpenIDInfo) = { Database.execute(OpenIdInfoQueries.UpdateOpenIdInfo(loginInfo, authInfo)).map(x => authInfo) } override def remove(loginInfo: LoginInfo) = { Database.execute(OpenIdInfoQueries.removeById(Seq(loginInfo.providerID, loginInfo.providerKey))).map(x => Unit) } }
Example 7
Source File: OAuth1InfoService.scala From play-silhouette-postgres-async-seed with Apache License 2.0 | 5 votes |
package services.user import com.mohiva.play.silhouette.api.LoginInfo import com.mohiva.play.silhouette.impl.daos.DelegableAuthInfoDAO import com.mohiva.play.silhouette.impl.providers.OAuth1Info import jdub.async.Database import models.queries.OAuth1InfoQueries import play.api.libs.concurrent.Execution.Implicits.defaultContext import scala.concurrent.Future object OAuth1InfoService extends DelegableAuthInfoDAO[OAuth1Info] { override def find(loginInfo: LoginInfo) = Database.query(OAuth1InfoQueries.getById(Seq(loginInfo.providerID, loginInfo.providerKey))) override def save(loginInfo: LoginInfo, authInfo: OAuth1Info) = { Database.transaction { conn => Database.execute(OAuth1InfoQueries.UpdateOAuth1Info(loginInfo, authInfo), Some(conn)).flatMap { rowsAffected => if (rowsAffected == 0) { Database.execute(OAuth1InfoQueries.CreateOAuth1Info(loginInfo, authInfo), Some(conn)).map(x => authInfo) } else { Future.successful(authInfo) } } } } override def add(loginInfo: LoginInfo, authInfo: OAuth1Info) = { Database.execute(OAuth1InfoQueries.CreateOAuth1Info(loginInfo, authInfo)).map(x => authInfo) } override def update(loginInfo: LoginInfo, authInfo: OAuth1Info) = { Database.execute(OAuth1InfoQueries.UpdateOAuth1Info(loginInfo, authInfo)).map(x => authInfo) } override def remove(loginInfo: LoginInfo) = { Database.execute(OAuth1InfoQueries.removeById(Seq(loginInfo.providerID, loginInfo.providerKey))).map(x => Unit) } }
Example 8
Source File: OAuth2InfoService.scala From play-silhouette-postgres-async-seed with Apache License 2.0 | 5 votes |
package services.user import com.mohiva.play.silhouette.api.LoginInfo import com.mohiva.play.silhouette.impl.daos.DelegableAuthInfoDAO import com.mohiva.play.silhouette.impl.providers.OAuth2Info import jdub.async.Database import models.queries.OAuth2InfoQueries import play.api.libs.concurrent.Execution.Implicits.defaultContext import scala.concurrent.Future object OAuth2InfoService extends DelegableAuthInfoDAO[OAuth2Info] { override def find(loginInfo: LoginInfo) = Database.query(OAuth2InfoQueries.getById(Seq(loginInfo.providerID, loginInfo.providerKey))) override def save(loginInfo: LoginInfo, authInfo: OAuth2Info) = { Database.transaction { conn => Database.execute(OAuth2InfoQueries.UpdateOAuth2Info(loginInfo, authInfo), Some(conn)).flatMap { rowsAffected => if (rowsAffected == 0) { Database.execute(OAuth2InfoQueries.CreateOAuth2Info(loginInfo, authInfo), Some(conn)).map(x => authInfo) } else { Future.successful(authInfo) } } } } override def add(loginInfo: LoginInfo, authInfo: OAuth2Info) = { Database.execute(OAuth2InfoQueries.CreateOAuth2Info(loginInfo, authInfo)).map(x => authInfo) } override def update(loginInfo: LoginInfo, authInfo: OAuth2Info) = { Database.execute(OAuth2InfoQueries.UpdateOAuth2Info(loginInfo, authInfo)).map(x => authInfo) } override def remove(loginInfo: LoginInfo) = { Database.execute(OAuth2InfoQueries.removeById(Seq(loginInfo.providerID, loginInfo.providerKey))).map(x => Unit) } }
Example 9
Source File: BaseController.scala From play-silhouette-postgres-async-seed with Apache License 2.0 | 5 votes |
package controllers import java.util.UUID import org.joda.time.LocalDateTime import play.api.i18n.I18nSupport import services.user.AuthenticationEnvironment import com.mohiva.play.silhouette.api._ import com.mohiva.play.silhouette.impl.authenticators.CookieAuthenticator import models.user.{ Role, User } import play.api.libs.concurrent.Execution.Implicits.defaultContext import play.api.mvc.{ AnyContent, Result } import scala.concurrent.Future abstract class BaseController() extends Silhouette[User, CookieAuthenticator] with I18nSupport { def env: AuthenticationEnvironment def withAdminSession(block: (SecuredRequest[AnyContent]) => Future[Result]) = SecuredAction.async { implicit request => if (request.identity.roles.contains(Role.Admin)) { block(request) } else { Future.successful(NotFound("404 Not Found")) } } def withSession(block: (SecuredRequest[AnyContent]) => Future[Result]) = UserAwareAction.async { implicit request => val response = request.identity match { case Some(user) => val secured = SecuredRequest(user, request.authenticator.getOrElse(throw new IllegalStateException()), request) block(secured).map { r => r } case None => val user = User( id = UUID.randomUUID(), username = None, profiles = Nil, created = new LocalDateTime() ) for { user <- env.userService.save(user) authenticator <- env.authenticatorService.create(LoginInfo("anonymous", user.id.toString)) value <- env.authenticatorService.init(authenticator) result <- block(SecuredRequest(user, authenticator, request)) authedResponse <- env.authenticatorService.embed(value, result) } yield { env.eventBus.publish(SignUpEvent(user, request, request2Messages)) env.eventBus.publish(LoginEvent(user, request, request2Messages)) authedResponse } } response } }
Example 10
Source File: AuthenticationController.scala From play-silhouette-postgres-async-seed with Apache License 2.0 | 5 votes |
package controllers import com.mohiva.play.silhouette.api.exceptions.ProviderException import com.mohiva.play.silhouette.api.{ LoginEvent, LogoutEvent } import com.mohiva.play.silhouette.impl.exceptions.IdentityNotFoundException import com.mohiva.play.silhouette.impl.providers.{ CommonSocialProfile, CommonSocialProfileBuilder, SocialProvider } import models.user.{ User, UserForms } import play.api.i18n.MessagesApi import services.user.AuthenticationEnvironment import play.api.libs.concurrent.Execution.Implicits.defaultContext import scala.concurrent.Future @javax.inject.Singleton class AuthenticationController @javax.inject.Inject() ( override val messagesApi: MessagesApi, override val env: AuthenticationEnvironment ) extends BaseController { def signInForm = withSession { implicit request => Future.successful(Ok(views.html.signin(request.identity, UserForms.signInForm))) } def authenticateCredentials = withSession { implicit request => UserForms.signInForm.bindFromRequest.fold( form => Future.successful(BadRequest(views.html.signin(request.identity, form))), credentials => env.credentials.authenticate(credentials).flatMap { loginInfo => val result = Redirect(controllers.routes.HomeController.index()) env.identityService.retrieve(loginInfo).flatMap { case Some(user) => env.authenticatorService.create(loginInfo).flatMap { authenticator => env.eventBus.publish(LoginEvent(user, request, request2Messages)) env.authenticatorService.init(authenticator).flatMap(v => env.authenticatorService.embed(v, result)) } case None => Future.failed(new IdentityNotFoundException("Couldn't find user.")) } }.recover { case e: ProviderException => Redirect(controllers.routes.AuthenticationController.signInForm()).flashing(("error", "Invalid credentials.")) } ) } def authenticateSocial(provider: String) = withSession { implicit request => (env.providersMap.get(provider) match { case Some(p: SocialProvider with CommonSocialProfileBuilder) => p.authenticate().flatMap { case Left(result) => Future.successful(result) case Right(authInfo) => for { profile <- p.retrieveProfile(authInfo) user <- env.userService.create(mergeUser(request.identity, profile), profile) authInfo <- env.authInfoService.save(profile.loginInfo, authInfo) authenticator <- env.authenticatorService.create(profile.loginInfo) value <- env.authenticatorService.init(authenticator) result <- env.authenticatorService.embed(value, Redirect(controllers.routes.HomeController.index())) } yield { env.eventBus.publish(LoginEvent(user, request, request2Messages)) result } } case _ => Future.failed(new ProviderException("Invalid provider [" + provider + "].")) }).recover { case e: ProviderException => logger.error("Unexpected provider error", e) Redirect(routes.AuthenticationController.signInForm()).flashing(("error", "Service error with provider [" + provider + "].")) } } def signOut = SecuredAction.async { implicit request => val result = Redirect(controllers.routes.HomeController.index()) env.eventBus.publish(LogoutEvent(request.identity, request, request2Messages)) env.authenticatorService.discard(request.authenticator, result).map(x => result) } private[this] def mergeUser(user: User, profile: CommonSocialProfile) = { user.copy( username = if (profile.firstName.isDefined && user.username.isEmpty) { profile.firstName } else { user.username } ) } }
Example 11
Source File: RegistrationController.scala From play-silhouette-postgres-async-seed with Apache License 2.0 | 5 votes |
package controllers import com.mohiva.play.silhouette.api.{ LoginEvent, LoginInfo, SignUpEvent } import com.mohiva.play.silhouette.impl.providers.{ CommonSocialProfile, CredentialsProvider } import models.user.{ RegistrationData, UserForms } import play.api.i18n.{ Messages, MessagesApi } import play.api.libs.concurrent.Execution.Implicits.defaultContext import play.api.mvc.AnyContent import services.user.AuthenticationEnvironment import scala.concurrent.Future @javax.inject.Singleton class RegistrationController @javax.inject.Inject() ( override val messagesApi: MessagesApi, override val env: AuthenticationEnvironment ) extends BaseController { def registrationForm = withSession { implicit request => Future.successful(Ok(views.html.register(request.identity, UserForms.registrationForm))) } def register = withSession { implicit request => UserForms.registrationForm.bindFromRequest.fold( form => Future.successful(BadRequest(views.html.register(request.identity, form))), data => { env.identityService.retrieve(LoginInfo(CredentialsProvider.ID, data.email)).flatMap { case Some(user) => Future.successful { Ok(views.html.register(request.identity, UserForms.registrationForm.fill(data))).flashing("error" -> "That email address is already taken.") } case None => env.identityService.retrieve(data.username) flatMap { case Some(user) => Future.successful { Ok(views.html.register(request.identity, UserForms.registrationForm.fill(data))).flashing("error" -> "That username is already taken.") } case None => saveProfile(data) } } } ) } private[this] def saveProfile(data: RegistrationData)(implicit request: SecuredRequest[AnyContent]) = { if (request.identity.profiles.exists(_.providerID == "credentials")) { throw new IllegalStateException("You're already registered.") // TODO Fix? } val loginInfo = LoginInfo(CredentialsProvider.ID, data.email) val authInfo = env.hasher.hash(data.password) val user = request.identity.copy( username = if (data.username.isEmpty) { request.identity.username } else { Some(data.username) }, profiles = request.identity.profiles :+ loginInfo ) val profile = CommonSocialProfile( loginInfo = loginInfo, email = Some(data.email) ) val r = Redirect(controllers.routes.HomeController.index()) for { avatar <- env.avatarService.retrieveURL(data.email) profile <- env.userService.create(user, profile.copy(avatarURL = avatar.orElse(Some("default")))) u <- env.userService.save(user, update = true) authInfo <- env.authInfoService.save(loginInfo, authInfo) authenticator <- env.authenticatorService.create(loginInfo) value <- env.authenticatorService.init(authenticator) result <- env.authenticatorService.embed(value, r) } yield { env.eventBus.publish(SignUpEvent(u, request, request2Messages)) env.eventBus.publish(LoginEvent(u, request, request2Messages)) result } } }
Example 12
package controllers import play.api._ import play.api.mvc._ import play.api.libs.ws.WS import play.api.Play.current import play.api.libs.json._ import play.api.libs.functional.syntax._ import play.api.libs.concurrent.Execution.Implicits.defaultContext import models.Repo class Api extends Controller { implicit val writesRepo = new Writes[Repo] { def writes(repo:Repo) = Json.obj( "name" -> repo.name, "language" -> repo.language, "is_fork" -> repo.isFork, "size" -> repo.size ) } implicit val readsRepoFromGithub:Reads[Repo] = ( (JsPath \ "name").read[String] and (JsPath \ "language").read[String] and (JsPath \ "fork").read[Boolean] and (JsPath \ "size").read[Long] )(Repo.apply _) def repos(login:String) = Action.async { val url = s"https://api.github.com/users/$login/repos" val request = WS.url(url).withHeaders("Content-Type" -> "application/json").get() request.map { r => if (r.status == 200) { val reposOpt = Json.parse(r.body).validate[List[Repo]] reposOpt match { case JsSuccess(repos, _) => Ok(Json.toJson(repos)) case _ => InternalServerError } } else { NotFound } } } }
Example 13
package controllers import play.api._ import play.api.mvc._ import play.api.libs.ws.WS import play.api.Play.current import play.api.libs.json._ import play.api.libs.functional.syntax._ import play.api.libs.concurrent.Execution.Implicits.defaultContext import models.Repo class Api extends Controller { implicit val writesRepo = new Writes[Repo] { def writes(repo:Repo) = Json.obj( "name" -> repo.name, "language" -> repo.language, "is_fork" -> repo.isFork, "size" -> repo.size ) } implicit val readsRepoFromGithub:Reads[Repo] = ( (JsPath \ "name").read[String] and (JsPath \ "language").read[String] and (JsPath \ "fork").read[Boolean] and (JsPath \ "size").read[Long] )(Repo.apply _) def repos(login:String) = Action.async { val url = s"https://api.github.com/users/$login/repos" val request = WS.url(url).withHeaders("Content-Type" -> "application/json").get() request.map { r => if (r.status == 200) { val reposOpt = Json.parse(r.body).validate[List[Repo]] reposOpt match { case JsSuccess(repos, _) => Ok(Json.toJson(repos)) case _ => InternalServerError } } else { NotFound } } } }
Example 14
Source File: HttpsAndWwwRedirectForElbFilter.scala From cave with MIT License | 5 votes |
package filters import play.api.Play import play.api.libs.concurrent.Execution.Implicits.defaultContext import play.api.mvc._ import play.api.Play.current import scala.concurrent.Future object HttpsAndWwwRedirectForElbFilter extends Filter { def apply(nextFilter: (RequestHeader) => Future[Result])(requestHeader: RequestHeader): Future[Result] = { //play uses lower case headers. requestHeader.headers.get("x-forwarded-proto") match { case Some(header) => { if ("https" == header) { if (doWwwRedirect(requestHeader)) Future.successful(Results.Redirect("https://www." + requestHeader.host + requestHeader.uri, 301)) else nextFilter(requestHeader).map { result => result.withHeaders(("Strict-Transport-Security", "max-age=31536000")) } } else { Future.successful(Results.Redirect("https://" + requestHeader.host + requestHeader.uri, 301)) } } case None => nextFilter(requestHeader) } } def doWwwRedirect(requestHeader: RequestHeader): Boolean = { val redirectsEnabled = Play.configuration.getBoolean("cave.enableWwwRedirect").getOrElse(false) val wwwRedirectEnabledDomain = Play.configuration.getString("cave.wwwRedirectEnabledDomain").getOrElse("cavellc.io") redirectsEnabled && requestHeader.host.startsWith(wwwRedirectEnabledDomain) && !requestHeader.host.startsWith("www.") } }
Example 15
Source File: Application.scala From Scalaprof with GNU General Public License v2.0 | 5 votes |
package controllers import play.api._ import play.api.mvc._ import akka.actor.{ActorSystem, Props} import akka.util.Timeout import akka.pattern.ask import scala.concurrent._ import scala.concurrent.duration._ import scala.util._ import edu.neu.coe.scala.numerics.Rational import akka.actor.ActorRef import com.typesafe.config.{ ConfigFactory, Config } import actors._ import models._ import spire.math.Real class Application extends Controller { val config = ConfigFactory.load() val which = config.getString("calculator") import play.api.libs.concurrent.Execution.Implicits.defaultContext implicit val timeout: Timeout = Timeout(10 seconds) implicit val system = ActorSystem("RPN-Calculator") val setup = which match { case "rational" => Application.getSetupForRational case "double" => Application.getSetupForDouble case "spire" => Application.getSetupForSpire case _ => Console.err.println(s"Unsupported calculator type: $which"); Application.getSetupForRational } val calculator = system.actorOf(setup _1,setup _2) val name: String = setup _3; println(s"$name is ready") def index() = Action.async { val xsf = (calculator ? View).mapTo[Seq[_]] xsf map { case xs => Ok(s"$name: calculator has the following elements (starting with top): $xs") } } def command(s: String) = Action.async { val xtf = (calculator ? s).mapTo[Try[_]] xtf map { case Success(x) => Ok(s"""$name: you have entered "$s" and got back $x""") case Failure(e) => if (s=="clr") Ok("$name: cleared") else Ok(s"""$name: you entered "$s" which caused error: $e""") // case Failure(e) => if (s=="clr") redirect("/") else Ok(s"""$name: you entered "$s" which caused error: $e""") } } } object Application { // TODO move these to model classes def getSetupForDouble(implicit system: ActorSystem) = { implicit val lookup: String=>Option[Double] = DoubleMill.constants.get _ implicit val conv: String=>Try[Double] = DoubleMill.valueOf _ implicit val parser = new ExpressionParser[Double](conv,lookup) val mill = DoubleMill() // Note: the following pattern should NOT be used within an actor val props = Props(new Calculator(mill,parser)) // TODO for these methods, return mill and parser instead of props (props,"doubleCalculator","Double Calculator") } // CONSIDER This assumes that we have Rational in our classpath already. // I'd like to try the possibility of dynamically loading the Rational stuff. // But, that's going to be very tricky, so we'll leave it for now. def getSetupForRational(implicit system: ActorSystem) = { implicit val lookup: String=>Option[Rational] = RationalMill.constants.get _ implicit val conv: String=>Try[Rational] = RationalMill.valueOf _ implicit val parser = new ExpressionParser[Rational](conv,lookup) val mill = RationalMill() // Note: the following pattern should NOT be used within an actor val props = Props(new Calculator(mill,parser)) (props,"rationalCalculator","Rational Calculator") } // CONSIDER This assumes that we have Spire in our classpath already. def getSetupForSpire(implicit system: ActorSystem) = { import spire.implicits._ import spire.math._ implicit val lookup: String=>Option[Real] = SpireMill.constants.get _ implicit val conv: String=>Try[Real] = SpireMill.valueOf _ implicit val parser = new ExpressionParser[Real](conv,lookup) val mill = SpireMill() // Note: the following pattern should NOT be used within an actor val props = Props(new Calculator(mill,parser)) (props,"spireCalculator","Spire Calculator") } }
Example 16
Source File: CalculatorSpec.scala From Scalaprof with GNU General Public License v2.0 | 5 votes |
package actors import org.scalatest._ import akka.testkit.TestActorRef import scala.concurrent.duration._ import scala.concurrent.Await import akka.pattern.ask import scala.util._ import scala.io.Source import scala.concurrent._ import scala.concurrent.duration._ import com.typesafe.config.{ ConfigFactory, Config } import akka.actor.{ Actor, ActorSystem, Props, ActorRef } import akka.util.Timeout import java.net.URL import org.scalatest.concurrent._ import org.scalatest._ import org.scalatest.time._ import edu.neu.coe.scala.numerics.Rational import models._ class CalculatorSpec extends FlatSpec with Matchers with Futures with ScalaFutures with Inside { implicit val system = ActorSystem("CountWords") import play.api.libs.concurrent.Execution.Implicits.defaultContext implicit val timeout: Timeout = Timeout(10 seconds) "Rational Calculator" should "yield empty list for /" in { val lookup: String=>Option[Rational] = RationalMill.constants.get _ val conv: String=>Try[Rational] = RationalMill.valueOf _ val parser = new ExpressionParser[Rational](conv,lookup) val mill: Mill[Rational] = RationalMill() val props = Props(new Calculator(mill,parser)) val taf = TestActorRef(props) val xsf = (taf ? View).mapTo[Seq[Rational]] val nf = xsf map { case xs => xs.size } whenReady(nf, timeout(Span(6, Seconds))) { case 0 => } } it should "yield 1 for 1" in { val lookup: String=>Option[Rational] = RationalMill.constants.get _ val conv: String=>Try[Rational] = RationalMill.valueOf _ val parser = new ExpressionParser[Rational](conv,lookup) val mill: Mill[Rational] = RationalMill() val props = Props(new Calculator(mill,parser)) val taf = TestActorRef(props) val xtf = (taf ? "1").mapTo[Try[Rational]] whenReady(xtf, timeout(Span(6, Seconds))) { case Success(Rational(1,1)) => } } it should "yield 1 when given floating point problem" in { val lookup: String=>Option[Rational] = RationalMill.constants.get _ val conv: String=>Try[Rational] = RationalMill.valueOf _ val parser = new ExpressionParser[Rational](conv,lookup) val mill: Mill[Rational] = RationalMill() val props = Props(new Calculator(mill,parser)) val taf = TestActorRef(props) val xtf = (taf ? "0.2 0.1 + 10 * 3 /").mapTo[Try[Rational]] whenReady(xtf, timeout(Span(6, Seconds))) { case Success(Rational(1,1)) => } } "Double Calculator" should "yield empty list for /" in { val lookup: String=>Option[Double] = DoubleMill.constants.get _ val conv: String=>Try[Double] = DoubleMill.valueOf _ val parser = new ExpressionParser[Double](conv,lookup) val mill: Mill[Double] = DoubleMill() val props = Props(new Calculator(mill,parser)) val taf = TestActorRef(props) val xsf = (taf ? View).mapTo[Seq[Double]] val nf = xsf map { case xs => xs.size } whenReady(nf, timeout(Span(6, Seconds))) { case 0 => } } // This test suffers from a very peculiar bug which might even be a bug // in the Scala compiler. Kudos to you if you can fix it!! ignore should "yield 1 for 1" in { val lookup: String=>Option[Double] = DoubleMill.constants.get _ val conv: String=>Try[Double] = DoubleMill.valueOf _ val parser = new ExpressionParser[Double](conv,lookup) val mill: Mill[Double] = DoubleMill() val props = Props(new Calculator(mill,parser)) val taf = TestActorRef(props) val xtf = (taf ? "1").mapTo[Try[Double]] whenReady(xtf, timeout(Span(6, Seconds))) { case Success(1.0) => } } }