GithubHelp home page GithubHelp logo

leon / play-salat Goto Github PK

View Code? Open in Web Editor NEW
201.0 22.0 52.0 208 KB

MongoDB / Salat plugin for Play 2 [MOVED]

Home Page: https://github.com/cloudinsights/play-salat

License: Other

Scala 98.02% HTML 1.98%

play-salat's Introduction

Deprecation Notice

play-salat is now maintained by @amarjitmult over at Cloud Insights.

https://github.com/cloudinsights/play-salat

MongoDB Salat plugin for Play Framework 2

Salat is a ORM for MongoDBs scala driver called Casbah.

The plugin's functionality simpifies the use of salat by presenting a simple "play style" configuration and binders for ObjectId

Build Status

Installation

Use g8 to start a new salat enabled play project

Install g8 on OSX using homebrew

brew update && brew install giter8

Or read about the other ways to install giter8 here

Then run

g8 leon/play-salat.g8

It will ask you a couple of questions, and your ready to rock 'n roll.

Manual installation

Start by adding the plugin, in your project/Build.scala

val appDependencies = Seq(
  "se.radley" %% "play-plugins-salat" % "1.5.0"
)

Then we can add the implicit converstions to and from ObjectId by adding to the routesImport and add ObjectId to all the templates

val main = PlayProject(appName, appVersion, appDependencies, mainLang = SCALA).settings(
  routesImport += "se.radley.plugin.salat.Binders._",
  templatesImport += "org.bson.types.ObjectId"
)

We now need to register the plugin, this is done by creating(or appending) to the conf/play.plugins file

500:se.radley.plugin.salat.SalatPlugin

We continue to edit the conf/application.conf file. We need to disable some plugins that we don't need. Add these lines:

dbplugin = disabled
evolutionplugin = disabled
ehcacheplugin = disabled

Configuration

now we need to setup our connections. The plugin is modeled after how plays DB plugin is built.

mongodb.default.db = "mydb"
# Optional values
#mongodb.default.host = "127.0.0.1"
#mongodb.default.port = 27017
#mongodb.default.user = "leon"
#mongodb.default.password = "123456"

# MongoURI
# ~~~~~
# a MongoURI can also be used http://www.mongodb.org/display/DOCS/Connections
# mongodb.default.uri = "mongodb://127.0.0.1:27017,mongodb.org:1337/salat-test"

# WriteConcern
# ~~~~~
# Can be any of the following
#
# fsyncsafe - Exceptions are raised for network issues and server errors; Write operations wait for the server to flush data to disk.
# replicassafe - Exceptions are raised for network issues and server errors; waits for at least 2 servers for the write operation.
# safe - Exceptions are raised for network issues and server errors; waits on a server for the write operation.
# normal - Exceptions are raised for network issues but not server errors.

#mongodb.default.writeconcern = "safe"

# Replica sets
# ~~~~~
# http://www.mongodb.org/display/DOCS/Why+Replica+Sets
#
# To user a replicaset instead of a single host, omit optional values and use the configuration below instead.
# Since replica sets use public key authentication, user and password won't work together with the replicaset option.

#mongodb.default.replicaset {
#    host1.host = "10.0.0.1"
#
#    host2.host = "10.0.0.2"
#    host2.port = 27018
#}

# Mongo Options
# ~~~~~
# http://api.mongodb.org/java/2.8.0/com/mongodb/MongoOptions.html
#
# For passing custom options to the MongoConnection add the properties under "options". Add just the ones which are different from defaults.

#mongodb.default.options {
#    connectionsPerHost = 100
#    threadsAllowedToBlockForConnectionMultiplier = 1000
#    connectTimeout = 60000
#}

More that one DB?

If you would like to connect to two databases you need to create two source names. You also can specify different options per database

mongodb.myotherdb.db = "otherdb"
mongodb.myotherdb.options.connectionsPerHost = 80

Then you can call mongoCollection("collectionname", "myotherdb")

What a model looks like

All models must be case classes otherwise salat doesn't know how to properly transform them into MongoDBObject's

package models

import play.api.Play.current
import java.util.Date
import com.novus.salat._
import com.novus.salat.annotations._
import com.novus.salat.dao._
import com.mongodb.casbah.Imports._
import se.radley.plugin.salat._
import mongoContext._

case class User(
  id: ObjectId = new ObjectId,
  username: String,
  password: String,
  address: Option[Address] = None,
  added: Date = new Date(),
  updated: Option[Date] = None,
  deleted: Option[Date] = None,
  @Key("company_id")company: Option[ObjectId] = None
)

object User extends ModelCompanion[User, ObjectId] {
  val dao = new SalatDAO[User, ObjectId](collection = mongoCollection("users")) {}

  def findOneByUsername(username: String): Option[User] = dao.findOne(MongoDBObject("username" -> username))
  def findByCountry(country: String) = dao.find(MongoDBObject("address.country" -> country))
}

