w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Play Framework 2.1.1 cannot find play object in multi-project setup Build.scala
Are you sure the Play plugin is correctly loaded ? Without it, the Play library cannot be used in the Build file (or anywhere else). As explained here, the project/plugins.sbt file must contain the plugin definition. You can look at these samples to have working examples of this file: // The Typesafe repository resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/" // Use the Play sbt plugin for Play projects addSbtPlugin("com.typesafe.play" % "sbt-plugin" % Option(System.getProperty("play.version")).getOrElse("2.0"))

Categories : Scala

Partially applied functions with all arguments missing in Scala
I'm sure others can synthesize a bunch of use-cases for this, but really it's just a consequence of the fact that functions are values. It would be much weirder if you couldn't pass a function around as a normal value. Scala's handling of this stuff is a little clunky. Partial application is usually combined with currying. I consider it a quirk that you can basically eta-expand any expression using _. What you're effectively doing (modulo Scala's syntactic quirks around currying) by writing add(_ : Int, _ : Int) is writing (x : Int) => (y : Int) => add(x, y). I'm sure you can think of instances where the latter definition might be useful in a program.

Categories : Scala

QuickSort can't be applied to ArrayBuffer to do sorting In place in Scala
I believe the answer to your question can be found by examining the source code of Scala, to determine just what behavior you can get from the built in functions that come with ArrayBuffer : sortWith, sortBy, etc.. These functions come from defining trait "SeqLike" (you can examine the source code by browsing to that class in ScalaDoc, and clicking the link to next to source:"Seqlike" at the top of the documentation.. Anyhow most of the code related to sorting just gets pushed off this function: def sorted[B >: A](implicit ord: Ordering[B]): Repr = { val len = this.length val arr = new ArraySeq[A](len) var i = 0 for (x <- this.seq) { arr(i) = x i += 1 } java.util.Arrays.sort(arr.array, ord.asInstanceOf[Ordering[Object]]) val b = newBuilder

Categories : Arrays

Scala class wrapping a partially applied constructor - how to use it to create API methods?
This is what I would do: object Interval { case class HalfInterval(start: Time) { def to(end: Time): Interval = Interval(start, end) def forMinutes(minutes: Int): Interval = to(getEnd(start, minutes)) private def getEnd(start: Time, minutes: Int) = ??? } def from(start: Time): HalfInterval = HalfInterval(start) } getEnd() adds the minutes parameter to start.minute, divided by 60, adds the result to start.hours and the rest of the division to minutes and there you build the end Time. (Then maybe do the hour modulus 24 in case you go to the next day). Edit: HalfInterval should be value class, but don't worry about that.

Categories : Scala

How to scale Play2 Evolutions
Actually Play has not possibility to divide evolutions by entities. IMHO it's rather matter of taste, you can add each entity in single next evolution, anyway only difference will be that counter of evolution will be bigger, I don't think that will help you to keep evolutions cleaner. Typical workflow is starting from ... good planning. Just create some graph representation of your schema and try to add there as many things as you need. It helps a lot while the project startup and also in next steps of development. If you are gonna to use Ebean, create all models from your graph and let the plugin to create automatic first evolution file, probably you will save a lot of time on writing evolutions for relations, constraints, etc. Spend some time for fixing and checking initial schema b

Categories : SQL

How to use jQuery UI with Play Scala
first of all you need to define an endpoint for your data in the controller. Simething like this: def autocompleteSearch(a: String) = Action { request => val data = List("apple", "apple iphone", "apple ipad", "microsoft windows", "microsot office"); val filteredData = data.filter(_.startsWith(a)) Ok(Json.toJson(filteredData)) } Then you need to add this endpoint to your routes: GET /some-ajax controllers.Application.autocompleteSearch Then in your .scala.html file you can write a script that will do a get you you, example: var updateTime = function() { $.get("@routes.Application.timeUpdate()", function(data) { display.html(data) }) return false } When you have the var you just pass it to the jQueryUI. My ex

Categories : Jquery

Scala Play Framework 2.1.1 JSON
__ is an alias for JsPath companion object is the operator to parse the symbol to read from the Json object. And tupled just puts them into a tuple so you can do something like case (name, age) => as in the example in the doc you posted.

Categories : Json

Can I use Scala List with Slick (Play)?
You can do that by defining a type mapper from let's say List[Int] to String and vice-versa. One possibility: implicit def date2dateTime = MappedTypeMapper.base[List[Int], String]( list => list mkString ",", str => (str split "," map Integer.parseInt).toList ) I say it's a possibility 'cause I haven't tested. Not sure the fact it's returning a list will disrupt Slick. One place where it can be ambiguous are aggregate queries, where you'd want to count the number of , and not do a count(field) (which will obviously be one). But this is completely non-relation. The relational way would be to have a new table with two fields, one foreign key referring one line at table SCORES and another field with one SCORE_PER_TIME. The foreign key should be a non-unique index so searches ar

Categories : Scala

play scala json of map with list
You can solve this problem by transforming your Map[User, List[Address]] to a List[User], and the JsonWriter will became easy to write. Something like: list.map { case (user, address) => user.copy(addresses = address.toSeq) }

Categories : Scala

Can't get the id in play framework scala program
The error message tells you what is wrong. Your userprofiles is a list of UserProfile. It does not have a member called id. Yet, you are trying to access it: @for(userprofile <- userprofiles.id) // ^--- this is invalid I think what you are trying to do is: @for(up <- userprofiles){ @if(up.id == userprofile.id) {} else { ... } }

Categories : Scala

Scala Play Json Reads
Just add the business key in the path: implicit val bsnsRds = ( (__ "business" "name").read[String] ~ (__ "business" "preferredUrl").read[String] ~ (__ "business" "businessPhone").read[String] ~ (__ "business" "retailer").read[Retailer](rltRds) )(Business)

Categories : Json

Play Scala Anorm One to Many relationship
A side note about something I have found useful: if youre not sure you will always want to fetch the addresses for a user you can avoid adding that relation as a field and instead use tuples or other datastructures for representing. This would allow you to have a method like this: def allUsersWithAddresses(): Map[User, Seq[Address])] = ... But still have methods that returns only users without having the joined data. To read a join (or subselect) you will have to parse the combined output with a parser, something like this: .as(User ~ Address *).groupBy(_._1) If you really want to put the addresses inside of user you'd have to make the adress list empty from the user parser and then map each distinct user into one with the addresses: .as(User ~ Address *).groupBy(_._1).map { cas

Categories : Mysql

Scala JSON Reads in Play 2.1.1
Try this: import play.api.libs.json._ import play.api.libs.functional.syntax._ implicit val priceReads:Reads[Price] = ( (__ "base").read[Int] ~ (__ "sale").readNullable[Int] )(Price.apply _) Strange that just passing case class is not working ...

Categories : Json

How to mavenize a Scala / Akka / Play project?
Don't use Maven - use SBT - it's the build tool of choice. Note maven is now squarely in the thoughtworks radar Hold section meaning nobody should be building new projects on it if you trust Fowler's advice: http://www.thoughtworks.com/radar Play comes with sbt under the hood already so you shouldn't have to look to far from where you are now: http://www.playframework.com/documentation/2.0/Build

Categories : Scala

What's the conventional way to handle a transaction in Play 2 Scala?
I'm not sure that there is a best practice for this yet. I look forward to reading other people's answers. This page should show you how to do what you want to do. Basically in Global you either extend WithFilters or override doFilter. You're still just wrapping the Action, but you're doing it from a central place. Now, whether or not this is a better idea than doing the action compsoition as suggested here, I don't know.

Categories : Database

Async Request in (Scala) Play "Hangs"
OK, I figured it out. Oh what a pain that was. The issue was that my "fire and forget" task was a long running task. But the thread pool size on the deployment machine ended up being smaller than my development machine. As a result, this long running task dropped in the thread pool and clogged it up. So the processing of the AsyncResult was presumably preempted by the long running calculation (it was actually blocking on a result from a long running calculation, but the bottom line is that it blocked). After reading a really nice explanation of futures in Scala 2.10 by Heather Miller, I noticed the blocking construct that can be used to temporarily expand the size of the thread pool for a single future. I wrapped my blocking code with a blocking call and that did the trick. Presuma

Categories : Scala

Play 2.1 Scala JsValue to Java ObjectNode
I think you can improve this a little by replacing val list = getEvents(id, limit) val buffer = new scala.collection.mutable.ListBuffer[JsValue] list.foreach(e => buffer += Json.toJson(e)) with val jsonEvents = getEvents.map(e => Json.toJson(e))

Categories : Json

Run scala compiler with options from play console
You can add scalac options in the project/Build.scala file. Open this file and add your own project settings into the Play project object at the bottom of the file. For example: val main = play.Project(appName, appVersion, appDependencies).settings( // Add your own project settings here scalacOptions += "-feature" )

Categories : Scala

Play framework scala and mysql error
I think it would work if you removed the quotes altogether (or use backticks, as suggested by Carsten). Here is the doc: http://dev.mysql.com/doc/refman/5.0/en/identifiers.html

Categories : Mysql

Scala JavaScript Routing Play Framework
Your javascript route is defined as: GET /javascriptRoutes controllers.TrackController.javascriptRoutes Edit: play uses a special reverse route for javascript, under routes.javascript. so your reverse controller will be at controllers.routes.javascript.TrackController.Track: @helper.javascriptRouter("jsRoutes")( routes.javascript.TrackController.Track ) You also need to make an implicit RequestHeader available in your template. So add at the beginning of your template: @(implicit request: RequestHeader) Or if you already have template parameters: @(<your parameters>)(implicit request: RequestHeader) And make sure it is available in your controller's Action: def myController = Action { implicit request => // <-- request is a RequestHeader // ...

Categories : Scala

Accessing value by javascript Play Framework/Scala
1) Is this code in your controller? And are the node variable in scope? If so this should be perfectly legal code, since it will be evaluated as pure scala. 2) The templates are a different story however. You probably know they parse everything as normal html, unless escaped. To use a variable you have to bring it into scope by either: defining a 'constructor' for the template at the absolute beginning of the file: @(node : Node) ... @node.name // later in the file See http://www.playframework.com/documentation/2.0/ScalaTemplates or define a variable inside the template: @defining( Get.node.from.somewhere ) { node => @node.name } See Play! framework: define a variable in template? If you did either of the two, you should have no problem accessing the node variable.

