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

Showing multiple logs on one day as one
Depending on the ORM you are using, you'll need to use the group_by functionality. ActiveRecord: Logs.select("date(created_at), sum(something) as something, sum(something_else) as something_else").group("date(created_at)") More information here. Mongoid 3.x.x: Logs.collection.group( :cond => {}, :key => 'created_at', :initial => { something_count: 0, something_else_count: 0 }, :reduce => "function(x, y) { y.something_count += x.something_count; y.something_else_count += x.something_else_count; }" ) More information here.

Categories : Ruby On Rails

PUT Request showing in logs
I don't think that it is required for PUT to have params in the URL to consider it as restful. You should have the following or something similar HTTPS PUT /users/<userid>/password Body: {password: abcd}

Categories : Rest

GWT.log logs not showing in the GWT Dev Mode console
In order for the logging to work you need to have the following: Logging module inherited in your module xml file: <inherits name="com.google.gwt.logging.Logging" /> Logging level set and handlers configured: <set-property name="gwt.logging.logLevel" value="FINE" /> <set-property name="gwt.logging.systemHandler" value="ENABLED" /> <set-property name="gwt.logging.consoleHandler" value="ENABLED" /> <set-property name="gwt.logging.developmentModeHandler" value="ENABLED" /> <set-property name="gwt.logging.popupHandler" value="DISABLED" /> <set-property name="gwt.logging.firebugHandler" value="DISABLED" /> <set-property name="gwt.logging.simpleRemoteHandler" value="DISABLED" /> You may need a different handler configuration than this one ba

Categories : Java

Symfony2 Fos Rest showing url , giving 500 in logs
The problem that you don't have /test/helloworld route, you have only test/helloworld.html cause for format, html is the default value, id you doesn't specify otherwise. If you want to test for AJAX calls (eg format with json ) AND normal request then leave it like this, but if you will use only with html format, remove the .{_format}, cause then you don't need it.

Categories : PHP

C# web app is using none hard coded path of dev pc showing up on server logs
The folders you see there are taken from the projects debug symbols. They are only there for you to know where the files were located on the build computer. This information is usually not accessible from your code so the error you are encountering is probably something else in the implementation of theme_skin_url.

Categories : C#

Web Deploy Command Line Logs in Event Logs (Updated / Inserted / Deleted Files) in event logs
I don't believe you can log the activities to the event log, but what you can do is use the -xml parameter to output the changes in XML format. You could then use this to log to the event log via a Powershell script, for example.

Categories : Iis

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Scala & Play! & Slick & PostgreSQL auto increment
Here is a suggestion, rewrite your autoInc and add methods like this: def autoInc = name ~ price ~ description returning id def add(product: Product)(implicit s:Session): Long = { Products.autoInc.insert(p.name, p.price, p.description) } Some databases own't allow you to insert null in the auto increment column. Maybe it's the Postgres case.

Categories : Postgresql

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

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

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

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

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

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

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

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



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