Capped Collections

If you want to use capped collections check this out

package models

import play.api.Play.current
import java.util.Date
import com.novus.salat._
import com.novus.salat.annotations._
import com.novus.salat.dao._
import com.mongodb.casbah.Imports._
import se.radley.plugin.salat._
import mongoContext._

case class LogItem(
  id: ObjectId = new ObjectId,
  message: String
)

object LogItem extends ModelCompanion[LogItem, ObjectId] {
  val dao = new SalatDAO[LogItem, ObjectId](collection = mongoCappedCollection("logitems", 1000)) {}
}

GridFS

If you want to store things in gridfs you can do this

package models

import play.api.Play.current
import se.radley.plugin.salat._
import mongoContext._

val files = gridFS("myfiles")

Mongo Context

All models must contain an implicit salat Context. The context is somewhat like a hibernate dialect. You can override mapping names and configure how salat does it's type hinting. read more about it here

In the sample there is a custom mongoContext, partly because we need to add plays classloader to salat so it knows when to reload it's graters, but also so we can override all models id fields to be serialized to MongoDB's _id.

Enums?

If you're using Scala Enumerations have a look at my play-enumeration project.

play-salat's People

Contributors

athieriot avatar bigdsk avatar edofic avatar jeantil avatar leon avatar opyate avatar relrod avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

play-salat's Issues

ClassCastException

Hi,

I still got this Exception. I searched around and found its a common issue regarding salat classloader and evolutionplugin. I use play-salat plugin which is supposed to have solved these issues, how every I still get error everytime I modify the view.

Is there any confirmed solution to this problem? It's really annoying..

Best,

Guan

Please update sample for Play 2.1.x

It would be nice to have an example that uses the 1.2-SNAPSHOT for Play 2.1.x and Scala 2.10, could not make it work myself. (managed to compile everything, but I get this weird error: [Exception: class models.User requires value for 'username'] In ...\play-salat\sample\app\views\list.scala.html at line 5.)

[ClassCastException: models.Profile cannot be cast to models.Profile]

This one really puzzles me.

This is my code:

package models

import play.api.Play.current
import java.util.{Date}
import com.novus.salat._
import com.mongodb.casbah.Imports._
import se.radley.plugin.mongodb._
import se.radley.plugin.mongodb.salat._

case class Profile(id: String,
                   displayName: Option[String] = None,
                   public: Boolean = false,
                   nsfw: Boolean = false,
                   created: Date = new Date,
                   meta: Map[String, String] = Map.empty)

object Profiles extends SalatDAO[Profile, String](collection = getCollection("profiles")) {
  def get(id: String): Profile = findOneByID(id).getOrElse {
    val prof = Profile(id)
    insert(prof)
    prof
  }

  def allPublic = find(MongoDBObject("public" -> true))
}

This occurs after an automatic recompiling. If I stop the server entirely, do a clean in the code, then restart, it works - once. After a second re-build, I get this error again.

This is the full exception:


play.core.ActionInvoker$$anonfun$receive$1$$anon$1: Execution exception [[ClassCastException: models.Profile cannot be cast to models.Profile]]
    at play.core.ActionInvoker$$anonfun$receive$1.apply(Invoker.scala:134) [play_2.9.1.jar:2.1-SNAPSHOT]
    at play.core.ActionInvoker$$anonfun$receive$1.apply(Invoker.scala:115) [play_2.9.1.jar:2.1-SNAPSHOT]
    at akka.actor.Actor$class.apply(Actor.scala:290) [akka-actor-2.0.jar:2.0]
    at play.core.ActionInvoker.apply(Invoker.scala:113) [play_2.9.1.jar:2.1-SNAPSHOT]
    at akka.actor.ActorCell.invoke(ActorCell.scala:617) [akka-actor-2.0.jar:2.0]
    at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:179) [akka-actor-2.0.jar:2.0]
Caused by: java.lang.ClassCastException: models.Profile cannot be cast to models.Profile
    at models.Profiles$.get(Profile.scala:18) ~[classes/:na]
    at controllers.Application$$anonfun$verify$1.apply(Application.scala:28) ~[classes/:2.1-SNAPSHOT]
    at controllers.Application$$anonfun$verify$1.apply(Application.scala:17) ~[classes/:2.1-SNAPSHOT]
    at play.api.mvc.Action$$anon$1.apply(Action.scala:170) ~[play_2.9.1.jar:2.1-SNAPSHOT]
    at play.core.ActionInvoker$$anonfun$receive$1$$anonfun$6.apply(Invoker.scala:126) ~[play_2.9.1.jar:2.1-SNAPSHOT]
    at play.core.ActionInvoker$$anonfun$receive$1$$anonfun$6.apply(Invoker.scala:126) ~[play_2.9.1.jar:2.1-SNAPSHOT]

Improve access to MongoDB object

