FAQ Database Discussion Community


spray akka deployment on webserver

java,scala,akka,spray,xsbt-web-plugin
I have an application built on spray + akka. using this guide: http://sysgears.com/articles/building-rest-service-with-scala/ It explains this example: https://github.com/oermolaev/simple-scala-rest-example The application is working just fine. But when trying to deploy on a webServer I didn't find a way to do that. I've tried to use xsbt-web-plugin to deploy on Tomcat, got...

How to properly use spray.io LruCache

scala,caching,spray
I am quite an unexperienced spray/scala developer, I am trying to properly use spray.io LruCache. I am trying to achieve something very simple. I have a kafka consumer, when it reads something from its topic I want it to put the value it reads to cache. Then in one of...

Custom resourceDirectory for Revolver/Spray

sbt,spray,sbt-revolver
I have a Spray application with a basic front end component with source in src/main/frontend and the deployed version (compiled sass, minification etc.) in Spray's default resources location src/main/resources. I would like to change the resource directory to src/main/frontend for Revolver's re-start task only, in order to see changes quicker...

Limiting File Uploads with Spray

spray
I am building an API with Spray that accepts file uploads. Typically the files will range in size from 100kb to 1mb. Is it possible with spray to limit file uploads to below this size so that anything bigger is rejected? Thanks...

Cryptic Spray Json error message

json,scala,spray,spray-json
I'm receiving the following error message when trying to parse some json: [info] The future returned an exception of type: spray.httpx.PipelineException, with message: Vector("eba760a81b177051b0520418b4e10596955adb98196c15367a2467ab66a19b5c", 600, "AN51SPP6iZBHFJ3aux1jtn6MMMD13Gh3t7", 500, ["1BXVXP82f7x9YWdWuCaCYwad8ZoYayyRYt"], "76a91473758c13a91699376abb8fe76931bdd9bdc04ee388ac", false) (of class scala.collection.immutable.Vector). (AddressUnspentTXORequestTest.scala:14) and I'm not really sure what that means. Here is the piece of json...

Akka consolidate concurrent database requests

scala,akka,spray
I want to be able to make concurrent requests to multiple data repositories and consolidate the results. I am trying to understand if my approach is at all valid or if there is a better way to approach this problem. I am definitely new to Akka / Spray / Scala...

java.lang.ClassCastException: Cannot cast akka.actor.Status$Success$ to akka.actor.Status$Success

akka,spray,spray-dsl
I am facing a weird exception java.lang.ClassCastException: Cannot cast akka.actor.Status$Success$ to akka.actor.Status$Success at java.lang.Class.cast(Class.java:3094) ~[na:1.7.0_45] at scala.concurrent.Future$$anonfun$mapTo$1.apply(Future.scala:405) ~[scala-library.jar:na] at scala.util.Success$$anonfun$map$1.apply(Try.scala:206) ~[scala-library.jar:na] at scala.util.Try$.apply(Try.scala:161) ~[scala-library.jar:na] at scala.util.Success.map(Try.scala:206) ~[scala-library.jar:na] Where the problem is the trailing $ - something...

Implicit jsonFormat for java class

