Scala + Play -> Type mismatch; found : anorm.RowParser Required: anorm.ResultSetParser[Option[models.User]] - postgresql

SOLUTION: I could not figure our how to return the non-exists for of Option[User] so in the case of not user found I create a dummy user object and reason on it from the controller (feels awful but working...):
from Application.scala
val loginForm = Form(
tuple(
"email" -> text,
"password" -> text
) verifying ("Invalid email or password", result => result match {
case (email, password) => (User.authenticate(email, password).map{_.id}.getOrElse(0) != 0)
})
)
AS OPPOSED TO:
val loginForm = Form(
tuple(
"email" -> text,
"password" -> text
) verifying ("Invalid email or password", result => result match {
case (email, password) => User.authenticate(email, password).isDefined
})
)
++++++++++++++++++ ORIGINAL 2 ++++++++++++++++++
Thanks for the advice! I have made some change and seem to be getting closer however I can't figure out how to return an undefinded Option[user]. I have also tried case _ => null, See below:
From User.scala
case class User(id: Int, email: String, name: String, password: String)
object User {
// -- Parsers
/**
* Parse a User from a ResultSet
*/
val userParser = {
get[Option[Int]]("uid")~
get[Option[String]]("email")~
get[Option[String]]("fname")~
get[Option[String]]("pbkval") map {
case (uid~email~name~pbkval) => validate(uid,email, name, pbkval)
}
}
/**
* Retrieve a User from email.
*/
def findByEmail(email: String): Option[User] = {
DB.withConnection { implicit connection =>
SQL("select * from get_pbkval({email})").on(
'email -> email
).as(userParser.singleOpt)
}
}
/**
* Authenticated user session start.
*/
def authenticate(email: String, password: String): Option[User] = {
DB.withConnection { implicit connection =>
SQL(
"""
select * from get_pbkval({email})
"""
).on(
'email -> email
).as(userParser.singleOpt)
}
}
/**
* Validate entry and create user object.
*/
def validate(uid: Option[Int], email: Option[String], fname: Option[String], pbkval: Option[String]): User = {
val uidInt : Int = uid.getOrElse(0)
val emailString: String = email.getOrElse(null)
val fnameString: String = fname.getOrElse(null)
val pbkvalString: String = pbkval.getOrElse(null)
User(uidInt, emailString, fnameString, pbkvalString)
}
I guess it is clear that I am not really getting something fundamental here.. I have read through http://www.playframework.org/modules/scala-0.9.1/anorm and searched around for hours.. any help would be much appreciated!

You didn't specify which rows to map. After your row mapper, put a * to signify which rows to map. While you're at it, I find it easier to define my row mapper in a separate val. Something like this.
val user = {
get[Option[Int]]("uid")~
get[Option[String]]("email")~
get[Option[String]]("fname")~
get[Option[String]]("pbkval") map {
case uid~email~name~password => validate(uid,email, name, password)
}
}
def authenticate(email: String, password: String): Option[User] = {
DB.withConnection { implicit connection =>
SQL(
"""
select * from get_pbkval({email})
"""
).on(
'email -> email
).as(user *)
}
}
def validate(uid: Option[Int], email: Option[String], fname: Option[String], pbkval: Option[String]): Option[User] = {
if (uid != None) {
val uidInt : Int = uid.getOrElse(0)
val emailString: String = email.getOrElse(null)
val fnameString: String = fname.getOrElse(null)
val pbkvalString: String = pbkval.getOrElse(null)
User(uidInt, emailString, fnameString, pbkvalString)
} else { return null}
}
Note the "as" method now has two arguments, your row mapper (which is now defined as a val "user", and a "*" signifying that you want to map all of the rows.

Related

how to apply Form validators on object

I have an API in Scala. When I want to create a new User, i need validators on some fields (UserName, FirstName, LastName). I can't find a solution to apply the Form on my case class User. I thought using (User.apply) this will override automatically my User class, but this isn't happening.
User.scala
case class User(
id: Int = 0,
userName: String,
firstName: String,
lastName: String
)
object User {
import play.api.libs.json._
implicit val jsonWrites = Json.writes[User]
implicit val userReads = Json.reads[User]
def tupled = (User.apply _).tupled
}
// Form validator for post requests
object UserForm {
val form: Form[User] = Form(
mapping(
"id" -> number,
"userName" -> text(minLength = 5),
"firstName" -> text(minLength = 5),
"lastName" -> nonEmptyText
)(User.apply)(User.unapply)
)
}
UsersController.scala
def create = Action(parse.json) { implicit request => {
val userFromJson = Json.fromJson[User](request.body)
userFromJson match {
case JsSuccess(user: User, path: JsPath) => {
var createdUser = Await.result(usersRepository.create(user), Duration.Inf)
Ok(Json.toJson(createdUser))
}
case error # JsError(_) => {
println(error)
InternalServerError(Json.toJson("Can not create user"))
}
}
}
}
UsersRepository.scala
def create(user: User): Future[User] = {
val insertQuery = dbUsers returning dbUsers.map(_.id) into ((x, id) => x.copy(id = id))
val query = insertQuery += user
db.run(query)
}
(UsersRepository doesn't matter so much in this problem)
So, when I read the json, I think there need to apply the form validators
val userFromJson = Json.fromJson[User](request.body)
but nothing happening. Another problem is if I send from client a null parameter, will get an error, can not read and create an User.
For example :
"firstName": "" - empty userName will pass
"firstName": null - will fail
This depends on how is configured the User class in client (Angular), with the field null or empty in constructor. I prefer to set it null, even if is a string, if is not a required field (better NULL value in database, than an empty cell)
Try to use this:
request.body.validate[User]
One other thing, you shouldn't use
var createdUser = Await.result(usersRepository.create(user), Duration.Inf)
So use val´s over var´s and the other thing, you don't need to force the future to resolve, use it like this:
val createdUser = usersRepository.create(user)
createdUser.map(Ok(Json.toJson(_)))
And your action should be async.
Find a solution, my Form need to be part of object User, and not to be another object.
object User {
import play.api.libs.json._
implicit val jsonWrites = Json.writes[User]
implicit val userReads = Json.reads[User]
val form: Form[User] = Form(
mapping(
"id" -> number,
"userName" -> text(minLength = 2),
"firstName" -> text(minLength = 4),
"lastName" -> nonEmptyText
)(User.apply)(User.unapply)
)
def tupled = (User.apply _).tupled
}
and the method in Controller became :
def create = Action(parse.json) { implicit request => {
User.form.bindFromRequest.fold(
formWithErrors => BadRequest(Json.toJson("Some form fields are not validated.")),
success => {
val userFromJson = Json.fromJson[User](request.body)
userFromJson match {
case JsSuccess(user: User, path: JsPath) => {
val createdUser = Await.result(usersRepository.create(user), Duration.Inf)
Ok(Json.toJson(createdUser))
}
case error#JsError(_) => {
println(error)
InternalServerError(Json.toJson("Can not create user"))
}
}
}
)
}
}
I know, I need to format my code ... using IntelliJ is so annoying after Visual Studio :(

Converting from JsResultException to JsError

I have Json that may have spaces in it which I'd like to trim. I created this case class to parse with Json.parse(...).as[PersonalInfo] but the issue is that it fails on the first failed read and also doesn't return a JsError. How would I define the JsError case while also preserving the errors for every field that wasn't parsed correctly?
case class PersonalInfo(
email: String,
password: String,
firstName: String,
lastName: String
)
object PersonalInfo {
implicit val personalInfoReads = new Reads[PersonalInfo] {
override def reads(json: JsValue): JsResult[PersonalInfo] = {
val email = (json \ "email").as[String].trim
val password = (json \ "password").as[String].trim
val firstName = (json \ "firstName").as[String].trim
val lastName = (json \ "lastName").as[String].trim
JsSuccess(PersonalInfo(email, password, firstName, lastName))
}
}
}
See my answer here
In two words: do not use as in reads. In case of failed parsing it throws exception. Use validate. Example you can find by link above
Update
Well, if you want solution..
case class PersonalInfo(email: String,
password: String,
firstName: String,
lastName: String)
object PersonalInfo {
implicit val personalInfoReads = new Reads[PersonalInfo] {
override def reads(json: JsValue): JsResult[PersonalInfo] = {
for {
email <- (json \ "email").validate[String]
password <- (json \ "password").validate[String]
firstName <- (json \ "firstName").validate[String]
lastName <- (json \ "lastName").validate[String]
} yield PersonalInfo(
email.trim(),
password.trim(),
firstName.trim(),
lastName.trim()
)
}
}
}
My idea is to use the standard format (you can also use read) of play-json
And then add a function to get it trimmed:
case class PersonalInfo(
email: String,
password: String,
firstName: String,
lastName: String
) {
def trimmed() = PersonalInfo(
email.trim,
password.trim,
firstName.trim,
lastName.trim
)
}
object PersonalInfo {
implicit val customWrites: OFormat[PersonalInfo] = Json.format[PersonalInfo]
}
You can use it like that:
json.validate[PersonalInfo] match {
case JsSuccess(info: PersonalInfo, _) =>
info.trimmed()
case JsError(errors) =>
error("Other than RunAdapter: " + errors.toString())
}
The errors is a list of all validation errors.

Play Framework:Error type mismatch; found :Int required: play.api.mvc.Result

I am trying to save form values to a database, and play I am getting the error:
type mismatch; found :Int required: play.api.mvc.Result
And here is my code :
Application.scala
import play.api._
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
import views.html.defaultpages.badRequest
import play.api.data.validation.Constraints._
import models.User
import models.UserData
object Application extends Controller {
val RegisterForm = Form(
mapping(
"fname" -> nonEmptyText(1, 20),
"lname" -> nonEmptyText(1, 20),
"email" -> email,
"userName" -> nonEmptyText(1, 20),
"password" -> nonEmptyText(1, 20),
"age" -> number,
"choice" -> text,
"gender" -> text
)(User.apply)(User.unapply)
.verifying("Ag should be greater then or equal to 18", model => model.age match {
case (age) => age >= 18
})
)
def index = Action {
Ok(views.html.index(RegisterForm))
}
def register = Action { implicit request =>
RegisterForm.bindFromRequest().fold(
hasErrors => BadRequest(views.html.index(hasErrors)),
success => {
User.save(success)
}
)
}
}
User.scala
import anorm._
import play.api.db.DB
import anorm.SqlParser._
import play.api.Play.current
case class User (
fname: String,
lname: String,
email: String,
userName: String,
password: String,
age: Int,
choice: String,
gender: String
)
object User {
val userinfo = {
get[String]("fname") ~
get[String]("lname") ~
get[String]("email") ~
get[String]("userName") ~
get[String]("password") ~
get[Int]("age") ~
get[String]("choice") ~
get[String]("gender") map {
case fname~lname~email~userName~password~age~choice~gender =>
User(fname, lname, email, userName, password, age, choice, gender)
}
}
def save(ud: User) = {
DB.withConnection { implicit c =>
SQL ("insert into userinfo(fname,lname,email,userName,password,age,choice,gender) values ({fname},{lname},{email},{userName},{password},{age},{choice},{gender})")
.on('fname -> ud.fname, 'lname ->ud.lname ,'email ->ud.email, 'userName->ud.userName , 'password->ud.password ,'age->ud.age, 'choice->ud.choice,'gender->ud.gender)
.executeUpdate()
}
}
}
i took help from the scala cook book for this save functions but i am having problem as i am new in play scala maybe the mistake was minor one so please help me,all i want is to store all the input values in DB which was entered in the form
The problem is with your controller function register:
def register = Action { implicit request =>
RegisterForm.bindFromRequest().fold(
hasErrors => BadRequest(views.html.index(hasErrors)),
success => {
// You need to return a `Result` here..
// Maybe redirect to login?
// Redirect("/login")
User.save(success)
}
)
}
The problem is that User.save returns an Int, and the controller function is expecting a Result, like Ok(..), Redirect(...), etc. You need to do something with the result of User.save to return a Result.
It would be better if you used executeInsert() instead of executeUpdate(), as executeInsert returns Option[Long] by default--which will help you determine if the save was successful.
e.g.:
def save(ud: User): Option[Long] = {
DB.withConnection {implicit c =>
SQL("insert into userinfo(fname,lname,email,userName,password,age,choice,gender) values ({fname},{lname},{email},{userName},{password},{age},{choice},{gender})")
.on('fname -> ud.fname, 'lname ->ud.lname ,'email ->ud.email, 'userName->ud.userName , 'password->ud.password ,'age->ud.age, 'choice->ud.choice,'gender->ud.gender)
.executeInsert()
}
}
Then within your controller function use it like this:
def register = Action { implicit request =>
RegisterForm.bindFromRequest().fold(
hasErrors => BadRequest(views.html.index(hasErrors)),
success => {
User.save(success) map { newId =>
Redirect("/login") // or whatever you want this to do on success
} getOrElse {
InternalServerError("Something has gone terribly wrong...")
}
}
)
}
You can replace my placeholder results with something a little more meaningful in your application.
The save(ud:User) method returns the integer value. Action should always return Result, so write
success => {
val result = User.save(success)
Ok(result.toString)
}

better slick dynamic query coding style

private def buildQuery(query: TweetQuery) = {
var q = Tweets.map { t =>
t
}
query.isLocked.foreach { isLocked =>
q = q.filter(_.isLocked === isLocked)
}
query.isProcessed.foreach { isProcessed =>
q = q.filter(_.processFinished === isProcessed)
}
query.maxScheduleAt.foreach { maxScheduleAt =>
q = q.filter(_.expectScheduleAt < maxScheduleAt)
}
query.minScheduleAt.foreach { minScheduleAt =>
q = q.filter(_.expectScheduleAt > minScheduleAt)
}
query.status.foreach { status =>
q = q.filter(_.status === status)
}
query.scheduleType.foreach { scheduleType =>
q = q.filter(_.scheduleType === scheduleType)
}
q
}
I am writing things like above to do dynamic query. really boring, any way better to do this ?
Maybe the MaybeFilter can help you https://gist.github.com/cvogt/9193220
I think this is the correct migrated code for slick 2.1.0
case class MaybeFilter[X, Y](val query: Query[X, Y, Seq]) {
def filter[T, R: CanBeQueryCondition](data: Option[T])(f: T => X => R) = {
data.map(v => MaybeFilter(query.withFilter(f(v)))).getOrElse(this)
}
}
I modified the answer of cvogt in order to work with slick 2.1.0. Explanations of what have changed are in here.
Hope it helps someone :)
case class MaybeFilter[X, Y](val query: scala.slick.lifted.Query[X, Y, Seq]) {
def filter(op: Option[_])(f:(X) => Column[Option[Boolean]]) = {
op map { o => MaybeFilter(query.filter(f)) } getOrElse { this }
}
}
Regards.
Corrected example:
//Class definition
import scala.slick.driver.H2Driver.simple._
import scala.slick.lifted.{ProvenShape, ForeignKeyQuery}
// A Suppliers table with 6 columns: id, name, street, city, state, zip
class Suppliers(tag: Tag)
extends Table[(Int, String, String, String, String, String)](tag, "SUPPLIERS") {
// This is the primary key column:
def id: Column[Int] = column[Int]("SUP_ID", O.PrimaryKey)
def name: Column[String] = column[String]("SUP_NAME")
def street: Column[String] = column[String]("STREET")
def city: Column[String] = column[String]("CITY")
def state: Column[String] = column[String]("STATE")
def zip: Column[String] = column[String]("ZIP")
// Every table needs a * projection with the same type as the table's type parameter
def * : ProvenShape[(Int, String, String, String, String, String)] =
(id, name, street, city, state, zip)
}
//I changed the name of the def from filter to filteredBy to ease the
//implicit conversion
case class MaybeFilter[X, Y](val query: scala.slick.lifted.Query[X, Y, Seq]) {
def filteredBy(op: Option[_])(f:(X) => Column[Option[Boolean]]) = {
op map { o => MaybeFilter(query.filter(f)) } getOrElse { this }
}
}
//Implicit conversion to the MaybeFilter in order to minimize ceremony
implicit def maybeFilterConversor[X,Y](q:Query[X,Y,Seq]) = new MaybeFilter(q)
val suppliers: TableQuery[Suppliers] = TableQuery[Suppliers]
suppliers += (101, "Acme, Inc.", "99 Market Street", "Groundsville", "CA", "95199")
//Dynamic query here
//try this asigment val nameFilter:Option[String] = Some("cme") and see the results
val nameFilter:Option[String] = Some("Acme")
//also try to assign None in here like this val supIDFilter:Option[Int] = None and see the results
val supIDFilter:Option[Int] = Some(101)
suppliers
.filteredBy(supIDFilter){_.id === supIDFilter}
.filteredBy(nameFilter){_.name like nameFilter.map("%" + _ + "%").getOrElse("")}
.query.list
Complete example:
https://github.com/neowinx/hello-slick-2.1-dynamic-filter
Are isLocked, isProcessed, etc Options?
Then you can also write things like
for (locked <- query.isLocked) { q = q.filter(_.isLocked is locked) }
if that's of any consolation :-}
Well, it seems like this code violates OCP. Try to take a look on this article - even though it's not on Scala, it explains how to properly design such methods.

Scala Type Mismatch

I am having a problem with type mismatch.
type mismatch; found : Option[models.User] required: models.User
def authenticate = Action { implicit request =>
signinForm.bindFromRequest.fold(
formWithErrors => BadRequest(html.signin(formWithErrors)),
user => Redirect(routes.Application.active).withSession(Security.username -> User.getUserName(user))
)
}
How can I force the function to accept Option[models.User] or can I convert the models.User into an Option?
The error occurs here: User.getUserName(user). getUserName requires models.User types.
===============================================
Update with all code used:
From User.scala
def authenticate(email: String, password: String) : Option[User] = {
(findByEmail(email)).filter { (user => BCrypt.checkpw(password, user.password)) }
}
def findByEmail(email: String) : Option[User] = {
UserDAO.findOne(MongoDBObject("email" -> email))
}
From Application.scala
val signinForm = Form {
mapping(
"email" -> nonEmptyText,
"password" -> text)(User.authenticate)(_.map(user => (user.email, "")))
.verifying("Invalid email or password", result => result.isDefined)
}
def authenticate = Action { implicit request =>
signinForm.bindFromRequest.fold(
formWithErrors => BadRequest(html.signin(formWithErrors)),
user => Redirect(routes.Application.active).withSession(Security.username -> User.getUserName(user.get))
)
}
To de-option an Option[User] into a User, you can do one of the following:
1) The unsafe way. Only do this if you are sure that optUser is not None.
val optUser: Option[User] = ...
val user: User = optUser.get
2) The safe way
val optUser: Option[User] = ...
optUser match {
case Some(user) => // do something with user
case None => // do something to handle the absent user
}
3) The monadic safe way
val optUser: Option[User] = ...
optUser.map(user => doSomething(user))
The biggest thing is that, if it's possible that optUser might actually be None, you need to figure out what you actually want to happen in the case that there is no User object.
There's a lot more information about Option in other StackOverflow questions if you'd like to read more.