In order to use GridFS, one needs to have access to the DB (type com.mongodb.casbah.MongoDB). Retrieving the db from the Salat plugin is quite painful:

def db(implicit app: PlayApp): MongoDB = {
  val source = app.plugin[SalatPlugin].map(_.source("default")).getOrElse(
    throw PlayException("SalatPlugin is not registered.", "You need to register the plugin with \"500:se.radley.plugin.salat.SalatPlugin\" in conf/play.plugins")
  )
  source.connection(source.db)
}

Create implicit json read for List collection which might be missing from input json

How can I create the implicit json read for List collection which might be missing in the input json?

case class LIProfile(
  id: ObjectId = new ObjectId,
  positions: List[Position] = Nil
)

object LIProfile extends LIProfileDAO with LIProfileJson

trait LIProfileDAO extends ModelCompanion[LIProfile, ObjectId] {
  def collection = mongoCollection("liprofiles")
  val dao = new SalatDAO[LIProfile, ObjectId](collection) {}

  // Indexes
  collection.ensureIndex(DBObject("emailAddress" -> 1), "li_profile_email", unique = true)

  // Queries
  def findOneByEmail(email: String): Option[LIProfile] = dao.findOne(MongoDBObject("emailAddress" -> email))
}


trait LIProfileJson {

  implicit val liprofileJsonWrite = new Writes[LIProfile] {
    def writes(p: LIProfile): JsValue = {
      Json.obj(
        "id" -> p.id,
        "positions" -> p.positions
      )
    }
  }
  implicit val liprofileJsonRead = (
    (__ \ 'id).read[ObjectId] ~
    (__ \ 'positions).read (
            (__ \ 'values).read[List[Position]]
            ) 
  )(LIProfile.apply _)
}

Using play-salat with scala 2.11.1

Hi,

I am trying to use your plugin with Scala 2.11.1, but I receive the following error. It does however work with 2.10.4. Would it be possible to distribute it for 2.11.1?

[info] Resolving se.radley#play-plugins-salat_2.11;1.4.0 ...
[warn]  module not found: se.radley#play-plugins-salat_2.11;1.4.0
[warn] ==== local: tried
[warn]   /home/jonas/.ivy2/local/se.radley/play-plugins-salat_2.11/1.4.0/ivys/ivy.xml
[warn] ==== activator-local: tried
[warn]   file:/usr/share/typesafe-activator/repository/se.radley/play-plugins-salat_2.11/1.4.0/ivys/ivy.xml
[warn] ==== public: tried
[warn]   http://repo1.maven.org/maven2/se/radley/play-plugins-salat_2.11/1.4.0/play-plugins-salat_2.11-1.4.0.pom
[warn] ==== typesafe-releases: tried
[warn]   http://repo.typesafe.com/typesafe/releases/se/radley/play-plugins-salat_2.11/1.4.0/play-plugins-salat_2.11-1.4.0.pom
[warn] ==== typesafe-ivy-releasez: tried
[warn]   http://repo.typesafe.com/typesafe/ivy-releases/se.radley/play-plugins-salat_2.11/1.4.0/ivys/ivy.xml
[warn] ==== Typesafe Releases Repository: tried
[warn]   http://repo.typesafe.com/typesafe/releases/se/radley/play-plugins-salat_2.11/1.4.0/play-plugins-salat_2.11-1.4.0.pom

UNRESOLVED DEPENDENCIES com.novus#salat_2.10;1.9.2-SNAPSHOT

I've tried to install salat plugin on play 2.1.1 it seems that dependency cannot be found in repository. I followed the manual insalation tutorial. Here's full stacktrace:

warn] ::::::::::::::::::::::::::::::::::::::::::::::
[warn] :: UNRESOLVED DEPENDENCIES ::
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[warn] :: com.novus#salat_2.10;1.9.2-SNAPSHOT: not found
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
error sbt.ResolveException: unresolved dependency: com.novus#salat_2.10;1.9.2-SNAPSHOT: not found
[warn] some of the dependencies were not recompiled properly, so classloader is not avaialable
[info] Updating {file:/.../mongoplay/}mongoplay...
[warn] module not found: com.novus#salat_2.10;1.9.2-SNAPSHOT
[warn] ==== local: tried
[warn] {mypath}/play-2.1.1/repository/local/com.novus/salat_2.10/1.9.2-SNAPSHOT/ivys/ivy.xml
[warn] ==== Typesafe Releases Repository: tried
[warn] http://repo.typesafe.com/typesafe/releases/com/novus/salat_2.10/1.9.2-SNAPSHOT/salat_2.10-1.9.2-SNAPSHOT.pom
[warn] ==== Typesafe Snapshots Repository: tried
[warn] http://repo.typesafe.com/typesafe/snapshots/com/novus/salat_2.10/1.9.2-SNAPSHOT/salat_2.10-1.9.2-SNAPSHOT.pom
[warn] ==== public: tried
[warn] http://repo1.maven.org/maven2/com/novus/salat_2.10/1.9.2-SNAPSHOT/salat_2.10-1.9.2-SNAPSHOT.pom
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[warn] :: UNRESOLVED DEPENDENCIES ::
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[warn] :: com.novus#salat_2.10;1.9.2-SNAPSHOT: not found
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
error sbt.ResolveException: unresolved dependency: com.novus#salat_2.10;1.9.2-SNAPSHOT: not found

Mongolab doesn't allow list databases...

hello, I'm currently trying to use MongoLab with play-salat, however as the subject says, this provider restrict the access to the dbs command.

The problem comes from the SalatPlugin's onStart method that is doing a sanity check by requesting all database names... And so throw an error saying that the server is not recheable (couldn't connect); which is false, we just haven't the right to do so :/.

