object evolutions is not a member of package play.api.db.slick - scala

I'm a newbie to Play framework and can't figure out why I'm getting this error in my application loader class that I copied and pasted from the Play 2.6 documention here with some modifications for new versions of slick and slick-evolutions.
Here is the part of my build.sbt that references the libraries:
scalaVersion := "2.12.2"
libraryDependencies ++= Seq(evolutions, jdbc)
libraryDependencies ++= Seq(jdbc, ehcache , ws , specs2 % Test , guice )
libraryDependencies ++= Seq("com.typesafe.play" %% "play" % "2.6.11")
libraryDependencies += "com.typesafe.play" %% "play-slick" % "3.0.1"
libraryDependencies += "com.typesafe.play" %% "play-slick-evolutions" % "3.0.1"
libraryDependencies ++= Seq("mysql" % "mysql-connector-java" % "5.1.36")
Here is my application.conf
play.application.loader=AppComponents
And here is the AppComponents class which I put in my root directory
import play.api.ApplicationLoader.Context
import play.api.BuiltInComponentsFromContext
import play.api.db.{Database, DBComponents, HikariCPComponents}
import play.api.db.slick.evolutions.{SlickEvolutionsComponents}
import play.api.routing.Router
import play.filters.HttpFiltersComponents
class AppComponents(cntx: Context)
extends BuiltInComponentsFromContext(cntx)
with DBComponents
with SlickEvolutionsComponents
with HikariCPComponents
with HttpFiltersComponents
{
// this will actually run the database migrations on startup
applicationEvolutions
}
I've examined the play-slick-evolutions_2.12-3.0.1.jar jar that was downloaded and it indeed has has play.api.db.slick.evolutions there. I've also tried earlier versions that comport exactly with the code in the Play 2.6 documentation, but there too, evolutions is not a member of the package.

First, a project rebuild took care of the initial error, but it did not solve the problem with the Application Loader. To fix this I returned to the Play 2.6 documentation and restored the class to the segment they provided and removed the play-slick sbt entries, restoring to the entries in the documentation. There was still a problem, and on finding another example it became evident that I didn't have a complete class. Here it is:
import play.api.ApplicationLoader
import play.api.ApplicationLoader.Context
import play.api.BuiltInComponentsFromContext
import play.api.db.{Database, DBComponents, HikariCPComponents}
import play.api.db.evolutions.EvolutionsComponents
import play.api.routing.Router
import play.filters.HttpFiltersComponents
class MyApplicationLoader extends ApplicationLoader {
def load(context: Context) = {
new MyComponents(context).application
}
}
class MyComponents(cntx: Context)
extends BuiltInComponentsFromContext(cntx)
with DBComponents
with EvolutionsComponents
with HikariCPComponents
with HttpFiltersComponents
{
// this will actually run the database migrations on startup
lazy val router = Router.empty
applicationEvolutions
}
I also adjusted my application.conf setting to:
play.application.loader=MyApplicationLoader
Note that I still need to add the routing because the lazy val router = Route.empty gives a web page that says:
Action Not Found
For request 'GET /'
These routes have been tried, in this order:

Related

Scala : play is not recognizing the test components

I am transitioning from Java to Scala. I have written a simple test to render a view. Like :
import org.scalatestplus.play.PlaySpec
import org.scalatest._
import org.slf4j.LoggerFactory
import play.test.WithApplication
class EvTemplateTests extends PlaySpec{
implicit lazy val log = LoggerFactory.getLogger(getClass)
//run your test//run your test
"render eval template" in {
val html = views.html.index("Hello")
contentType(html) must equalTo("text/html")
contentAsString(html) must contain("Welcome to Play!")
}
}
When compiling, looks like it is not finding "index","contentType", "contentAsString" etc.Looks like, the project is using the libraries:
lazy val thirdPartyDependencies = Seq(
jdbc,
"com.typesafe.play" %% "anorm" % "2.4.0",
"com.typesafe.play" %% "play-mailer" % "3.0.1",
"com.microsoft.sqlserver" % "mssql-jdbc" % "6.4.0.jre8",
"io.swagger" %% "swagger-play2" % "1.5.0", // This version adds Play 2.4 support.
// ScalaTest+ Play (have to use non-release 1.4.0-M4 version for now as it is only compatible with Play 2.4)
"org.scalatestplus" %% "play" % "1.4.0-M4" % "test",
"org.mockito" % "mockito-core" % "1.10.19" % "test"
)
May I get any insight?
You can start from here:
import controllers.AssetsFinder
import org.specs2.mutable.Specification
import play.api.Application
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.mvc._
import play.api.test._
import play.api.test.Helpers._
class EvTemplateTests
extends Specification
with DefaultAwaitTimeout
with FutureAwaits
with Results {
val application: Application = GuiceApplicationBuilder().build()
"render eval template" in new WithApplication(app = application) {
implicit val assetsFinder = app.injector.instanceOf[AssetsFinder]
val html = views.html.index("Hello")
contentType(html) mustEqual "text/html"
contentAsString(html) must contain("Hello")
}
}
add this after jdbc in LibraryDependencies: specs2 % Test
Most important part of test setup here is implicit AssetFinder that derived from GuiceApplicationBuilder:
val application: Application = GuiceApplicationBuilder().build()
AssetFinder is really important part of view testing in PlayFramework

