object mongodb is not a member of package com - mongodb

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._

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

Need help in setup of Redshift and Scala using Play

I am new to Scala and Redshift, I am trying to connect redshift with play framework. I have tried a couple of things but still not able to connect. i am using these configurations
db.default.driver=org.redshift.Driver
db.default.url="jdbc:redshift://url:5439/myDb?"
db.default.username="name"
db.default.password="password"
play.modules.enabled += "scalikejdbc.PlayModule"
# scalikejdbc.PlayModule doesn't depend on Play's DBModule
play.modules.disabled += "play.api.db.DBModule"
My SBT file looks like this
scalaVersion := "2.12.4"
libraryDependencies += guice
libraryDependencies += "org.scalatestplus.play" %% "scalatestplus-play" % "3.1.2" % Test
// https://mvnrepository.com/artifact/com.typesafe.play/anorm
libraryDependencies ++= Seq(
"org.scalikejdbc" %% "scalikejdbc" % "3.2.1",
"com.h2database" % "h2" % "1.4.196",
"ch.qos.logback" % "logback-classic" % "1.2.3"
)
// https://mvnrepository.com/artifact/com.amazon/redshift-jdbc41
resolvers += "redshift" at "http://redshift-maven-repository.s3-website-us-east-1.amazonaws.com/release"
libraryDependencies += "com.amazon.redshift" % "redshift-jdbc4" % "1.2.10.1009
"
I am getting this error connecting DB
Setup Redshift with Play Scala
Application.conf
db.default.driver=com.amazon.redshift.jdbc4.Driver
db.default.url="jdbc:redshift://url:5439/db"
db.default.username="name"
db.default.password="password"
SBT file
libraryDependencies += jdbc
libraryDependencies ++= Seq(
"org.scalikejdbc" %% "scalikejdbc" % "3.2.0",
"org.scalikejdbc" %% "scalikejdbc-config" % "3.2.0",
"org.scalikejdbc" %% "scalikejdbc-play-initializer" % "2.6.0-scalikejdbc-3.2"
)
// https://mvnrepository.com/artifact/com.amazon/redshift-jdbc41
resolvers += "redshift" at "http://redshift-maven-repository.s3-website-us-east-1.amazonaws.com/release"
libraryDependencies += "com.amazon.redshift" % "redshift-jdbc4" % "1.2.10.1009"
Controller
package controllers
import javax.inject._
import play.api._
import play.api.mvc._
import play.api.db._
/**
* This controller creates an `Action` to handle HTTP requests to the
* application's home page.
*/
#Singleton
class HomeController #Inject()(db: Database, cc: ControllerComponents) extends AbstractController(cc) {
/**
* Create an Action to render an HTML page.
*
* The configuration in the `routes` file means that this method
* will be called when the application receives a `GET` request with
* a path of `/`.
*/
def index() = Action {
var outString = "Number is "
val conn = db.getConnection()
try {
val stmt = conn.createStatement
val rs = stmt.executeQuery("SELECT 9 as testkey ")
while (rs.next()) {
outString += rs.getString("testkey")
}
} finally {
conn.close()
}
Ok(outString)
// implicit request: Request[AnyContent] =>
//
// Ok(views.html.index())
}
}

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

spray Collection ToResponseMarshallable

I am trying to return a List from my complete directive in spray-routing.
complete {
List("hello")
}
However, I am getting an error -
Expression of type List[String] doesn't conform to expected type ToResponseMarshallable
I am getting the same error with Seq. I see that marshallers for List and Seq are not provided by default in spray-httpx documentation. However, spray-json provides marshalling support in its DefaultJsonProtocol. I have imported spray.httpx.SprayJsonSupport._ and spray.json.DefaultJsonProtocol._ in my code, but that too hasn't helped.
Any idea how can I marshal a List/Seq using spray-json? Or will I have to write my own Marshaller?
(My scala version is 2.11.4)
Using spray 1.3.2 and spray-json 1.3.2 it should be possible.
Make sure you import (although you say you do, but double check).
import spray.httpx.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._
Consider following example:
import akka.actor.{ActorSystem, Props, Actor}
import akka.io.IO
import spray.can.Http
import spray.routing.HttpService
import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent.duration._
import spray.httpx.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._
object Boot extends App {
implicit val system = ActorSystem("so")
val testActor = system.actorOf(Props[TestActor])
implicit val timeout = Timeout(5.seconds)
IO(Http) ? Http.Bind(testActor, interface = "0.0.0.0", port = 5000)
}
class TestActor extends Actor with HttpService {
def receive = runRoute(route)
def actorRefFactory = context
val route = get{
path("ping") {
complete(List("OK"))
}
}
}
Requesting /ping returns ["OK"] which looks okay.
Just for reference build.sbt bellow.
build.sbt
val akkaVersion = "2.3.5"
val sprayVersion = "1.3.2"
resolvers += "spray" at "http://repo.spray.io/"
scalaVersion := "2.11.5"
scalacOptions := Seq("-feature", "-unchecked", "-deprecation", "-encoding", "utf8")
libraryDependencies ++= Seq(
"com.typesafe.akka" %% "akka-actor" % akkaVersion,
"io.spray" %% "spray-can" % sprayVersion,
"io.spray" %% "spray-routing" % sprayVersion,
"io.spray" %% "spray-client" % sprayVersion,
"io.spray" %% "spray-json" % "1.3.1"
)
API for marshalling seems to have changed since akka 2.3.5. For akka-2.4.11.2, SprayJsonSupport needs import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
1) Following is working sbt,
name := "some-project"
version := "1.0"
scalaVersion := "2.11.5"
scalacOptions := Seq("-unchecked", "-deprecation", "-encoding", "utf8")
val akkaVersion = "2.4.5"
libraryDependencies ++= {
Seq(
"com.typesafe.akka" %% "akka-http-experimental" % akkaVersion,
"com.typesafe.akka" % "akka-http-spray-json-experimental_2.11" % akkaVersion,
"com.typesafe.akka" %% "akka-slf4j" % akkaVersion,
"org.mongodb" % "mongo-java-driver" % "3.4.1",
"org.apache.kafka" %% "kafka" % "0.10.1.1",
"org.apache.kafka" % "kafka-clients" % "0.10.1.1",
//test
"org.scalatest" %% "scalatest" % "2.2.5" % "test",
"com.typesafe.akka" %% "akka-http-testkit" % "10.0.9" % "test",
"de.flapdoodle.embed" % "de.flapdoodle.embed.mongo" % "2.0.0" % "test"
)
}
parallelExecution in Test := false
2) And imports are,
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._
object GetMusicResources {
val music_get_api =
path("music") {
get {
complete {
List("my data1")
}
}
}
}
3) Tests
Get("/music") ~> GetMusicResources.music_get_api ~> check {
val response1: Future[ByteString] = response.entity.toStrict(300.millis).map {_.data }
response1.map(_.utf8String).map { responseString =>
responseString shouldBe """["my data1"]"""
}
}
In my case, I was missing the second import in :
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._ // <= this one
In case anyone stumble into the same issue

Cannot find Await from akka

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.