Categories : Scala

Simple Websocket in scala / akka / play
There are two parts in a WebSocket connection: the server and the client. You could just make the server part using Play2 and implement a client with Android (see websocket-android-phonegap), iOS (see Unitt), javascript app... Here is an example for a very basic websocket connection taken from http://blog.tksfz.org/2012/10/12/websockets-echo-using-play-scala-and-actors-part-i/: package controllers import play.api.mvc._ object Application extends Controller { def index = WebSocket.using[String] { val out = Enumerator.imperative[String]() val in = Iteratee.foreach[String] { msg => out.push(msg) } (in, out) } } You only have to set a route that points to your controller conf/routes: GET /connect Application.index The server is ready to run. You c

Categories : Scala

Run scala script with play framework classpath?
The easiest way is to do this from a play project and use the play console. create a new play project and go to the created folder launch the play console (just type play from your shell) from the play console, launch the scala console with the console command You can then load a specific scala file using :load. Ex : scala> :load /path/to/my_script.scala

Categories : Scala

Scala Play framework 2.1 derived classes
The json API extensively uses implicit parameters which is a feature of Scala where you can provide an "implicit" parameter list and if you don't specify those parameters the compiler will try to find an object in the current scope that is marked as implicit and matches that signature. So if you for example would write: implicit val s = "my implicit string" def magicPrint(implicit message: String) { println(message) } // and then call it magicPrint The compiler would select s for the parameter message since it is in scope and has the correct type (String), so after the implicit resolution the last line of code would actually look more like this magicPrint(s) The Format/Writer is selected by the compiler, at compile time, with an implicit parameter. If you look at the signature of