How to use jquery-ui with JSImport

I want to access the jquery ui library in my scala js project. I have tried defining the following main module:
import org.scalajs.jquery.JQueryStatic
import scala.scalajs.js
import org.scalajs.dom
import scalatags.JsDom.all._
import scala.scalajs.js.annotation.JSImport
#JSImport("jquery", JSImport.Namespace)
#js.native
object JQuery extends JQueryStatic
#js.native
trait JQueryUI extends JQueryStatic {
def spinner(options: js.Object = js.Dynamic.literal()): JQueryUI = js.native
}
#JSImport("jquery-ui", JSImport.Namespace)
#js.native
object JQueryUI extends JQueryUI
object App {
def main(args: Array[String]): Unit = {
dom.document.getElementById("root").appendChild(div(input(id := "input")).render)
JQuery("#input").asInstanceOf[JQueryUI].spinner()
}
}
And my build.sbt is as follows:
enablePlugins(ScalaJSBundlerPlugin)
lazy val opexCounter = project.in(file(".")).settings(
name := "Repro",
scalaVersion := "2.12.8",
libraryDependencies ++= Seq(
"org.scala-js" %%% "scalajs-dom" % "0.9.6",
"com.lihaoyi" %%% "scalatags" % "0.6.7",
"be.doeraene" %%% "scalajs-jquery" % "0.9.4"
),
npmDependencies in Compile ++= Seq(
"jquery" -> "2.2.1",
"jquery-ui" -> "1.12.1",
),
mainClass in Compile := Some("App"),
scalaJSUseMainModuleInitializer := true,
webpackDevServerPort := 3000
)
But when I load my page I get the following error in my console:
TypeError: qual$1.spinner is not a function
Is this not the correct way to import the library and if not what is?
The complete source for the project can be found here
I changed my npm dependency from jquery-ui to jquery-ui-bundle and imported it. I also had to make an explicit reference to my JQueryUIImport object in order to ensure it was instantiated. Those 2 changes fixed the problem

unable to use WS.url() in Play app tutorial

I am doing a tutorial for Play framework with Scala. I am quite early into the tutorial and i am having a problem with ws. In my class WS is not recognized although that says to use WS.url("url-here") and to import play.api.libs._ which i have done both. I have also tried using ws.url("url-here") as well... and here wsis recognized but after that i get a "can't resolve symbol 'url'". Here is my build.sbt:
name := """play_hello"""
organization := "x.x"
version := "1.0-SNAPSHOT"
lazy val root = (project in file(".")).enablePlugins(PlayScala)
scalaVersion := "2.12.3"
libraryDependencies ++= Seq(
"org.scalatestplus.play" %% "scalatestplus-play" % "3.1.2" % Test,
"com.ning" % "async-http-client" % "1.9.29",
guice,
ws
)
And here is the code for my class:
package controllers
import javax.inject.Inject
import com.ning.http.client.oauth.{ConsumerKey, RequestToken}
import play.api.Play.current
import play.api.libs._
import play.api.mvc._
import scala.concurrent.Future
class Application #Inject()(cc: ControllerComponents) extends
AbstractController(cc){
def tweets = Action.async{
credentials.map { case (consumerKey, requestToken) =>
WS.url("http://stream.twitter.com")
Future.successful{
Ok
}
}getOrElse{
Future.successful{
InternalServerError("Twitter credentials are missing!")
}
}
}
def credentials: Option[(ConsumerKey, RequestToken)] = for{
apiKey <- current.configuration.getString("twitter.apiKey")
apiSecret <- current.configuration.getString("twitter.apiSecret")
token <- current.configuration.getString("twitter.token")
tokenSecret <- current.configuration.getString("twitter.tokenSecret")
}yield (
new ConsumerKey(apiKey, apiSecret),
new RequestToken(token, tokenSecret)
)
}
I Figure that most likely this is some type of problem with a dependency conflict. Here is a screenshot of ws related libraries in project structure. I would appreciate any help in finding a solution to this. Thank you.
The solution was to add ws: WSClient to the parameters of Application class constructor. Apperently standalone WS object has been removed in more recent versions of ws library.
class Application #Inject()(cc: ControllerComponents, ws: WSClient) extends AbstractController(cc)
Now i can use:
ws.url("https://stream.twitter.com/1.1/statuses/filter.json")
Also according to the documentation on play website if you for some reason can not use an injected WSClient, then you can create an instance of one and use that.

Unable to import DefaultHttpFilters

