Cannot find Await from akka - scala

I have an error of importing Await from akka.io. Here is my build.sbt:
name := "Project1"
version := "0.1"
scalaVersion := "2.10.1"
libraryDependencies += "org.json4s" %% "json4s-native" % "3.2.4"
resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/"
libraryDependencies += "com.typesafe.akka" % "akka-actor_2.10" % "2.1.4"
Here is a part of a code:
import akka.actor.Actor
import akka.actor.ActorSystem
import akka.actor.Props
import akka.dispatch.Await
import akka.pattern.ask
//.......
private def resultId = {
private val someActor = context.actorSelection("../someActor123") // defined in Application object
val future = someActor ? SomeMessage
val result = Await.result(future, 1.timeout).asInstanceOf[String]
}
It says object Await is not a member of package akka.dispatch and value ? is not a member of akka.actor.ActorSelection and not found: value Await
Of course, I reloaded it and did gen-idea.

As #S.R.I noted you should use scala.concurrent.Await instead of akka.dispatch.Await.
value ? is not a member of akka.actor.ActorSelection
There is no ask pattern support for ActorSelection in version 2.1.4. See this commit. Ask support for ActorSelection is available only after version 2.2.

Related

Simple hello world api using finagle - Error: object twitter is not a member of package com import com.twitter.finagle.Http

Im really new to this microservice world and was trying to learn from scratch. But for some reason not able to call a simple dependency.
Getting the error
object twitter is not a member of package com import
com.twitter.finagle._
SBT file, Ive tried three ways
Trial 1
name := "microservicestest"
version := "0.1"
scalaVersion := "2.12.15"
libraryDependencies ++= Seq(
"com.github.finagle" %% "finch-core" % "0.31.0",
"com.github.finagle" %% "finch-circe" % "0.31.0",
"io.circe" %% "circe-generic" % "0.9.0"
)
Trial 2 (puttting just the dependency line in here)
libraryDependencies += "com.twitter" %% "finagle-http" % "21.8.0"
Trial 3
libraryDependencies ++= Seq(
"com.github.finagle" %% "finch-core" % "0.15.1"
)
Scala file
import io.finch._
import com.twitter.finagle.Http
import com.twitter.util.Await
object HelloWorld extends App {
val api: Endpoint[String] = get("hello") { Ok("Hello, World!") }
Await.ready(Http.server.serve(":8080", api.toServiceAs[Text.Plain]))
}
SBT file
libraryDependencies += "com.twitter" %% "finagle-http" % "21.8.0"
Working simple code
import com.twitter.finagle.{Http, Service}
import com.twitter.finagle.http
import com.twitter.util.{Await, Future}
object HelloWorld extends App {
val service = new Service[http.Request, http.Response] {
def apply(req: http.Request): Future[http.Response] =
Future.value(http.Response(req.version, http.Status.Ok))
}
val server = Http.serve(":8080", service)
Await.ready(server)
}

PlaySpec not found in IntelliJ

Below is a Scala test of websocket:
import java.util.function.Consumer
import play.shaded.ahc.org.asynchttpclient.AsyncHttpClient
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.test.{Helpers, TestServer, WsTestClient}
import scala.compat.java8.FutureConverters
import scala.concurrent.Await
import scala.concurrent.duration._
import org.scalatestplus.play._
class SocketTest extends PlaySpec with ScalaFutures {
"HomeController" should {
"reject a websocket flow if the origin is set incorrectly" in WsTestClient.withClient { client =>
// Pick a non standard port that will fail the (somewhat contrived) origin check...
lazy val port: Int = 31337
val app = new GuiceApplicationBuilder().build()
Helpers.running(TestServer(port, app)) {
val myPublicAddress = s"localhost:$port"
val serverURL = s"ws://$myPublicAddress/ws"
val asyncHttpClient: AsyncHttpClient = client.underlying[AsyncHttpClient]
val webSocketClient = new WebSocketClient(asyncHttpClient)
try {
val origin = "ws://example.com/ws"
val consumer: Consumer[String] = new Consumer[String] {
override def accept(message: String): Unit = println(message)
}
val listener = new WebSocketClient.LoggingListener(consumer)
val completionStage = webSocketClient.call(serverURL, origin, listener)
val f = FutureConverters.toScala(completionStage)
Await.result(f, atMost = 1000.millis)
listener.getThrowable mustBe a[IllegalStateException]
} catch {
case e: IllegalStateException =>
e mustBe an[IllegalStateException]
case e: java.util.concurrent.ExecutionException =>
val foo = e.getCause
foo mustBe an[IllegalStateException]
}
}
}
}
}
But compile is failing on line import org.scalatestplus.play._ with error :
Cannot resolve symbol scalatestplus
From https://www.playframework.com/documentation/2.8.x/ScalaTestingWithScalaTest I have added scalatest and play to build:
build.sbt:
name := "testproject"
version := "1.0"
lazy val `testproject` = (project in file(".")).enablePlugins(PlayScala)
resolvers += "scalaz-bintray" at "https://dl.bintray.com/scalaz/releases"
resolvers += "Akka Snapshot Repository" at "https://repo.akka.io/snapshots/"
scalaVersion := "2.12.2"
libraryDependencies ++= Seq( jdbc , ehcache , ws , guice , specs2 % Test)
// https://mvnrepository.com/artifact/com.typesafe.scala-logging/scala-logging
libraryDependencies += "com.typesafe.scala-logging" %% "scala-logging" % "3.9.2"
libraryDependencies ++= Seq(
"org.scalatestplus.play" %% "scalatestplus-play" % "3.0.0" % "test"
)
unmanagedResourceDirectories in Test <+= baseDirectory ( _ /"target/web/public/test" )
I've tried rebuilding the project and module in IntelliJ "build" option and "Build Option" when I right click on build.sbt but the import is not found.
sbt dist from Intellij "sbt shell" then File -> "Invalidate caches" with restart of IntelliJ seems to fix the issue
:Invalidate caches screenshot

