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

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

Related

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"

Symbol 'type <none>.scalacheck.Shrink' is missing from the classpath

I have the following ScalaCheck unit test using Mockito:
import org.scalatest.mockito.MockitoSugar
import org.mockito.Mockito.when
import org.scalatest.prop.PropertyChecks
import org.mockito.Mockito.verify
class PlayerTest extends org.scalatest.FunSuite with MockitoSugar with PropertyChecks {
test("doesn't accept anything but M") {
val mockIOHandler = mock[IOHandler]
val name = "me"
val player = new Player(name)
when(mockIOHandler.nextLine).thenReturn("m")
val apiUser = new Player("player1")
apiUser.chooseHand(mockIOHandler)
verify(mockIOHandler).write("some value")
}
}
In my build.sbt I have the following dependencies:
scalaVersion := "2.12.2"
libraryDependencies += "org.scalactic" %% "scalactic" % "3.0.1"
libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.1" % "test"
// https://mvnrepository.com/artifact/org.mockito/mockito-core
libraryDependencies += "org.mockito" % "mockito-core" % "1.8.5"
For it, I am getting this error:
Error:(12, 41) Symbol 'type <none>.scalacheck.Shrink' is missing from the classpath.
This symbol is required by 'value org.scalatest.prop.GeneratorDrivenPropertyChecks.shrA'.
Make sure that type Shrink is in your classpath and check for conflicting dependencies with `-Ylog-classpath`.
A full rebuild may help if 'GeneratorDrivenPropertyChecks.class' was compiled against an incompatible version of <none>.scalacheck.
test("doesn't accept anything but M") {
Any idea what could be wrong?
Adding scalacheck did the trick for me
lazy val scalaTest = "org.scalatest" %% "scalatest" % "3.0.+"
lazy val scalaCheck = "org.scalacheck" %% "scalacheck" % "1.13.+"

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

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