I'm attempting to create a filter to collect metrics related to request fulfillment time in a Scala Play 2.5 app. I am following this documentation.
It instructs me to create a class that extends DefaultHttpFilters. However, I am unable to import this class! import play.api.http.DefaultHttpFilters is unrecognized. It occurred to me that I may need to make an addition to build.sbt, so I added filters to libraryDependencies in that file, but still no luck. The truly strange thing is that import play.api.http.HttpFilters is recognized. DefaultHttpFilters lives in the same package, and in fact implements the HttpFilters trait, so I'm rather bamboozled by the fact that the import is unrecognized.
Any advice would be greatly appreciated, and please let me know if I can provide any further information to help in diagnosing the issue.
Here is my build.sbt:
name := """REDACTED"""
version := "1.0.0"
lazy val root = (project in file(".")).enablePlugins(PlayScala)
scalaVersion := "2.11.7"
routesGenerator := InjectedRoutesGenerator
resolvers += "scalaz-bintray" at "https://dl.bintray.com/scalaz/releases"
libraryDependencies ++= Seq(
ws,
filters,
"com.typesafe.play" %% "play-slick" % "2.0.0",
"com.h2database" % "h2" % "1.4.187",
"org.scalatestplus.play" %% "scalatestplus-play" % "1.5.0" % "test",
"mysql" % "mysql-connector-java" % "5.1.39",
specs2 % Test
)
unmanagedJars in Compile += file(Path.userHome+"/lib/*.jar")
resolvers += "Sonatype snapshots" at "http://oss.sonatype.org/content/repositories/snapshots/"
fork in run := true
Here is plugins.sbt:
resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/"
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.5.0")
addSbtPlugin("com.jamesward" %% "play-auto-refresh" % "0.0.14")
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.3.5")
Filters are defined in the following way
app/filters/AccessLoggingFilter.scala:
import javax.inject.Inject
import akka.stream.Materializer
import play.api.Logger
import play.api.mvc.{Filter, RequestHeader, Result}
import play.api.routing.Router.Tags
import scala.concurrent.Future
class AccessLoggingFilter #Inject() (implicit val mat: Materializer) extends Filter {
def apply(nextFilter: RequestHeader => Future[Result])(requestHeader: RequestHeader): Future[Result] = {
val requestStartTime = System.nanoTime
nextFilter(requestHeader).map { result =>
val requestedAction = requestHeader.tags(Tags.RouteController) + "." + requestHeader.tags(Tags.RouteActionMethod)
val requestFulfillmentTime = System.nanoTime - requestStartTime
Logger.info("Request for " + requestedAction + " resulted in status code " + result.header.status +
" and had request fulfillment time " + requestFulfillmentTime + " nanoseconds")
result.withHeaders("Request-Time" -> requestFulfillmentTime.toString)
}
}
}
And then app/filters/Filters.scala:
package filters
import javax.inject.Inject
class Filters #Inject() (accessLoggingFilter: AccessLoggingFilter) { }
DefaultHttpFilters was only introduced in Play 2.5.4, and you are using Play 2.5.0.
So change your Play version to 2.5.4 at least (the current version at the time of writing is 2.5.6)
// In plugins.sbt
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.5.4")
Then, just reload the project and update your dependencies (activator update)
If you really need to use that version, use HttpFilters instead (same example from "Using filters")
import javax.inject.Inject
import play.api.http.HttpFilters
import play.filters.gzip.GzipFilter
class Filters #Inject() (
gzip: GzipFilter,
log: LoggingFilter
) extends HttpFilters {
val filters = Seq(gzip, log)
}

I can not import filters in playframework 2.3.0

I use playframework 2.3.0, recently I want to add the CSRFFilter
when I import csrf in global.scala:
import play.filters.csrf._
I get an error for this:
[error] G:\testprojects\app\Global.scala:7: object filters is not a member
of package play
[error] import play.filters.csrf._
My plugin.sbt is
...
// The Play plugin
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.3.0")
...
I use Build.scala instead of build.sbt
lazy val root = Project("root", base = file(".")).enablePlugins(PlayScala)
.settings(baseSettings: _*)
.settings(libraryDependencies++=appDependencies)
.settings(
scalaVersion := "2.11.1",
version := "1.0"
)
According to the documentation you have to add the filters dependency to your project:
libraryDependencies += filters
The documentation is for build.sbt but I guess it should work with Build.scala too.
Play Framework GzipFilter is working for me,
my build.sbt file
name := "GZIP"
version := "1.0-SNAPSHOT"
libraryDependencies ++= Seq(
javaJdbc,
javaEbean,
cache,
filters
)
play.Project.playJavaSettings
steps to get play.filters package
1. play
2. update //important
3. clean
4. eclipse
5. compile
6. run
finally it will work.... (update command is important)
if IDE not detecting play.filters
do the above steps one more time
finally copy paste below code
import play.GlobalSettings;
import play.api.mvc.EssentialFilter;
import play.filters.gzip.GzipFilter;
public class Global extends GlobalSettings {
public <T extends EssentialFilter> Class<T>[] filters() {
return new Class[]{GzipFilter.class};
}
}
In Play 2.4.3, the import is:
import play.filters.cors.CORSActionBuilder
It's no longer called csrf, but cors.