import error when using Slick in Play

I am using play-scala-starter-example as the base for my application. I want to use 'slick' for accessing mysql DB. After following https://playframework.com/documentation/2.5.x/PlaySlick I added following lines in application.conf
slick.dbs.default.driver="slick.driver.MySQLDriver$"
slick.dbs.default.db.driver=com.mysql.jdbc.Driver
slick.dbs.default.db.url="jdbc:mysql://localhost/playexamplemysql?characterEncoding=UTF-8"
slick.dbs.default.db.username="user"
slick.dbs.default.db.password="password"
The import is used in DbController.scala as follows:
import play.api.mvc._
import play.api.db._
import play.api.libs.json._
import play.api.libs.functional.syntax._
import slick.DatabaseConfigProvider
import slick.jdbc.JdbcProfile
import slick.driver.MySQLDriver.api._
When i run this app, i get following error:
[error] /play-scala-starter-example/app/controllers/DbController.scala:11: object jdbc is not a member of package play.api.db.slick
[error] import slick.jdbc.JdbcProfile
[error] ^
[error] /play-scala-starter-example/app/controllers/DbController.scala:12: object driver is not a member of package play.api.db.slick
[error] import slick.driver.MySQLDriver.api._
Looking at slick APIs these are valid package path names.
build.sbt:
name := """play-scala"""
version := "1.0-SNAPSHOT"
lazy val root = (project in file(".")).enablePlugins(PlayScala)
scalaVersion := "2.11.11"
libraryDependencies += jdbc
libraryDependencies += cache
libraryDependencies += ws
libraryDependencies += "org.scalatestplus.play" %% "scalatestplus-play" % "2.0.0" % Test
libraryDependencies += "com.typesafe.play" %% "play-slick" % "2.0.0"
libraryDependencies += "mysql" % "mysql-connector-java" % "5.1.36"

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)
}

object mongodb is not a member of package com

After run i getting this object mongodb is not a member of package com in Play
I cant resolve that problem. Im trying to do Play Scala MongoDB and from client side Scala.js
my build.sbt is >
lazy val server = (project in file("server")).settings(
scalaVersion := scalaV,
scalaJSProjects := clients,
pipelineStages := Seq(scalaJSProd, gzip),
resolvers += "scalaz-bintray" at "https://dl.bintray.com/scalaz/releases",
libraryDependencies ++= Seq(
"com.vmunier" %% "play-scalajs-scripts" % "0.3.0",
"org.mongodb" %% "casbah" % "3.1.0",
"org.webjars" % "jquery" % "1.11.1",
"com.novus" %% "salat" % "1.9.9",
"se.radley" %% "play-plugins-salat" % "1.5.0",
"commons-codec" % "commons-codec" % "1.6",
specs2 % Test
object code
package model
import com.mongodb.DBObject
import com.mongodb.casbah.MongoConnection
import com.mongodb.casbah.commons.MongoDBObject
/**
* Created by qqQQaAs on 2016-01-04.
*/
object AllBooks {
def toJson() {
val collection = MongoConnection()("books")("books")
val query = "Krakow"
// simply convert the result to a string, separating items with a comma
// this string goes inside an "array", and it's ready to hit the road
val json = "[%s]".format(
collection.find(query).toList.mkString(",")
)
}
Controller
package controllers
import com.mongodb.casbah._
import model.AllBooks
import play.api.mvc._
import shared.SharedMessages
object Application extends Controller {
def index = Action {
Ok(views.html.index(SharedMessages.itWorks))
}
def service() = Action {
val json = AllBooks.toJson()
Ok(json).as("application/json")
}
}
Thanks for help guys
You should import the following pages as per the official documentation:
import org.mongodb.scala._
import org.bson._