FAQ Database Discussion Community


ScalaJson: Traversing JSValue structure (JSONPath syntax) where key might be one of two different strings

json,scala,playframework,playframework-2.0,jsonpath
I need to retrieve information from a JsValue that may be structured in a few different ways buy the specific values I'm looking for will always be under similar names. So for example I could have something like: { "name" : "Watership Down", "location" : { "lat" : 51.235685, "long"...

Activator: command not found

java,bash,scala,playframework,activator
I am trying to install activator in my linux system. so first I install java $ sudo add-apt-repository ppa:webupd8team/java $ sudo apt-get update $ sudo apt-get install oracle-java8-installer downloaded succefully then I downloaded activator sudo wget downloads.typesafe.com/typesafe-activator/1.3.4/ypesafe-activator-1.3.4.zip then added path export PATH=$PATH:/home/govind/activator-1.3.4/ then reloaded bash by source ~/.bashrc then I...

How can I get the ID of an item in a radio-group in a helper.form?

java,scala,playframework
I am building some sort of quiz where the user gets a question and several possible answers. The answers are listed within a radio-group and could be duplicates! Example: How tall is tall? - Very! - Depends on your definition! - Very! The questions and answers come from a list...

Error:Module 'name' production: java.lang.NullPointerException

java,intellij-idea,playframework
I'm running my Java project in IntelliJ 14.1.1 and I'm using play framework. For some reason I can't compile any part of the code in IntelliJ (even though everything is working perfectly in the play environment). I get this error when trying to compile : Information:5/26/15, 19:26 - Compilation completed...

Activator fails creating new project with java.lang.RuntimeException

playframework,typesafe-activator,activator,typesafe
Activator fails when creating a new project when running command from path [email protected]:~/projects$ activator new Fetching the latest list of templates... Browse the list of templates: http://typesafe.com/activator/templates Choose from these featured templates or enter a template name: 1) minimal-akka-java-seed 2) minimal-akka-scala-seed 3) minimal-java 4) minimal-scala 5) play-java 6) play-scala (hit...

Finding the implicit value for Json in play

scala,playframework,implicit-conversion
When I use the following code: import JsonImpl.graphFormat val js = Json.toJson(g)(graphFormat) My code compiles and works fine but when I do this it doesn't work and says: "No Json serializer found for type SGraph. Try to implement an implicit Writes or Format for this type." import JsonImpl.graphFormat val js...

No Json formatter found for type Seq[models.Comment] Try to implement an implicit Format for this type