java,json,scala,akka,spray
I have a generated java class: package cc.notsoclever.customerservice public class Customer { protected String name; public String getName() { return name; } public void setName(String value) { this.name = value; } } (generated from WSDL to provide a SOAP interface, but it doesn't matter) I want to connect to a...

Why are my requests handled by a single thread in spray-http?

akka,spray
I set up an http server using spray-can, spray-http 1.3.2 and akka 2.3.6. my application.conf doesn't have any akka (or spray) entries. My actor code: class TestActor extends HttpServiceActor with ActorLogging with PlayJsonSupport { val route = get { path("clientapi"/"orders") { complete {{ log.info("handling request") System.err.println("sleeping "+Thread.currentThread().getName) Thread.sleep(1000) System.err.println("woke up...

spray-routing - akka ask with Marshaller

scala,akka,spray,spray-dsl
I am trying to complete a service in spray.io following examples from original documentation and I am stuck on error message: could not find implicit value for parameter marshaller: spray.httpx.marshalling.ToResponseMarshaller[scala.concurrent.Future[AdImporterServiceActor.StatusOfImport]] val adServiceRoute: Route = { path("service" / "import" / "status") { get { respondWithMediaType(`text/plain`) { complete { adImporterService.ask(GetImportStatus)(1 second).mapTo[StatusOfImport] }...

Spray request - Complete request only after nested futures

scala,akka,spray,spray-client
New to spray and scala. Been struggling to get it right for couple of days now. I am trying to merge facebook oauth2 login + user login details into the database in case the same user logs in by different ways(user/pass or fb login). Pasting below spray routing snippet. path("facebook")...

Spray scala building non blocking servlet

java,scala,servlets,spray
I've builded a scala application using spray with akka actor. My problem is that the request are synchronized and the server can't manage many requests at once. Is that a normal behaviour? what can I do to avoid this? This is my boot code: object Boot extends App with Configuration...

Spray.io log leaks sensitive information

scala,akka,spray
I'm using Spray client to consume a third-party API. Unfortunately, the API I'm consuming is not very secure and utilizes an authentication method using GET query parameters. Sometimes we're getting timeouts or connection issues which we know to deal with applicatively. The problem is that Spray logs this at a...

NodeSeqMarshaller with ContentType charset not resolving

scala,character-encoding,marshalling,spray
Attempting to get a spray endpoint negotiating a postman request for content. My XML marshaller seems to let me down, ie, it never resolves the correct marshaller option based on Accept header and charset. I have the following: object ResponseVO { val NodeSeqMarshaller = Marshaller.delegate[ResponseVO, NodeSeq](ContentType(`text/xml`, `UTF-8`)) { respVO =>...

spray-client upload form with file

scala,spray,spray-client
I have a next form: <form action="/upload" method="POST" enctype="multipart/form-data"> <input type="text" name="name"> <input type="file" name="file"> <input type="submit" value="Upload image"> </form> I want to send request with name and with file I use spray-client for this, when i send only file this work fine: val file = "my-image.png" val bis =...

Not able to set header for content type request in spray

scala,spray
A piece of my code to validate user login is : val loginRoute = path("login") { post { parameter('next ?) { (next) => entity(as[FormData]) { params => implicit ctx => { var headers = List[HttpHeader]() val user = params.fields.find(_._1 == "username").get._2 val pass = params.fields.find(_._1 == "password").get._2 val remember =...

Call Redis (or other db) from within Spray Route

scala,akka,spray,jedis
I am trying to figure out the best way to establish a Redis Pool and then make calls to Redis from within a Spray route. I want to make sure that I can use the connection pool for Redis connections. What would be the best way to instantiate the pool...

Extracting Raw JSON as String inside a Spray POST route

json,scala,rest,post,spray
I've a POST Spray route and the request contains a JSON body (content-type "application/json"). I want a way to extract the raw JSON from this request inside my route. For http://host:port/somepath/value1 I want to extract the post body as TextMsgResponse. But for http://host:port/somepath/value2 I want to extract the post body...

Spray route get response from child actor

scala,akka,spray
I am trying to figure out how I can setup a Master Actor that calls the appropriate children, in support of some spray routes where I am trying to emulate db calls. I am new to akka / spray, so just trying to gain a better understanding of how you...

Implicit jsonFormat for case class with varargs

scala,akka,spray,spray-json
I have a case class containing varargs, with an implicit jsonFormat as follows: import spray.json._ case class Colors(name: String*) object MyJsonProtocol extends DefaultJsonProtocol { implicit val colorFormat = jsonFormat1(Colors) } import MyJsonProtocol._ Colors("CadetBlue").toJson It raises an error: error: type mismatch; found : Color2.type required: Seq[String] => Color2 Note: implicit value...

Spray rejections is not converted to status code?

scala,spray,spray-dsl
I am following spray manual from here. So I put to gather pretty simple test class AtoImportServiceApiTest extends WordSpecLike with MustMatchers with ScalatestRouteTest { "AtoImportService" must { "return HTTP status 401 Unauhorized when accessing withou basic auth" in { Post("/ato/v1/orders/updateStatus") ~>new AtoImportServiceApi().route ~> check { handled must be(false) rejections must...

Processing large downloads with Spray

scala,spray
I'd like to GET a potentially large file with Spray and process it incrementally, rather than loading the whole response entity into memory at once. (Specifically, to process a CSV file line by line.) The request will be to an arbitrary server, so I can't expect a chunked response. Is...

spray app on Heroku: not able to find script created from stage command

bash,scala,heroku,spray
trying my hand at spray/scala for the first time and I am stuck with a deploy error on Heroku here's the contents for target directory locally after sbt clean compile stage ran successfully Anadis-MacBook-Pro:mail-service anadi$ cd target/universal/stage/bin/ Anadis-MacBook-Pro:bin anadi$ ls -ltr total 40 -rw-r--r-- 1 anadi staff 4877 Feb 3...

Akka: multiple dispatcher vs multiple actor system

akka,spray
I am wondering what would be the criteria to choose between having several actor systems in one application over having multiple dispatcher ? What are the consequence of multiple actor system vs multiple dispatcher ? ( or advantage)...

What does N in jsonFormatN in spray mean?

json,marshalling,spray
I'm looking at the code of "Akka and Spray" tutorial in Typesafe's Activator, written by eigengo. I do not get where jsonFormat1, jsonFormat2, ... jsonFormatN is defined and how it does what it does. implicit val sendMessageFormat = jsonFormat2(SendMessage) The above snippet is in scala > api > MessengerService.scala Thank...

Handle services returning Try values in Spray

scala,try-catch,spray,spray-dsl
I am working on a codebase where calling my Spray API need to synchronously call a service that returns a Try which Spray need to format and return over HTTP. My initial attempt looked like this : // Assume myService has a run method that returns a Try[Unit] lazy val...

spray-cache not showing new elements after adding

scala,spray
My aim is to add elements to an existing spray-cache instance. This does not happen without any obvious reason or error. My approach is to use available scala-future api to get intermediate results and available mapping methods of scala-futures (map, foreach) to "unpack" data produced by futures. Here's code showing...

spray.io upgrade causes missing mock library in specs2

scala,spray,specs2,spray-test
I use specs2 in my spray.io project. It all works fine and when I use the following versions. val akkaV = "2.3.6" val sprayV = "1.3.2" val specs2V = "2.3.11" However, recently I tried to upgrade the akka and spray version to the following. val akkaV = "2.3.9" val sprayV...

Spray microservice assembly deduplicate

scala,sbt,akka,spray,microservices
I'm using this template to develop a microservice: http://www.typesafe.com/activator/template/activator-service-container-tutorial My sbt file is like this: import sbt._ import Keys._ name := "activator-service-container-tutorial" version := "1.0.1" scalaVersion := "2.11.6" crossScalaVersions := Seq("2.10.5", "2.11.6") resolvers += "Scalaz Bintray Repo" at "https://dl.bintray.com/scalaz/releases" libraryDependencies ++= { val containerVersion = "1.0.1" val configVersion = "1.2.1"...

Spray Dead Letter msg

scala,akka,actor,spray
I'm trying to execute the following code trait CustomHttpService extends HttpService { import MyJsonProtocol._ import spray.httpx.SprayJsonSupport._ implicit def executionContext = actorRefFactory.dispatcher implicit val timeout = Timeout(5 seconds) val offerActor = actorRefFactory.actorOf(Props[OfferActor], "offer-actor") val defaultRoute = { path("offer" / JavaUUID) { uuid => get { respondWithMediaType(`application/json`) { complete { (offerActor ?...

Where to put favicon for a scala Spray application (i.e. what is the root of the site?)?

scala,rest,akka,favicon,spray
Internet says I should put my favicon.ico in the root of the site to stop Spray from clogging my logs with huge stacktraces. I don't know what the root of the site means, particularly in the context of a RESTful spray application. Suppose my project is in ~/src/my-project - I...

Spray-can NoClassDefFoundError

spray
I'm new to spray, i can't get it to work... :/ My build.sbt: val apacheDeps = Seq( "commons-validator" % "commons-validator" % "1.4.1" ) val sprayAndAkkaDeps = { val sprayV = "1.3.3" Seq( "io.spray" %% "spray-can" % sprayV, "io.spray" %% "spray-routing" % sprayV, "io.spray" %% "spray-testkit" % sprayV % "test", "com.typesafe.akka"...

Spray routing filter path parameter

scala,functional-programming,akka,spray
given this snippet of code val passRoute = (path("passgen" / IntNumber) & get) { length => complete { if(length > 0){ logger.debug(s"new password generated of length $length") newPass(length) } else { logger.debug("using default length 8 when no length specified") newPass(8) } } } How could I replace the if-else with...

Why are all HttpResponse's sent to dead letters (it worked fine so far)?

scala,akka,spray
This morning my code just stopped working. All the HttpResponses are now sent incorrectly to deadLetter. What could be the issue? class MyActor extends Actor { val mediator = DistributedPubSubExtension(context.system).mediator def receive = { case "tick" => { val pipeline = sendReceive ~> unmarshal[MyItems[Id]] val pipeline2: HttpRequest => Future[HttpResponse] =...

Can I modify http response status in completion block?

spray
Is there way to modify the http status code inside of the complete {} block? I've defined a Marshaller to work with scalaz.concurrent.Task like so: implicit def taskMarshaller[A](implicit m: Marshaller[A]) = Marshaller[scalaz.concurrent.Task[A]]{(task, ctx) => task.runAsync(_.fold(l => throw l, r => m(r, ctx))) } and I do complete { Task {...}...

Spray rejection handler not detecting an existing path

scala,http,spray
I have a file static.scala : val staticRoute = { path("") { getFromResource("web/index.html") } ~ pathPrefix("web") { getFromResourceDirectory("web") } } Another file a.scala : val actionRoute = (handleRejections(rejectionHandler) & handleExceptions(exceptionHandler)) { path("action" / "create") { (put | post) { implicit ctx => { val xmlString = ctx.request.entity.asString val actionObject =...

Akka Ask & Futures

akka,spray
I'm an akka noob so apologies! I'm playing around with a system that uses Spray and Akka. I'm using the following code snippet to send a message to another actor. It uses ask which, from what I understand will return a future which is resolved in "mapTo" and "map". I...

Body of HTTP-request as spray-json object

spray,spray-json
I want to create a simple rest-service with spray. The rest service shall receive a json-body via http put. I want to pass the parsed json-string to a function for further processing. Is there any example out there how to do this? I have not found any example how to...

scala spray get long list of parameters

scala,spray
I have an application written on scala/spray, and a GET function that need to receive a long list of parameters (30+). what is the best way to receive them in route as an hashMap or object?...

How to unmarshall a list of case class in Spray

xml,scala,spray,spray-client
First time Spray user failing to find any proper examples on this anywhere. I'm looking to unmarshall the XML API response that contains a List[Person]. Say case class Person(name: String, age: Int). The unmarshaller should produce the appropriate List[Person]. Spray has a default NodeSeqUnmarshaller but I can't figure out how...

Chaining Akka Actors in a Spray Route

scala,akka,actor,spray
I have a restful API that receives an array of JSON messages that will be converted to individual Avro messages and then sent to Kafka. Inside the route, I call 3 different actors: 1) one actor goes out and retrieves the Avro schema from disk 2) then loop through the...

How to get a reference to an existing ActorSystem in Akka?

scala,akka,actor,spray
is it possible in Akka (scala) to get a reference to an existing ActorSystem? I am working on a Spray application with another Actor for DB. I am also extending Directives to have an object per path. the directives are not actors by themselves, but they need to pass messages...

Scala spray immediately close connection after send answer

scala,tcp,spray,so-linger
How scala spray immediately close connection after send answe? In other http server Im set tcp optionsso_linger` = 0 Where I can set so_linger param in spray_can?...

Spray: Testing File Uploads with Specs2

spray,specs2
I have an API built using Spray that handles file uploads. I am trying to write a test for the upload functionality but I'm not getting anywhere fast. I'm nots sure how to structure the test to simulate a file upload. I have the following test... "Valid POST Requests should...

Execute some logic asynchronously in spray routing

scala,akka,spray
Here is my simple routing application: object Main extends App with SimpleRoutingApp { implicit val system = ActorSystem("my-system") startServer(interface = "0.0.0.0", port = System.getenv("PORT").toInt) { import format.UsageJsonFormat._ import spray.httpx.SprayJsonSupport._ path("") { get { complete("OK") } } ~ path("meter" / JavaUUID) { meterUUID => pathEnd { post { entity(as[Usage]) { usage...

Akka-Spray object marshall

json,scala,akka,marshalling,spray
I am experimenting with aka and spray, what I want to achieve is a simple object marshalling service. When I try to compile the code I get the following error : Error:(33, 18) could not find implicit value for parameter marshaller: spray.httpx.marshalling.Marshaller[ExampleApplication.Password] marshal(Password(randomString(8),i,0)) ^ Here is the code: import akka.actor.ActorSystem...

Akka IO and TestActorRef

scala,akka,spray,spray-client
If I need to write an integration test involving HTTP request via spray-can, how can I make sure that spray-can is using CallingThreadDispatcher? Currently the following actor will print None class Processor extends Actor { override def receive = { case Msg(n) => val response = (IO(Http) ? HttpRequest(GET, Uri("http://www.google.com"))).mapTo[HttpResponse]...

Combining Spray Routing + Actor Pattern Matching

scala,akka,spray,akka-cluster
Following the Akka Cluster documentation, I have the Worker Dial-in example running. http://doc.akka.io/docs/akka/snapshot/java/cluster-usage.html So I've trying to integrate that with a spray routing. My idea is to have a cluster behind the scenes and through a http rest, call that service. So I have the following code. object Boot extends...

Parsing a simple array with Spray-json

scala,spray,spray-json
I'm trying (and failing) to get my head around how spray-json converts json feeds into objects. If I have a simple key -> value json feed then it seems to work ok but the data I want to read comes in a list like this: [{ "name": "John", "age": "30"...

Spray: delete temporary file after response is sent

scala,spray
I use getFromFile to respond with temporary file. How can I delete this file after it's written to response stream? Underlying server is spray-servlet.

How to use actor to receive http requests and requests from other actors?

scala,akka,spray
I want TestHttp class to be able to receive http requests or messages from other actors. How can I do it? Code: object Main extends App with SimpleRoutingApp { implicit val system = ActorSystem("system") import system.dispatcher implicit val timeout = Timeout(240.seconds) startServer(interface = "localhost", port = 3000) { get {...

Switching from Scalatra to Spray : Handling notFound and errors in spray?

scala,servlets,spray,scalatra
We were Scalatra users. Everytime we would create a servlet , we would extend our BaseServlet which extend ScalatraBase : trait BaseServlet extends ScalatraFilter with ScalateSupport with FlashMapSupport { /** * Returns the request parameter value for the given argument. */ def getParam(key:String)(implicit request: HttpServletRequest): Option[String] = Option(request.getParameter(key)) notFound {...

serializing polymorphic classes using spray.json getting could not find implicit value for evidence parameter of type

scala,spray
I am trying to produce json trait Bar case class Foo(name:String) extends Bar case class Buz(name:String,age:Int) extends Bar case class Responsive(id:String ,bars:List[Bar]) when calling import spray.json._ val foo = Foo("foo") val fooRes = Responsive("abc",List(foo)) println(fooRes.toJson) I am getting Cannot find JsonWriter or JsonFormat type class for com.demo.Responsive println(s" res =...

Sending large files with Spray

scala,akka,spray
I know very similar questions have been asked before. But I don't think the solutions I found on google/stackoverflow are suitable for me. I started to write some web services with Scala/Spray, and it seems the best way to send large files without consuming large amouns of memory is using...