Categories : Scala

Generic way to implement a Pk Writes in Play Scala
The only thing you need to do is ensuring that there is deserializer for type E in scope, because now you can't be sure that each type you use is writeable. You can try it: class Value[A](value: A){ def get[A] = value } implicit def valueWrites[E](implicit longWrites: Writes[E]) = new Writes[Value[E]]{ def writes(value: Value[E]): JsValue = Json.toJson(value.get) } Json.toJson(new Value(5L)) You can shorten implicit method to: implicit def valueToJson[E: Writes] = new Writes[Value[E]]{ def writes(value: Value[E]): JsValue = Json.toJson(value.get) } Edit: These two methods above are exactly the same, it means that method needs implicit value, in your case Pk[Long], so this method knows how to deserialize number. In other words, E: Writes tells the method: search for imp

Categories : Scala

Serving local images with Play 2 / Scala
Just add an Action in a Controller that provides the image: def picture(name: String) = Action { Ok.sendFile(new java.io.File(name)) // the name should contains the image extensions } Then add the corresponding route in your routes file: GET /picture/:name controllers.MyPictureController.picture(name: String) And your HTML should look like: <img src="/picture/image.png"> or if you use the Scala templates: <img src="@routes.controllers.MyPictureController.picture("image.png")">

Categories : Scala

How do I create a periodic Poller with Play 2.0 and Scala
I would start by switching your actor over to Akka. Play is already built on top of Akka and the scala actor API has been deprecated and will be removed soon. Then, you can leverage the Akka ActorSystem Scheduler to handle the scheduling aspect and let the actor itself only handle the polling. The refactored actor could look like this: import akka.actor._ class PollingActor extends Actor{ def receive = { case "poll" => //do polling work here } } Then schedule it's execution outside of the actor. All you need is a reference to the ActorSystem that play is running on top of: import scala.concurrent.duration._ val poller = system.actorOf(Props[PollingActor], "poller") val cancellable = system.scheduler.schedule(0 milliseconds, 100 milliseconds, poller, "poll") In

Categories : Scala

Play Framework Scala tuple in view
I know it might be one late answer, but I managed to solve this at that time. Code might be a bit dirty, but I hope it will come in handy to someone. Model part: def intersection(c1:Seq[String], c2:Seq[String]): Seq[String] = { (Set(c1: _*) & Set(c2: _*)).toSeq } Controller part: compareForm.bindFromRequest.fold( hasErrors = {errors => BadRequest(views.html.compares.index(compareForm, username, User.find(username)))}, success = { ldapName => val leftUser = Compare.findAll(ldapName._1) val rightUser = Compare.findAll(ldapName._2) val intersection = Compare.intersection(leftUser.memberOf,rightUser.memberOf) val rightLacking: Seq[String] = (leftUser.memberOf.toSet -- intersection.toSet).toList.map(_.toString).sorted val leftLacking: Seq[String] = (rightUse

Categories : Scala

Play Scala Json Missing Property vs Null
You can use something like : val FooReader = ( (__ "a").readNullable[String] and (__ "b").read(Reads.optionNoError[String]) and (__ "c").readNullable[String] )(Foo) The 'Reads.optionNoError[String]' will produce a JsError if '(__ "b")' is missing. You can actually do something like : val FooReader = ( (__ "a").read(Reads.optionNoError[String]) and (__ "b").read(Reads.optionNoError[String]) and (__ "c").read(Reads.optionNoError[String]) )(Foo)

Categories : Scala

Using scala and java in play framework 2.1 : Session usage
I may be wrong, but I think that your Scala controllers should look like: def myaction() = Action { implicit request => ... } instead of: def myaction() = Action { ... } Ie, you have to add the request to the scope of your Action. And add it also to your view, at the beginning of the file: @(...)(implicit session:Session)

Categories : Java

Scala play - "not found: value routes" (Eclipse and IDEA)
Since there seems to be no answer, I'll at-least describe my workaround: Instead of using <link href=@routes.Assets.at("stylesheets/style.css") rel="stylesheet" type="text/css" /> in my template HTML, I'm using <link href="assets/stylesheets/styles.css") rel="stylesheet" type="text/css" /> Since I'm not invoking routes.Assets.at, there is no issue with not finding the value routes. (However, I'm guessing this workaround will easily crumble when I would have need of more complex templates)

Categories : Scala

Play (Scala) Custom form type validation
I think you can write val dayForm = Form( mapping( "id" -> optional(longNumber), "time" -> number (min =0, max =2), "date" -> sqlDate("yyyy-MM-dd") )((id, time, date) => Entry(id, convertFunction(time), date)) ((entry: Entry) => Some(entry.id, inverseFunction(entry.time), entry.date)) )

Categories : Scala

Scala play catch/log java.lang.ExceptionInInitializerError
You can use play's built in Logger. import play.Logger try { configuration.get("badKey").get } catch { case e:ExceptionInInitializerError => { Logger.error("ExceptionInInitializerError") Logger.error(e.getMessage()) } case e:Exception => { Logger.error("Exception") Logger.error(e.getMessage()) } } Or write an accessor that goes to a default or logs an error without needing a try catch import play.Logger import play.api.Play object Conf { private val config = Play.current.configuration def get(key:String):String = config.getString(key) match { case Some(value:String) => value case _ => { Logger.warn("No value found in application.conf for [" + key + "]") "some default value" } } }

Categories : Scala

Need to validate nested json arrays in play 2.1 in scala
First of all, ensure you are using the latest Play 2.1.1 releases. There was an issue with earlier versions when validating case classes with a single field. After that, it should all work - please see below for an example: object JsonTest { case class SecondStructure(index: Int) case class EntryStructure(field1: String, muSecondJsonArray: List[SecondStructure]) case class MyJsonArray(allEntries: List[EntryStructure]) // Use the macro "inception" feature to automatically build your Readers. implicit val ssReads = Json.reads[SecondStructure] implicit val esReads = Json.reads[EntryStructure] implicit val arrayReads = Json.reads[MyJsonArray] // Defining an example instance... val testArray = MyJsonArray( List( EntryStructure("foo", List(SecondStructure(1), Sec

Categories : Scala

Idea does not recognize plugins (on scala) for Play framework 2.1.1
You just need to relaunch the idea command, after sbt has refreshed your dependencies Add a dependency in Build.Scala sbt> reload sbt> idea Open idea, a popup will alert you to reload the project.

Categories : Intellij Idea

Using Scala's Play & Slick with two form (validation & insertion)
I am not very familiar with Play form handling but Regarding 1: Instead of (Coffee.apply)(Coffee.unapply) you could use something like ({ case (a,b,c,d) => (Coffee(a,b),OtherRow(c,d)) })({ case (Coffee(a,b),OtherRow(c,d)) => (a,b,c,d) }) to separate fields into different entities. And later Coffees.insert(entity._1); OtherTable.insert(entity._2) Regarding 2: HTTP requests like POST are user input, which you can't trust. Make sure that whatever comes in does not misbehave. First, make sure you do NOT insert into the * projection, but into a separate one, which does not include the id column. Then nobody can insert an id. (The computer-database sample in play-slick is a bad example for this at the moment, because it uses * to define autoInc.) You can find an updated (but also more

Categories : Scala

How do I unit test a controller in play framework 2 scala
Using Mockito with Specs2, I mock services to verify their method calls. My controller is instantiated by Spring. That allows me to treat it is as a class instead of object. => That is essential to make controller testable. Here an example: @Controller class MyController @Autowired()(val myServices: MyServices) extends Controller To enable Spring for controllers, you have to define a Global object, as the Play! documentation explains: object Global extends GlobalSettings { val context = new ClassPathXmlApplicationContext("application-context.xml") override def getControllerInstance[A](controllerClass: Class[A]): A = { context.getBean(controllerClass) } } My unit test doesn't need Spring; I just pass collaborators (mocks) to constructor. However, concerning the render

Categories : Unit Testing

scala play form how handle java bigdecimal
Looks like problem in anorm or somewhere near. As you may see from error description sys_owner1_id and sys_owner2_id are BigIntegers in query result, but declared as long in form. I am not familiar with anorm, but solution is to declare these ids as long in anorm, or declare them as BigInteger in form mapping or convert from BigInteger to long in your query.

Categories : Scala

How to trim a JsArray in Scala Play Framework 2.1 using transformers
It works, but probably it's not best option: import play.api.libs.json._ import play.api.libs.json.Reads._ import play.api.libs.functional.syntax._ val transformer: Reads[JsArray] = of[JsArray].map{ case JsArray(xs) => JsArray(xs.flatMap{ case x: JsObject => Some( x.transform( (__ "keyA").json.pickBranch and (__ "keyB").json.pickBranch reduce ).get ) }) }

Categories : Scala

Understanding a Scala function from Play framework zentask example
A parameter of the form fn: => String represents a 'generator' (either a function or a value) that returns (or is) a String, so, for example, you might have a method defined as def myMethod(fn: => String): String = "Fn output = " + fn and call this as follows (the return types I use here can typically be inferred by the compiler, I'm just adding them for pedagogical purposes): def myFn: String = "Hello!" // Alternatively: def myFn(): String = "Hello!" // or: val myFn: () => String = "Hello!" // or most simply: val myString = "Hello!" val output = myMethod(myFn) // output = "Fn output = Hello!" Building on this, we can define a method that takes a function that turns a String into an Int, eg: def my2ndMethod(fn: String => Int): Int = fn("4") and call it as follows: de

Categories : Scala



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.