To resolve this we could maybe request the collections on a specific database (from the config)?

Here is the SO related question: http://stackoverflow.com/questions/12012129/cant-connect-to-mongodb-from-play-app-with-salat-command-failed-listdatabases

Cheers

Create Snapshot version

Hi,

I need test a fix from salat that's available in version 1.9.3-SNAPSHOT and will be great test it with a Snapshot version of play-salat.

play-salat doesn't work with activator-1.2.8 (play 2.2, scala 2.11)

We're using activator-1.2.8, which includes play 2.3.2 and scala 2.11

When I added play-salat, I get the following exception upon the first call that uses Mongo:

Caused by: play.api.PlayException: SalatPlugin is not registered.[You need to register the plugin with "500:se.radley.plugin.salat.SalatPlugin" in conf/play.plugins]
    at se.radley.plugin.salat.package$$anonfun$mongoCollection$2.apply(package.scala:17) ~[play-plugins-salat_2.11-1.5.0.jar:1.5.0]
    at se.radley.plugin.salat.package$$anonfun$mongoCollection$2.apply(package.scala:17) ~[play-plugins-salat_2.11-1.5.0.jar:1.5.0]
    at scala.Option.getOrElse(Option.scala:120) [scala-library-2.11.2.jar:na]
    at se.radley.plugin.salat.package$.mongoCollection(package.scala:17) ~[play-plugins-salat_2.11-1.5.0.jar:1.5.0]
    at models.Application$.collection(Application.scala:27) ~[classes/:na]

However, I already have a conf/play.plugins with that line in it.

How do I get this to work?

Support username + password in mongodb uri

Please add support for username/password in a MongoDB URI.

Given a valid mongodb uri
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

You could use:

val mongoUri = "mongodb://apa:[email protected]/test"
val uri = new URI(mongoUri)
val dbHost = uri.getHost
// Strip out leading slash
val dbName = if(uri.getPath.startsWith("/")) uri.getPath.substring(1) else uri.getPath
val dbPort = uri.getPort
val conn = MongoConnection(dbHost, dbPort)(dbName)

// Get user credentials
val credentials = if(Option(uri.getUserInfo) isDefined) Option(uri.getUserInfo.split(":",2)) else None

// If we have credentials try to authenticate
if (credentials isDefined)  conn.authenticate(credentials.get.head, credentials.get.tail.head)

I don't have time atm to do a pull request. So I'm dumping some working code I've used before. It takes an java.net.URI and extracts the credentials. I'll do a pull request at a later date if you wish.

Can't find github repository for play-salat

I'm trying to install the plugin through the process you specified. When I do g8 leon/play-salat.g8, I get an error saying "Unable to find github repository: leon/play-salat.g8 (master)"

Any solutions?

Does 1.2-SNAPSHOT support Play 2.1?

I'm using the 1.2 snapshot build

val playSalat = "se.radley" % "play-plugins-salat_2.10.0-RC1" % "1.2-SNAPSHOT"

I assumed, this snapshot build already works with Play 2.1. But I get the following exception:

play.api.PlayException: Cannot load plugin[Plugin [se.radley.plugin.salat.SalatPlugin] cannot been instantiated.]
    at play.api.WithDefaultPlugins$$anonfun$plugins$1$$anonfun$apply$9.apply(Application.scala:156) ~[play_2.10.jar:2.1.0]
    at play.api.WithDefaultPlugins$$anonfun$plugins$1$$anonfun$apply$9.apply(Application.scala:130) ~[play_2.10.jar:2.1.0]
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244) ~[scala-library.jar:na]
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244) ~[scala-library.jar:na]
    at scala.collection.immutable.List.foreach(List.scala:309) ~[scala-library.jar:na]
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:244) ~[scala-library.jar:na]
Caused by: java.lang.IncompatibleClassChangeError: Found interface play.api.Application, but class was expected
    at se.radley.plugin.salat.SalatPlugin.configuration$lzycompute(SalatPlugin.scala:13) ~[play-plugins-salat_2.10.0-RC1-1.2-SNAPSHOT.jar:1.2-SNAPSHOT]
    at se.radley.plugin.salat.SalatPlugin.configuration(SalatPlugin.scala:13) ~[play-plugins-salat_2.10.0-RC1-1.2-SNAPSHOT.jar:1.2-SNAPSHOT]
    at se.radley.plugin.salat.SalatPlugin.enabled(SalatPlugin.scala:123) ~[play-plugins-salat_2.10.0-RC1-1.2-SNAPSHOT.jar:1.2-SNAPSHOT]
    at play.api.WithDefaultPlugins$$anonfun$plugins$1$$anonfun$apply$9.apply(Application.scala:133) ~[play_2.10.jar:2.1.0]
    at play.api.WithDefaultPlugins$$anonfun$plugins$1$$anonfun$apply$9.apply(Application.scala:130) ~[play_2.10.jar:2.1.0]
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244) ~[scala-library.jar:na]

Does this snapshot build not yet support Play 2.1??

Unresolved dependency.