scala,playframework,playframework-2.0
Hello scala and playFramework gurus, I don't understand why usage of implicit Json.format[Comment] does not work in my code. From the docs description it should works as Format[Comment] but looks like it doesn't. Here is code of my two case classes with their companions case class ServiceTask(id: Option[String], name: String,...

How can I load database entries into my scala template?

database,scala,playframework
I am using play 2.3.8 and building a program where you can ask questions and answer them. I have several different users, so I use their unique email as the ID in the database. Questions / answers have an ownerID, to show who has written them. My users are stored...

Model.Finder Deperecated Play! 2.4

java,model-view-controller,playframework,ebean
I am building an application using the latest version of Play!. When defining a Finder( as in Model.Finder) my IDE gives me a warning Finder is deprecated. I can't find any information in the documentation about Model.Finder being deprecated of any alternative to using it. Has anyone experienced a similar...

Is there a way to locate line from stack trace in Playframework?

playframework
I'm using Playframework 2.3.9 and having problem that occurs only in Selenium test in Jenkins build. at scala.collection.immutable.List.map(List.scala:285) ~[scala-library-2.11.6.jar:0.13.8-M5] at views.html.showOrderHistory$.apply(showOrderHistory.template.scala:47) ~[classes/:na] at controllers.OrderHistory$$anonfun$showOrderHistory$1$$anonfun$apply$3$$anonfun$apply$4.apply(OrderHistory.scala:70) ~[classes/:na] It shows line number of the code generated by template. Since this occurs only in Selenium test in Jenkins and not in my local PC....

Sticky Cookies in Scala

javascript,scala,cookies,playframework,playframework-2.0
I've set a cookie in Scala similar to the following: val cookies:Seq[Cookie] = new Seq() val nDaysExpire:Int = 2000 val nSecondsExpire:Int = nDaysExpire * 24 * 60 * 60 val cookie:Cookie = new Cookie(sCookieID, sValue, Option(nSecondsExpire)) cookies = cookies:+ cookie Ok(views.html.main(sID)).withCookies(cookies:_*) and then I immediately delete the cookie in JavaScript....

CSS to conf/messages in play framework

java,css,intellij-idea,playframework,playframework-2.0
I have messages under conf directory of play framework. required.message=This field cannot be empty And in the model, I have: @Constraints.Required(message = "required.message") public String name; I am getting the messages properly on validation. What I want to do is, change the color of the messages. Currently I am getting...

Play framework Scala actions

scala,playframework,playframework-2.3
As someone new to Scala, can someone explain the code here? val echo = Action { request => Ok("Got request [" + request + "]") } So I get that you're creating a new value called echo, from an Action trait (similar to a Java interface from what I can...

Global Exception Handling in play framework java 2.3.7

java,exception,playframework
I am trying to implement global exception handling in Play framework(RESTful) using Java. While searching I found out that extending GlobalSettings and overriding the onError method should handle all errors and give the appropriate response/view. But in the console where I execute "activator run", I still get the ugly stack...

PlayFramework HTML, variable into Javascript?

javascript,scala,playframework,reactjs
Imagine a simple Play Action defined as def reactTest = Action { request => Ok(views.html.hello("JOHN")) } and the hello.scala.html looks like this, using a basic React.js example: @(name: String) .... <div id="example"></div> <script type="text/jsx"> React.render( <h1>Hello, @name!</h1>, <---- NAME PARAMETER USED HERE document.getElementById('example') ); </script> This works fine and the...

Play Framework @routes.Assets.at Compilation Error

java,playframework,java-8,playframework-2.4
I'm using Play 2.4.0 and I've been trying to follow the tutorial from the main page: https://playframework.com/ which is for Play 2.3 and after solving a couple of issues regarding changes in the Ebean ORM from version 2.3 to 2.4, I'm stuck with the following error: Compilation error value at...

Play + ReactiveMongo: capped collection and tailable cursor

mongodb,scala,playframework,reactivemongo,capped-collections
I'm using Play Framework with Scala, Akka and ReactiveMongo. I want to use a collection in MongoDB as a circular queue. Several actors can insert documents into it; one actor retrieves these documents as soon as they're available (a sort of publish-subscribe system). I'm using capped collections and tailable cursor....

How to recover an error from a Future in an EssentialAction

scala,playframework,future,iteratee
Starting with the example from this post, I'm wondering how to deal with recover: def HasToken(action: String => EssentialAction): EssentialAction = EssentialAction { requestHeader => val maybeToken = requestHeader.headers.get("session") val futureIteratee: Future[Iteratee[Array[Byte], SimpleResult]] = maybeToken map { token => //This returns a future... Session.find(token).map { case Some(session) => action(session)(requestHeader) case...

Retrieving number of rows with non-empty one-to-many relation

playframework,playframework-2.3,ebean
I am using Play Framework 2 (Java) together with Ebean. Among my model classes, I have classA with a one-to-many relation to classB. The associated table for classB therefore has a field which either contains nullor an id for a classA entity. I would like to retrieve the number of...

Faking Ajax Request Form for testing

java,ajax,unit-testing,playframework,playframework-2.0
In my Playframework 2.4 project I have methods like this: public static Result resetValue(int client) { String receivedName= form().bindFromRequest().get("username"); User user = User.findByName(receivedName); if( user == null ) { return badRequest("No user logged in"); } user.setValue(0); user.saveUsertoDB(); return ok("Value set to zero"); } I want to write JUnit Tests for...

Doesn't work debug for play project in IDEA 14 Ultimate

scala,debugging,intellij-idea,playframework,breakpoints
I do following steps: Import to IDEA Play project generated with Activator UI from Play Scala Seed template. Create Run/Debug configuragion using standart "Play 2 App" template. Add break point in my project. Run debug and open page in a browser. I can see in IDE console "play - Application...

Slick 3.0: Idiomatic way to GET results from the database inside of Option (Scala Play Framework)

scala,playframework,slick,slick-3.0
I have this code for an API that allows me to retrieve and object from the database and return a JSON object using Slick 3.0: // Model case class Thing(id: Option[Int], name: String) object Thing { implicit val teamWrites = Json.writes[Thing] } class Things(tag: Tag) extends Table[Thing](tag, "thing") { def...

How to write a custom form helper template for dynamically generated content?

html,css,twitter-bootstrap,scala,playframework
I have some sort of quiz system, where to user gets shown a question and several answer-options with radio-buttons. But as I am using a helper for a inputRadioGroup that gets filled via a list, it does not look pretty anymore (like Twitter Bootstrap). The radiobuttons are inline, while they...

When I select a row in MySQL using hibernate classes, it makes an update automatically

java,mysql,hibernate,playframework,playframework-2.2
I'm trying to develop a blacklist for my users including several variables. So when a user sign up in my application, I check if some parameters are blacklisted or not. The problem is that when I perform a select and the database find something that fits with my search, it...

Can I ignore the “twitter bootstrap is deprecated” warnings in my code?

twitter-bootstrap,playframework,deprecated,playframework-2.3
I am using the play framework 2.3.8 with twitter Bootstrap 3.3.4 and have several forms in my application, where you can enter input. Sample: @import models.Question @import models.Answer @import helper._ @import helper.twitterBootstrap._ @(questionForm: Form[Question], questionList: List[Question]) @main("Ask Question"){ @helper.form(action = routes.Application.sendQuestion()){ <fieldset> @helper.inputText(questionForm("questionID")) @helper.inputText(questionForm("questionText")) @helper.inputText(questionForm("voteScore"))...

Cast and instance of in scala view template in playFramework

java,scala,templates,view,playframework
I am looping over collection of Person in scala view in PlayFramework2.2.6. Person class is superclass for classes User,Contact. While looping I would like to access some parameters specified for extending classes like email attribute in User class. Here is model's classes: public class Person { int id; String name;...

Complete override of error handler in PlayFramework

playframework
When an unexpected exception is generated in a Play application, you can override the response in Global.onError(). However, the exception still seems to get written as an ERROR log by Play. Is there any way to override that behaviour (only for specific exceptions)? Case explanation: Generally the response to an...

Import implicit variable for generic class from implementation

scala,playframework,reactivemongo
I have an issue in Scala I'm really stuck on. I know the title is probably more confusing so let me try to explain it as easy as possible. Imagine I have an abstract class called Repo. This class describes a couple of methods on them, most of them are...

Playframework Scala Transform Request from Json to x-www-form-urlencoded

scala,playframework
Hi I am new to Scala and Playframework. I am getting an ajax request that is json format and I need to make another request to another server with x-www-form-urlencoded format. I have this code in the controller def getToken = Action.async(parse.json) { request => WS.url("https://api.xxxx.com/v1/yyyy") .withHeaders( "accept" -> "application/json",...

Auto reload with play2

java,maven,playframework,maven-plugin
This is my play2 project having maven nature: pom.xml with relevant code: <packaging>play2</packaging> <plugin> <groupId>com.google.code.play2-maven-plugin</groupId> <artifactId>play2-maven-plugin</artifactId> <version>${play2.plugin.version}</version> <extensions>true</extensions> <configuration> <!-- only if using database evolutions --> <serverJvmArgs>-DapplyEvolutions.default=true</serverJvmArgs> </configuration>...

How to use `controllers.Default.redirect` in Play 2.4 and `InjectedRoutesGenerator`

scala,playframework,playframework-2.4
If I try to use controllers.Default.redirect(to = "/foo/bar") in my routes file with routesGenerator := InjectedRoutesGenerator enabled in my build.sbt file, I get the compilation error type Default is not a member of package controllers With this new injected routes feature in Play 2.4 is there still a way to...

Table creation in play 2.4 with play-slick 1.0

scala,playframework,playframework-2.0,slick,slick-2.0
I got the play-slick module up and running and am also using evolution in order to create the required tables in the database during application start. For evolution to work it is required to write a 1.sql script which contains the table definitions that I want to create. At the...

Mac OS X Activator New Play Framework Error

java,osx,scala,playframework,typesafe-activator
I'm running the most recent Yosemite 10.10.3 with the latest activator from Typesafe 1.3.4 and I tried creating a new Scala Project template 6 and I can no longer run the template without this error. [info] Loading project definition from /Users/Master/x/x/project java.lang.UnsupportedClassVersionError: play/runsupport/classloader/ApplicationClassLoaderProvider : Unsupported major.minor version 52.0 at java.lang.ClassLoader.defineClass1(Native...

Play Framework: How to Add a Header to Every Response

scala,playframework,http-headers,token
In the following Controller, Authenticated extracts the token from the request headers and invokes a given action if and only if the token is valid (the code has been simplified for clarity): object MyController extends Controller { def Authenticated(action: Token => EssentialAction) = EssentialAction { requestHeader => val jwt =...

Unit Testing a Play framework Controller

scala,playframework,specs2
I have written this controller which works perfectly from browser package controllers import play.api._ import play.api.mvc._ class Application extends Controller { val productMap = Map(1 -> "Keyboard", 2 -> "Mouse", 3 -> "Monitor") def listProductsXML() = Action { Ok(views.xml.products(productMap)) } } The route is defined as GET /listProducts.xml controllers.Application.listProductsXML Now...

How to keep Akka running all the time in Play 2.3

playframework,playframework-2.0,akka
I am using akka as a scheduler in a website written with Play framework 2.3. I kept the server running by using activator run in dev environment. And when I changed some files and tried to visit my website, the Play server will compile these changed files and reload the...

Is it possible to send log messages to different files with Play Framework?

java,playframework
I'm using PlayFramework 2.2.2 and I'm very interested in knowing if is possible to log my app in different files and how to do it. I would like to have different files for different controllers not for different levels. I have test it to mix several filenames inside conf/application-logger.conf as...

play-slick 1.0.0: Cannot define column with type of java.sql.Date

playframework,slick,play-slick,slick-3.0,playframework-2.4
I'm currently trying to define a slick schema as follows using play-framework 2.4.0-RC5 together with play-slick 1.0.0-RC3: import java.sql.Date import play.api.Play import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfig} import slick.profile.RelationalProfile class Dao extends HasDatabaseConfig[RelationalProfile] { protected val dbConfig = DatabaseConfigProvider.get[RelationalProfile](Play.current) import driver.api._ private class Tab(tag: Tag) extends Table[(Int, Date)](tag, "tab") { def id =...

How to save a file that was uploaded via AngularJS and Play Framework 1.3?

java,angularjs,file-upload,playframework
I'm adding file upload functionality to the form of data collection for some clients. Have such a problem... Here is a simple file upload functionality. I'm uploading the file to the server, but can not save it there. Generally speaking, I would like to keep the file in the database,...

How to know an object has changed compared to database

java,hibernate,jpa,playframework,playframework-1.x
I need to know if some fields of a model object has been changed before save because I need to compare the new values with the old ones. I can't touch the model classes are they are generated. My problem is that whenever I change an object in a controller...

Play - Akka: Actors testing

scala,playframework,akka,actor,akka-testkit
I've read about TestKit, TestActorRef and ImplicitSender provided by Akka. But I didn't found a way to check if a certain actor has received a certain message. I think that "expectMsg(Foo)" can be useful if the receiver-actor does "sender ! Foo". But my application is different: I have an actor...

Play Scala activator compile command shows value userid is not a member of play.api.data.Form[models.Changepas sword]

scala,model-view-controller,playframework,playframework-2.0,typesafe-activator
I am new to play framework(Scala),In my project I need to update new Password for this I need to get user id which is Primary key for that user table. Based on this unique user id value i will update Password. What I need need to get user table's user...

Convert existing SBT Scala application to Play

scala,playframework,sbt,akka
I've been working on building an application with Akka actors, and now that I've completed the actor-based business logic I'd like to give it a RESTful + websocket front-end. I'm trying to find instructions for how to setup Play within the context of an existing application. The only instructions I...

Play Framework using View Tags

scala,playframework
This is my day 1 with play framework and I am using view templates Application.scala package controllers import play.api._ import play.api.mvc._ class Application extends Controller { val productMap = Map(1 -> "Keyboard", 2 -> "Mouse", 3 -> "Monitor") def listProducts() = Action { Ok(views.html.products(productMap.values.toSeq)) } } routes GET /listProducts controllers.Application.listProducts...

AKKA stops logging stack traces after a while

java,playframework,akka,slf4j
I've having a really strange issue with Akka and Play 2.3 (Java). I have a bunch of actors with very standard slf4J logging: public abstract class ScheduledJob extends UntypedActor { protected final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); My akka.conf looks like this akka { loggers = ["akka.event.slf4j.Slf4jLogger"] loglevel = "DEBUG"...

convert play framework route to java URL class (used to initialize java.net.URL class)

java,playframework,playframework-2.0
I want to play song in page when it opening. (I know It's a bad idea but I want to say Happy Birthday to my cousins :D ) for that I need to convert play framework routes to java.net.URL class. I tried these line of code but all of them...

How to get the list of scheduled job and stop it in Play Framework?

java,scala,playframework
I'm using ActorSystem.scheduler.schedule() method, and it can work well the question is: when I want to stop a scheduled job , how can i find it and stop it? I went over the documention and couldn't find how to resolve it.

How does @Inject in Scala work

scala,playframework,dependency-injection,playframework-2.0
I'm wondering how does @Inject annotation in Play-Scala works. It obviously injects a dependency, but I'm curious how is it working. When I was using it on class extending controller and set routes generator to injectroutesgenerator it seems to autmagically create objects from those classes, but how do I use...

How do I implement a PatternAnalyzer in elastic4s and elasticsearch to exclude result with a certain field

elasticsearch,playframework,elastic4s
I'm trying to perform a query on my index and get all reviews that do NOT have a reviewer with a gravatar image. To do this I have implemented a PatternAnalyzerDefinition with a host pattern: "^https?\\:\\/\\/([^\\/?#]+)(?:[\\/?#]|$)" that should match and extract host of urls like: https://www.gravatar.com/avatar/blablalbla?s=200&r=pg&d=mm becomes: www.gravatar.com The mapping:...

Advanced HTTP server configurations in Play 2.3

playframework,playframework-2.0,playframework-2.2,playframework-2.1,playframework-2.3
I am using Play 2.3 to develop an application. I need to set http.netty.log.wire to true which is by default false as specified in Play documents. In the below link (last section) it says this option is available but it also specifies "we cannot use application.conf" to specify this. https://www.playframework.com/documentation/2.3.x/ProductionConfiguration...

EssentialAction: How to Get the Body of a Request without Parsing It

scala,playframework
Given the following EssentialAction... object MyController extends Controller { ... def HasToken(action: Token => EssentialAction) = EssentialAction { request => ... // this doesn't compile val body = request.body match { case json: JsValue => json.toString case _ => "" } // calculate hash with body content here ... }...

Play Framework 2.4 don't accept “public static Result” for controllers

java,playframework
I am try to start an app using Play Framework 2.4 with JDK8 in Mac, when I download the base using ./activator new Project play-java the template code contains the next: Project/app/controlles/Application.java package controllers; import play.*; import play.mvc.*; import views.html.*; public class Application extends Controller { public Result index() {...

Nested Async calls using Scala and Play Framework?

scala,cookies,asynchronous,playframework,playframework-2.0
I would like to make nested asynchronous calls. I would like to perform one async call before I make a 2nd async call. The 1st async call will dictate what parameters or actions to take with the 2nd async call. Here's the original async call: def render(param1:String) = Action.async {...

Not able to access key-values pairs in a JSON using Play library in scala

json,scala,playframework
I am using elasticsearch where as a response from the server I get a JSON. So, val builder = new TermVectorRequestBuilder(client, "new_index", "documents", "0056").setSelectedFields("text") builder.setTermStatistics(true).setFieldStatistics(true) val resp: TermVectorResponse = builder.execute().actionGet() val json_reader = XContentFactory.contentBuilder(XContentType.JSON).prettyPrint() where json_reader is of type org.elasticsearch.common.xcontent.XContentBuilder. Following is what json_reader looks like: "_index""new_index", "_type"...

hot swap in sbt project without play-plugin

scala,playframework,sbt
When I am using play framework, every time I've changed the code, it will take effect automatically by re-compile the code. However, when I'm using sbt to run a project without play-plugin, it won't take effect. I'm wondering if there were a way to make sbt project hot swap the...

Deploying a tar file from CI to heroku

heroku,playframework
I have a play application for my website. Currently, codeship builds it, and heroku deploys it once the build succeeds. The problem is that since the project has become too big, heroku is not able to build it within 15 minutes while codeship can still build it in less than...

The “right” way to use write Slick 3.0 Scala queries in Play Framework

scala,playframework,slick
I'm using Slick 3.0 and (of course) almost all the examples out there cover Slick 2.x. Things have changed and frankly seem more complicated, not less. Here's an example: I want to get an object (a GPPerson) by id. This is what I have right now, and it seems very...

JQuery Grab text from td when button clicked

javascript,jquery,playframework
Using the Scala Play Framework in case there is something that adds to the question here. I have a test function ... <script> $(document).ready(function(){ $('.editbtn').click(function(){ $(this).html($(this).html() == 'edit' ? 'modify' : 'edit'); }); }); </script> and a table <table> <tr><td><button class="editbtn">edit</button></td></tr> <tr><td><button class="editbtn">edit</button></td></tr> <tr><td><button...

Play Framework Java - Display htm file stored on local server

java,playframework,playframework-2.1
Hello Stackoverflow community ! I am working with the Play Framework 2.1.1 using Java. Ideally I would like that, when the user click on a link in the top menu (defined by a Navbar) he gets redirected to a file stored in an internal server. The file path is of...

Providing implicit value for singletons in Play Json library

json,scala,playframework,scala-macros
I have following configuration: sealed trait Status case object Edited extends Status case object NotEdited extends Status case class Tweet(content:String, status:Status) I want to use Play Json format, so I guess I have to have something like this(I don't want to do it in companion object): trait JsonImpl{ implicit val...

Why does Play Framework 2.3.8 Deployment not work?

java,playframework
I have written a program with the play framework 2.3.8 named quizSystem. It is using a memory database, some controller, viewclasses etc. Now I want to run my program on another machine (windows 7 with JDK 8u45 installed and the PATH set to the JDK), therefore I ran activator dist...

Play Framework building select options including a no-op option

scala,playframework,playframework-2.0
I'm creating a search form with a select element which has "Any" as the first option. The rest of the options are widget ids and names. The variable myWidgets is a list of three instances, the result I'm aiming for is along these lines: <select id="widget" name="widget"> <option value="-1">Any</option> <option...

Play Scala 2.4 linking asynchronous calls

scala,asynchronous,playframework,playframework-2.0
I'm trying to figure out how to link multiple asynchronous calls and return a result. I am currently trying to asynchronously user data first, and update user data asynchronously and return result, but it seems like it is not working :( i used map { result => Ok(result)}, but play...

Play Framework routing error that I can't fix

java,playframework
I am building my first controller with the Play Framework. I'm receiving the error: Compilation error value getAll is not a member of controllers.api.protocol.Period My routes.conf file looks like: # Routes # This file defines all application routes (Higher priority routes first) # ~~~~ # Home page GET / controllers.Application.index()...

Configuration depending on launch mode

scala,playframework
Play can be launched in dev mode (via run), in production mode (via start) or in test mode. Is there a way to provide a different config file (conf/application.conf) depending on which mode it is launched in?

How to map all OPTION requests to a certain controller in play 2?

java,playframework,routes
How can i route all OPTION requests to a certain controller in play 2+? I have this route in routes file : OPTIONS / @controllers.CORSController.preFlight I also need to route all OPTION requests to the same controller like : OPTIONS /dev/upload @controllers.CORSController.preFlight OPTIONS /some/path @controllers.CORSController.preFlight ... how can i achieve...

Akka wait for Ack before stopping actor

scala,playframework,akka
I'm using Plays play.api.mvc.WebSockets in combination with akka.contrib.pattern.DistributedPubSub events and this works fine already. class SomeSocketActor(out: ActorRef) extends Actor { val mediator = DistributedPubSubExtension(context.system).mediator mediator ! Subscribe("some_group", self) def receive: Actor.Receive = { case SubscribeAck(Subscribe("some_group", None, `self`)) => context become ready } def ready: Actor.Receive = { // ... }...

Play! Framework support for Java 8 Optional

java,playframework,playframework-2.0,java-8
I've got a Play! 2 routes file and controller that looks something like this: GET /books BooksController.getBooks(author: play.libs.F.Option[String]) public class BooksController extends Controller { public static Result getBooks(play.libs.F.Option<String> author) { ... } } I would like to refactor it to use Java 8's Optional, but this causes a compilation error:...

How do I automatically compile Coffeescript using Typesafe?

scala,playframework,coffeescript,typesafe-activator
First of all I would like to mention that I have downloaded "play-scala-intro" template from Playframework official website, after running this project using terminal command ./activator ui (Ubuntu), the Typesafe UI web application started to listen on port 8888, and "play-scala-intro" application on port 9000. At every change and save...

Play Framework 2.4 @routes.WebJarAssets.at Compilation Error in IntelliJ IDEA 14.1.3

scala,intellij-idea,playframework,intellij-idea-14,playframework-2.4
I'm trying to use WebJars with Play Framework 2.4.0, in Intellij IDEA 14.1.3. I have SBT 1.7.0 plugin and Scala 1.5.2 plugin (with project Scala version 2.11.6). My application works well when I run it from the terminal ($ activator run or $ sbt run) but I have compilation error...

Play Specs2: FakeRequest to WebSocket server

scala,playframework,websocket,specs2
I have a controller with the following method def subscribe(id: String) = WebSocket.tryAcceptWithActor[JsValue, JsValue] I've written the following route in conf/routes: GET /subscribe/:id @controllers.WsManager.subscribe(id: String) The application works but I want to do a specific test through Specs2. I tried to "subscribe" to websocket endpoint with: val request = FakeRequest(GET,...

pass dynamically created data to d3 through playframework

javascript,scala,d3.js,playframework
this is the scenario : we have a web server (playframework) which based on user requirements produces a set of json data, this data then needs to be passed to javascript function. at the moment I can use it only if I retrieve data from a static files, but not...

Play cannot resolve MySQL Driver

java,playframework,sbt,playframework-2.4
I just upgraded to Play 2.4 and for whatever reason I'm unable to load up the JDBC MySQL driver. Here is what I have in build.sbt libraryDependencies ++= Seq( javaJdbc, cache, javaWs, "mysql" % "mysql-connector-java" % "5.1.+", evolutions ) After refreshing (IntelliJ) and running the application, I still receive the...

Ignore dependency jars on dist task

playframework,sbt,sbt-native-packager
I have a Play 2.3.x app that consists of some subprojects, and I use dist to generate a zip package of the full application. The problem is that this package is too big, because it includes every dependency needed for the app to run (ex: scala, play libs, db driver(s),...

Format a string and replace %s with html element in scala play framework

java,scala,playframework
I have a string like "User: %s" and want to format it and replace "%s" with something like <a href="#">John</a>. How should I do it in view files? P.S. I am using "User: %s".format("John") but browser render I am <a href="#">John</a> instead of "I am John"....

ClassCastException when asInstanceOf in for comprehension

scala,playframework,classcastexception,for-comprehension
In PlayFramework 2.4 I try to transform all controllers methods into JavaScript routes. val jsRoutesClass = classOf[routes.javascript] val controllers = jsRoutesClass.getFields.map(_.get(null)) for ( controller <- controllers; method <- controller.getClass.getDeclaredMethods ) yield method.invoke(controller).asInstanceOf[JavaScriptReverseRoute] But the following error occur: Error injecting constructor, java.lang.ClassCastException: java.lang.String cannot be cast to play.api.routing.JavaScriptReverseRoute at...

Play: How to improve error handling and avoid creation of unnecessary throwable instances

scala,exception-handling,playframework
Creating and throwing exceptions is an expensive task... and often in web applications is not necessary to throw exceptions at all. If an error occurs in a service class used by the controller, then throwing an exception makes sense... but if the controller is already aware of the issue (e.g....

Scala Play syntax confustion “&>”

scala,playframework
I am reading a reactive web programming book about Scala and Play. Can someone explain to me what the following code snippet is about? More specifically, what exactly does &> mean? I understand what an iteratee and enumerator is. val jsonStream: Enumerator[JsValue] = enumerator &> Encoding.decode() &> Enumeratee.grouped(JsonIteratees.jsSimpleObject) ...

Play Framework Form Error Handling

scala,playframework,playframework-2.3,playframework-2.4
This is my view file containing the form that has to filled in by the user: @helper.form(call) { @helper.input(resumeForm("surname"), '_label -> "Surname") { (id, name, value, args) => <input name="@name" type="text" value="@value" placeholder="Enter your surname"> } } This is my custom field constructor: @(elements: helper.FieldElements) @if(!elements.args.isDefinedAt('showLabel) || elements.args('showLabel) == true)...

Play 2.3.x: Multiproject, disable BoneCP

scala,testing,playframework,playframework-2.3,specs2
I've got a Play project with some subprojects. One of the subproject needs JDBC, so BoneCP (it accessed MySQL DB). On the other hand, the root project doesn't need JDBC at all. My problem is: JDBC is declared in the build.sbt of the subproject. When I run all the tests,...

Casbah: No implicit view available error

mongodb,scala,playframework,casbah,salat
In a Play app, using Salat and Casbah, I am trying to de-serialize a DBObject into an object of type Task, but I am getting this error when calling .asObject: No implicit view available from com.mongodb.casbah.Imports.DBObject => com.mongodb.casbah.Imports.MongoDBObject. Error occurred in an application involving default arguments. The object is serialized...

PlayFramework: value as is not a member of Array[Byte]

scala,playframework
I want to make file download from a database using Play framework. But when I use this code I get this message: value as is not a member of Array[Byte] And if I change Ok(bytOfImage.as("image/jpg")) to Ok(bytOfImage) it works good but I get a file with a name: secondindex without...

How to do database initialization when using DI in Play 2.4?

scala,playframework,dependency-injection,playframework-2.4
Play 2.4 discourages using GlobalSettings.onStart and whole Global object. I'm using play-slick and it has great DI sample in GitHub, but it is missing a example how to do database initialization. How does one implement the database initialization when using DI and when GlobalSettings.onStart is not available? Common cases for...

Deserialize body of result which is a byte array to json response

scala,playframework,playframework-2.3
I'm trying to take the body of a result and deserialize it into JSON. val str = """ {"protectedBitcoinAddress":"moLM1zdPBSh81eykhfcoLZ3myqUSy9FRRG"} """ val request : JsValue = Json.parse(str) println("Request: " + request.toString) val result : Future[Result] = createUnsignedNLockTime()(FakeRequest().withJsonBody(request)) whenReady(result, timeout(19 seconds), interval(5 millis)) { res => println("==============================") val e: play.api.libs.iteratee.Enumerator[Array[Byte]] = res.body...

Play Framework and Threadpools

playframework,threadpool
Is there a limit on the number of threads that Play framework exposes to my application? Is the thread size inside Play app so darn precious? What if I use a thread pool that I create by myself in the application and not use the one provided by Play. Is...

Where to put user uploaded files in play framework?

java,playframework,playframework-2.0
There is the possibility in my web App that the user can upload different files. the files are not stored in the DB, but in the file System. but I don't want them to be accessible publicly (only throw my Controller). is there any difference between storing the files in...

Play Scala Converting sync to async

multithreading,scala,asynchronous,playframework
I've been trying to run an Action combined with Action async. I want to know how to run a separate async thread to retrieve some data from the server, and do a redirect or badrequest based off of that result asynchronously. Right now I have to send out a status...

How to reuse MappedColumnType in Table classes?

scala,playframework,slick
The use of MappedColumnType is demonstrated in this example: https://github.com/playframework/play-slick/blob/master/samples/computer-database/app/dao/ComputersDAO.scala#L21 How can I reuse dateColumnType in another table class?...

Serialize only specific attributes using Writes trait with unapply

json,scala,serialization,playframework
Lets imagine I have a case class like this: case class Product(ean: Long, name: String, description: String) and I want so serialize objects of this class to Json, I can implement the Writes trait like this: implicit val productWrites: Writes[Product] = ( (JsPath \ "ean").write[Long] and (JsPath \ "name").write[String] and...

Retrieve HTTP status from Promise on Play 2.3.7

java,json,playframework,promise,playframework-2.3
in our project we use JSON for data transmission between front and backend. Basically we creating requests by preparing WSRequestHolder, just like the play doc tells to (https://www.playframework.com/documentation/2.3.7/JavaWS) and then posting a json string. The WSResponse is then mapped "asJson" returned as a Promise. But unlike WSResponse, the JsonNode does...

Play: stop WebSocket actor in case of failure

scala,playframework,websocket,akka
I'm using Play framework and Akka actors for WebSocket communication. I'm using tryAcceptWithActor method: def socket = WebSocket.tryAcceptWithActor[String, String] { request => Future.successful(request.session.get("user") match { case None => Left(Forbidden) case Some(_) => Right(MyWebSocketActor.props) }) } I would like MyWebSocketActor to Stop when it fails (e.g. throwing an Exception). Is this...

Json implicit format with recursive class definition

json,scala,recursion,playframework,play-json
I have a recursive class defined : case class SettingsRepository(id: Option[BSONObjectID], name: Option[String], children: Option[List[SettingsRepository]]) with a JSON implicit format as below : implicit val repositoryFormat = Json.format[SettingsRepository] How can I do to resolve this compilation error? : No implicit format for Option[List[models.practice.SettingsRepository]] available. In /path/to/the/file.scala:95 95 implicit val repositoryFormat...

How to inject something into a form

java,playframework,playframework-2.4
Since play 2.4.0, we can use a DI framework. I am trying to use DI in my app. I moved my jpa finders from static methods on my models classes to methods in a service layer that I inject into my controllers. My main problem is that I have some...

Accessing a javascript file in play framework

angularjs,playframework
value at is not a member of controllers.ReverseAssets not able to access javascript file using [email protected]("assets/app.js") ' <script [email protected]**at**("assets/angular.min.js")'></script> ...

Error running tests in Play Framework after migrating to 2.4.x (Java)

java,playframework,guice,webjars,playframework-2.4
I just migrated from 2.3 to 2.4. The application itself seems to be working, but none of the tests will run. They all fail with the following error: [error] Test models.TestCountry.createTheater failed: com.google.inject.ProvisionException: Unable to provision, see the following errors: [error] [error] 1) Error injecting constructor, java.lang.IllegalStateException: Got deeper than...

Play Framework: How to get the current port number

scala,playframework
How do I get the current port number in a Play application? I use scala.

Play template project requires subscription to typesafe, why?

playframework,typesafe-activator
I'm using Play Framework to create a quick web app. I took template play-java-intro-reactive-platform-15v01, created a new app and when I want to run $ activator test I get an error: [error] == Typesafe Reactive Platform: project/typesafe.properties must exist with typesafe.subscription=< YOUR SUBSCRIPTION ID >. Why? Is it possible to...

Play Framework For Scala: Compilation error[type Application is not a member of package controllers]

scala,playframework,playframework-2.0
I try to compile a scala example in the book: "Play for Scala" but get a following compilation error on Play console: C:\Play\exp\ch6_implicits>activator run [info] Loading project definition from C:\Play\exp\ch6_implicits\project [info] Set current project to ch6_implicits (in build file:/C:/Play/exp/ch6_implicits/) --- (Running the application, auto-reloading is enabled) --- [info] p.a.l.c.ActorSystemProvider -...

Play Framework 2.4 IDE Eclipse directions don't work

eclipse,playframework,sbt,playframework-2.4
The directions can be found here: If I try and do activator eclipse I get an error that eclipse isn't a command. Specifically: "[error] Not a valid command: eclipse" If I I add addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "4.0.0") to plugins.sbt it gives an error....

How to configure the connection pool in Play Framework 1.3 through application.conf and c3p0.properties?

playframework,connection-pooling,c3p0,playframework-1.x
I'm configured the Play 1.3 application to use four databases (on three different servers). There was a problem of leakage connections, this problem has been partially solved, I wrote about this - Do I need to annotate JPA actions with @Transactional in Play Framework-1.x to prevent the connection leak? Now...