[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[warn] :: UNRESOLVED DEPENDENCIES ::
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[warn] :: net.liftweb#lift-json_2.9.1;2.5-SNAPSHOT: not found
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[error] {file:/Users/username/Development/rep/}fly/*:update: sbt.ResolveException: unresolved dependency: net.liftweb#lift-json_2.9.1;2.5-SNAPSHOT: not found

I am receiving this unresolved dependency. Here is by Build.scala:

val appName = "fly"
val appVersion = "1.0-SNAPSHOT"

val appDependencies = Seq(
  // Add your project dependencies here,

  "se.radley" %% "play-plugins-salat" % "1.0.9",
  "org.jba" %% "play2-mustache" % "0.4",
  "com.twitter" %% "util-core" % "4.0.1",
  "it.justwrote" %% "scala-faker" % "0.2-SNAPSHOT",
  "com.github.twitter" % "bootstrap" % "2.1.0",
  "jp.t2v" %% "play20.auth" % "0.2",

  "com.twitter" % "cassie" % "0.19.0" excludeAll(
    ExclusionRule(organization = "javax.jms"),
    ExclusionRule(organization = "com.sun.jdmk"),
    ExclusionRule(organization = "com.sun.jmx")
  )


  // exclude("com.sun.jmx", "jmx")
)

// appDependencies +=  "com.twitter" % "cassie" % "0.19.0"

val main = PlayProject(appName, appVersion, appDependencies, mainLang = SCALA).settings(
    // Add your own project settings here      
    resolvers += "Twitter's Repository" at "http://maven.twttr.com/",
    resolvers += Resolver.url("julienba.github.com", url("http://julienba.github.com/repo/"))(Resolver.ivyStylePatterns),
    resolvers += "justwrote" at "http://repo.justwrote.it/snapshots/",  //Scala Faker
    resolvers += "webjars" at "http://webjars.github.com/m2",
    resolvers += "t2v.jp repo" at "http://www.t2v.jp/maven-repo/",

    routesImport += "se.radley.plugin.salat.Binders._",

    templatesImport += "org.bson.types.ObjectId"
    //templatesImport += "org.jba.Mustache"
    )

}

MongoOptions Support

It should be useful to be able to configure mongo options, such as pool size and timeouts, right in the application.config and load it together with mongo sources.

Could not find a suitable constructor in se.radley.plugin.salat.SalatPlugin. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private.

  • should should be valid *** FAILED ***
    com.google.inject.ConfigurationException: Guice configuration errors:
    1. Could not find a suitable constructor in se.radley.plugin.salat.SalatPlugin. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private.
      at se.radley.plugin.salat.SalatPlugin.class(SalatPlugin.scala:12)
      while locating se.radley.plugin.salat.SalatPlugin

Problem with FakeApplication() in scala test plus :(

Unresolved Dependencies for version 1.0.4

Hello
When i try to run the sample using play run , i get sbt.ResolveException. What i doing wrong?

[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[warn] :: UNRESOLVED DEPENDENCIES ::
[warn] ::::::::::::::::::::::::::::::::::::::::::::::
[warn] :: se.radley#play-plugins-salat_2.9.1;1.0.4: not found
[warn] ::::::::::::::::::::::::::::::::::::::::::::::

I tried to find it in the maven repository, but to no avail.
http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22se.radley%22%20AND%20a%3A%22play-plugins-salat_2.9.1%22

If i change the version on 1.0.3 all works fine.

Adding Salat built in JSON support

With the recent release of salat version 0.0.8 snapshot, Salat has very good support for JSON <-> Model. But since salat uses lift json and not jerkson the Play built in JSON BodyParser will not work. It will be nice for this plugin to also support JSON -> Model conversion from the HTTP request using Salats implementation.

sample with play-plugins-salat can't recognize ObjectId (related to https://github.com/leon/play-salat/issues/53)

I think What I was trying to say it that sample doesn't work, not sure if it's because of the plugin or not. I use everytihng from the sample, nothing from my side except minor changes I mentioned above to upgrade to play 2.2.1 and it still can't recognize ObjectId.

My assumption was that it can't recognize plugin at all even though I added
conf/play.plugins file with:
#500:se.radley.plugin.salat.SalatPlugin

please see playframework/playframework#2055 for more details. I am really struggling to make it work :(

[1.1-SNAPSHOT] Wrong host / port used on Heroku

Hi,

I'm trying to deploy an app using play-salat on Heroku. I have set a specific configuration file for it, with accurate host, port, and user for MongoDB. But at some point, the driver tries to connect to the default 127.0.0.1:27017.

Any idea why? Thanks in advance.

012-09-12T01:52:56+00:00 app[web.1]: [info] play - mongodb [default] connected at *****@ds*****.mongolab.com:37587/heroku_app***** 2012-09-12T01:52:56+00:00 app[web.1]: [info] play - Application started (Prod) 2012-09-12T01:52:56+00:00 app[web.1]: [info] play - Listening for HTTP on port 37741... 2012-09-12T01:52:57+00:00 heroku[web.1]: State changed from starting to up 2012-09-12T01:52:57+00:00 heroku[web.1]: Process exited with status 143 2012-09-12T01:55:04+00:00 app[web.1]: [error] application - 2012-09-12T01:55:04+00:00 app[web.1]: 2012-09-12T01:55:04+00:00 app[web.1]: ! @6bjjg89jk - Internal server error, for request [POST /] -> 2012-09-12T01:55:04+00:00 app[web.1]: 2012-09-12T01:55:04+00:00 app[web.1]: play.core.ActionInvoker$$anonfun$receive$1$$anon$1: Execution exception [[Network: can't call something : /127.0.0.1:27017/*****]] 2012-09-12T01:55:04+00:00 app[web.1]: at play.core.ActionInvoker$$anonfun$receive$1.apply(Invoker.scala:134) [play_2.9.1-2.0.3.jar:2.0.3] 2012-09-12T01:55:04+00:00 app[web.1]: at play.core.ActionInvoker$$anonfun$receive$1.apply(Invoker.scala:115) [play_2.9.1-2.0.3.jar:2.0.3] 2012-09-12T01:55:04+00:00 app[web.1]: at akka.actor.Actor$class.apply(Actor.scala:318) [akka-actor-2.0.2.jar:2.0.2] 2012-09-12T01:55:04+00:00 app[web.1]: at play.core.ActionInvoker.apply(Invoker.scala:113) [play_2.9.1-2.0.3.jar:2.0.3] 2012-09-12T01:55:04+00:00 app[web.1]: at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:197) [akka-actor-2.0.2.jar:2.0.2] 2012-09-12T01:55:04+00:00 app[web.1]: at akka.actor.ActorCell.invoke(ActorCell.scala:626) [akka-actor-2.0.2.jar:2.0.2] 2012-09-12T01:55:04+00:00 app[web.1]: Caused by: com.mongodb.MongoException$Network: can't call something : /127.0.0.1:27017/***** 2012-09-12T01:55:04+00:00 app[web.1]: at com.mongodb.DBTCPConnector.call(DBTCPConnector.java:226) ~[mongo-java-driver-2.8.0.jar:na] 2012-09-12T01:55:04+00:00 app[web.1]: at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:298) ~[mongo-java-driver-2.8.0.jar:na] 2012-09-12T01:55:04+00:00 app[web.1]: at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:313) ~[mongo-java-driver-2.8.0.jar:na] 2012-09-12T01:55:04+00:00 app[web.1]: at com.mongodb.DBCollection.findOne(DBCollection.java:682) ~[mongo-java-driver-2.8.0.jar:na] 2012-09-12T01:55:04+00:00 app[web.1]: at com.mongodb.DBCollection.findOne(DBCollection.java:661) ~[mongo-java-driver-2.8.0.jar:na] 2012-09-12T01:55:04+00:00 app[web.1]: at com.mongodb.casbah.MongoCollectionBase$class.findOne(MongoCollection.scala:225) ~[casbah-core_2.9.1-2.4.1.jar:2.4.1] 2012-09-12T01:55:04+00:00 app[web.1]: Caused by: java.io.IOException: couldn't connect to [/127.0.0.1:27017] bc:java.net.ConnectException: Connection refused 2012-09-12T01:55:04+00:00 app[web.1]: at com.mongodb.DBPort.call(DBPort.java:78) ~[mongo-java-driver-2.8.0.jar:na] 2012-09-12T01:55:04+00:00 app[web.1]: at com.mongodb.DBPort._open(DBPort.java:222) ~[mongo-java-driver-2.8.0.jar:na] 2012-09-12T01:55:04+00:00 app[web.1]: at com.mongodb.DBPort.go(DBPort.java:111) ~[mongo-java-driver-2.8.0.jar:na] 2012-09-12T01:55:04+00:00 app[web.1]: at com.mongodb.DBTCPConnector.call(DBTCPConnector.java:217) ~[mongo-java-driver-2.8.0.jar:na] 2012-09-12T01:55:04+00:00 app[web.1]: at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:313) ~[mongo-java-driver-2.8.0.jar:na] 2012-09-12T01:55:04+00:00 app[web.1]: at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:298) ~[mongo-java-driver-2.8.0.jar:na]

Registering JodaTimeConversions Helpers

I am having trouble getting the JodaTime deserialization working. I have already posted this issue in the salat forum and play forum with no luck and want to get your thoughts if the issue am seeing is because of how the plugins works with Play. The error is the when I deserialize a json to a DateTime field using salat I get the below error.

play.core.ActionInvoker$$anonfun$receive$1$$anon$1: Execution exception [[MatchE
rror: -1974930944 (of class java.lang.Integer)]]
at play.core.ActionInvoker$$anonfun$receive$1.apply(Invoker.scala:134) [
play_2.9.1-2.0.3.jar:2.0.3]
at play.core.ActionInvoker$$anonfun$receive$1.apply(Invoker.scala:115) [
play_2.9.1-2.0.3.jar:2.0.3]
at akka.actor.Actor$class.apply(Actor.scala:318) [akka-actor.jar:2.0.2]
at play.core.ActionInvoker.apply(Invoker.scala:113) [play_2.9.1-2.0.3.ja
r:2.0.3]
at akka.actor.ActorCell.invoke(ActorCell.scala:626) [akka-actor.jar:2.0.
2]
at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:197) [akka-actor.j
ar:2.0.2]
Caused by: scala.MatchError: -1974930944 (of class java.lang.Integer)
at com.novus.salat.transformers.in.DateToJodaDateTime$class.transform(In
jectors.scala:275) ~[salat-core_2.9.1-1.9.1.jar:1.9.1]
at com.novus.salat.transformers.in.package$$anon$22.transform(Injectors.
scala:61) ~[salat-core_2.9.1-1.9.1.jar:1.9.1]
at com.novus.salat.transformers.Transformer$$anonfun$transform_$bang$1.a
pply(Transformer.scala:75) ~[salat-core_2.9.1-1.9.1.jar:1.9.1]
at com.novus.salat.transformers.Transformer$$anonfun$transform_$bang$1.a
pply(Transformer.scala:75) ~[salat-core_2.9.1-1.9.1.jar:1.9.1]
at scala.Option.flatMap(Option.scala:146) ~[scala-library.jar:0.11.3]
at com.novus.salat.transformers.Transformer.transform_$bang(Transformer.
scala:75) ~[salat-core_2.9.1-1.9.1.jar:1.9.1]

The code I am using for the testing is at https://gist.github.com/3711637
Initially I registered the conversion helpers in the context then based on the feedback for salat and play forums I moved it to Global.scala.

Below are the logs after changing the play log level to debug and running play. We can see that the Joda Time helpers do get registered by Global.scala but other convertors get registered after the first request hits the server and a mongo connection is created. Is it possible that the jodadate convertors that were registered during startup are not visible when the connection is created and may be the JODA time convertor should be registered in the plugin when the connection is created for this to work ?

[debug] n.s.e.Cache - Initialised cache: play
[debug] n.s.e.c.ConfigurationHelper - CacheDecoratorFactory not configured for d
efaultCache. Skipping for 'play'.
[debug] c.m.c.c.c.s.RegisterJodaTimeConversionHelpers$ - Registering Joda TimeScala Conversions.
[debug] c.m.c.c.c.s.RegisterJodaTimeConversionHelpers$ - Hooking up Joda DateTime deserializer
[debug] c.m.c.c.c.s.RegisterJodaTimeConversionHelpers$ - Hooking up Joda DateTime serializer.
[debug] c.m.c.c.c.s.RegisterJodaTimeConversionHelpers$ - Reached base registration method on MongoConversionHelper.
[info] application - Application has started with JodaTime registered
[info] play - Application started (Dev)
[debug] j.m.mbeanserver - name=com.mongodb:type=ConnectionPool,host=/127.0.0.1,port=27017,instance=2
[debug] j.m.mbeanserver - ObjectName = com.mongodb:type=ConnectionPool,host=/127.0.0.1,port=27017,instance=2
[debug] j.m.mbeanserver - name=com.mongodb:type=ConnectionPool,host=/127.0.0.1,port=27017,instance=2
[debug] j.m.mbeanserver - Send create notification of object com.mongodb:host=/127.0.0.1,instance=2,port=27017,type=ConnectionPool
[debug] j.m.mbeanserver - JMX.mbean.registered com.mongodb:type=ConnectionPool,host=/127.0.0.1,port=27017,instance=2
[debug] j.m.mbeanserver - name=com.mongodb:type=ConnectionPool,host=/127.0.0.1,port=27017,instance=3
[debug] j.m.mbeanserver - ObjectName = com.mongodb:type=ConnectionPool,host=/127.0.0.1,port=27017,instance=3
[debug] j.m.mbeanserver - name=com.mongodb:type=ConnectionPool,host=/127.0.0.1,port=27017,instance=3
[debug] j.m.mbeanserver - Send create notification of object com.mongodb:host=/127.0.0.1,instance=3,port=27017,type=ConnectionPool
[debug] j.m.mbeanserver - JMX.mbean.registered com.mongodb:type=ConnectionPool,host=/127.0.0.1,port=27017,instance=3
[debug] c.m.c.c.c.s.RegisterConversionHelpers$ - Registering Scala Conversions.
[debug] c.m.c.c.c.s.RegisterConversionHelpers$ - Deserializers for Scala Conversions registering
[debug] c.m.c.c.c.s.RegisterConversionHelpers$ - Serializers for Scala Conversions registering
[debug] c.m.c.c.c.s.RegisterConversionHelpers$ - Setting up OptionSerializer
[debug] c.m.c.c.c.s.RegisterConversionHelpers$ - Setting up ScalaJCollectionSerializer
[debug] c.m.c.c.c.s.RegisterConversionHelpers$ - Setting up ScalaRegexSerializers
[debug] c.m.c.c.c.s.RegisterConversionHelpers$ - Hooking up scala.util.matching.Regex serializer
[debug] c.m.c.c.c.s.RegisterConversionHelpers$ - Reached base registration method on MongoConversionHelper.

Thanks
Zafer

@Persist annotation

I found salat annotations to customize serialization. https://github.com/novus/salat/wiki/Annotations

I decided to try @Persist annotation. So i little change sample example, edited User.scala. I added "persist line" and curly braces:

...
 deleted: Option[Date] = None,
  @Key("company_id")company: Option[ObjectId] = None
){
  @Persist val reverse = username.reverse // <-- added line
}

object User extends ModelCompanion[User, ObjectId] {
  val collection = mongoCollection("users")
...

Then i run sample. This is result from mongo console:

db.users.find()
{ "_id" : ObjectId("4fca4927d7edf5a43422c11f"), "username" : "leon", "password"
: "1234", "address" : { "street" : "├Цrebro", "zip" : "123 45", "country" : "Swe
den" }, "added" : ISODate("2012-06-02T17:11:03.928Z") }
{ "_id" : ObjectId("4fca4928d7edf5a43422c120"), "username" : "guillaume", "passw
ord" : "1234", "address" : { "street" : "Paris", "zip" : "75000", "country" : "F
rance" }, "added" : ISODate("2012-06-02T17:11:04.261Z") }

reverse is not saved =(

I am a novice in Scala and MongoDB (I started learning it yesterday), so I'm a little confused where I look for an answer. Maybe I do not understand something?

Thanks in advance.

Error on Play 2.4

Hi, I'm using your library.
When I compile my project I got:

[error] missing or invalid dependency detected while loading class file 'Binders.class'.
[error] Could not access type JavascriptLitteral in package play.api.mvc,
[error] because it (or its dependencies) are missing. Check your build definition for
[error] missing or conflicting dependencies. (Re-run with -Ylog-classpath to see the problematic classpath.)
[error] A full rebuild may help if 'Binders.class' was compiled against an incompatible version of play.api.mvc.

My built.sbt is:

name := """panorama-settings"""

version := "1.0-SNAPSHOT"

lazy val root = (project in file(".")).enablePlugins(PlayScala)

scalaVersion := "2.11.6"

lazy val dbD = Seq(
"org.mongodb" %% "casbah" % "2.8.0",
"com.typesafe.play.plugins" %% "play-plugins-redis" % "2.3.1",
"com.novus" %% "salat" % "1.9.9",
"se.radley" %% "play-plugins-salat" % "1.5.0" // ORM for mongo
)

libraryDependencies ++= Seq(
jdbc,
cache,
ws,
specs2 % Test
) ++ dbD

routesImport += "se.radley.plugin.salat.Binders._"

TwirlKeys.templateImports += "org.bson.types.ObjectId"

resolvers += "scalaz-bintray" at "http://dl.bintray.com/scalaz/releases"

resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots"

// Play provides two styles of routers, one expects its actions to be injected, the
// other, legacy style, accesses its actions statically.
routesGenerator := InjectedRoutesGenerator

Using deprecated authenticate method

The plugin still uses a deprecated method for authenticating.

@deprecated("Please use MongoClient to create a client, which will authenticate all connections to server.", "2.7")
def authenticate(username: String, passwd: String): Boolean = underlying.authenticate(username, passwd.toArray)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.