Why is Play! breaking apart the {format} param in routes? - scala

Must be a syntax issue on my part, but can't quite pin it:
In my controller I have this defined:
request.format match {
case "json" => Json(output)
case "xml" => toXml(parse(output.toString))
case _ => BadRequest
}
And in my routes I have this defined:
# Map the API to the proper domain
GET /{key}/{action}/{param}.{format} API.{action}
POST /{key}/{action}/{param}.{format} API.{action}
I posted something like: /34523452345/job/today.json
So when I go to actually run the request, it takes {param} and includes the period. So the result for {param} is today.js and the {format} becomes on
The catch if I switch the period to a forward slash / it works just fine
What is the cause of the problem?

I believe you have to escape the dot as in \., as Play uses regexp in the routes files.

Related

Can't pass parameter to reverse router in playframework

I have defined a route like this:
GET /login controllers.Login.showForm(continue: Option[String] = None)
Login.showForm is this:
def showForm(continue: Option[String] = None) = Action { implicit request =>
val nextPage = continue match {
case None => routes.CtrlIndex.index().absoluteURL().toString()
case Some(page) => page
}
Ok(views.html.login(nextPage))
}
Now, using action composition I made an authenticated action that performs this when the user is not authenticated:
val continue =
if (request.method == "GET") request.uri
else routes.CtrlIndex.index().absoluteURL().toString() // This is not code duplication for reasons that are out of the scope of this question.
Redirect(routes.Login.showForm(Some(continue)))
This fails to compile with this message:
too many arguments for method showForm: ()play.api.mvc.Call
[error] Redirect(routes.Login.showForm(Some(continue)))
Changing the route definition makes it work:
GET /login controllers.Login.showForm(continue: Option[String])
But then when I use the javascript reverse router, it generates the following error in the generated javascript:
SyntaxError: missing formal parameter
function(continue) {
---------^
I have tried all combination of the definition of the function signatures but when the javascript works, the other stops working or the other way around. How can I use
Optional parameter on /login
Use the reverse javascript router
Redirect to /login with the "continue" parameter
I would also like to change request.uri for something that returns an absolute path.
Thanks in advance
PS. If you see something in Spanish, let me know and I'll fix it, the code is originally in Spanish; I may have missed something even after I read it.
The likely cause is that "continue" is a reserved word in javascript
Play's javascript reverse router constructs a given route using the controller path and method argument(s) specified in the routes file; in your case, "continue" may be tripping up the js parser, much like a method named "delete", which works fine server-side but will blow up in the client-side reverse router.
This may be a non-issue for newer browsers, but have been bitten by "delete" method name on older versions of Internet Explorer (that we are required to support).

Scala Lift - REST-Get on dynamic generated image

I use Scala and Lift for REST web-services and I have a method that generates dynamic jpg images that should be made accessible via a Get Request, so that for each Get-Request the method generates an image again and sends it back in the response.
I made a case in serve:
case "img.jpg" :: Nil Get _ => Full(OkResponse())
case _ => Full(NotFoundResponse())
But this case does not seem to be recognised, it always catches the Default-Case.
What is the proper way to serve routes on a . url? And what response type can be used to deliver the jpg?
The file extension is handled separately from the rest of the path, so matching as you do above won't work. You can see some more discussion about this in the Lift Cookbook.
To make the above work, you should be able to do this:
case "img" :: Nil Get req if req.path.suffix == "jpg" => Full(OkResponse())
I believe you can also use the Req object, which will let you specify the suffix like this:
case Req("img" :: Nil, "jpg", GetRequest) => Full(OkResponse())

playframework wildcard matching

Say I have the following url:
/baseurl
I'd like play to match and route on this url. I'd like to satisfy all these patterns:
/baseurl
/baseurl/
/baseurl/*
/baseurl/*/*
So basically I don't care what comes after '/baseurl'. I don't want to explicitly have to pass a variable to my action for the part coming in after '/baseurl' because I don't care about it: I just want it all routed to the same controller (for a single page app). I also am ok if I have to do this with multiple route lines.
I'd put something like this pretty high in the routes file:
GET /baseurl/*path/ controllers.Application.untrail(path: String)
(and the variations thereof)
And then in controllers.Application:
def untrail(path: String) = Action {
MovedPermanently("/baseurl")
}

Routing based on query parameter in Play framework

My web application will be triggered from an external system. It will call one request path of my app, but uses different query parameters for different kinds of requests.
One of the parameters is the "action" that defines what is to be done. The rest of the params depend on the "action".
So I can get request params like these:
action=sayHello&user=Joe
action=newUser&name=Joe&address=xxx
action=resetPassword
...
I would like to be able to encode it similarly in the routes file for play so it does the query param based routing and as much of the validation of other parameters as possible.
What I have instead is one routing for all of these possibilities with plenty of optional parameters. The action processing it starts with a big pattern match to do dispatch and parameter validation.
Googling and checking SO just popped up plenty of samples where the params are encoded in the request path somehow, so multiple paths are routed to the same action, but I would like the opposite: one path routed to different actions.
One of my colleagues said we could have one "dispatcher" action that would just redirect based on the "action" parameter. It would be a bit more structured then the current solution, but it would not eliminate the long list of optional parameters which should be selectively passed to the next action, so I hope one knows an even better solution :-)
BTW the external system that calls my app is developed by another company and I have no influence on this design, so it's not an option to change the way how my app is triggered.
The single dispatcher action is probably the way to go, and you don't need to specify all of your optional parameters in the route. If action is always there then that's the only one you really need.
GET /someRoute controller.dispatcher(action: String)
Then in your action method you can access request.queryString to get any of the other optional parameters.
Note: I am NOT experienced Scala developer, so maybe presented snippets can be optimized... What's important for you they are valid and working.
So...
You don't need to declare every optional param in the routes file. It is great shortcut for type param's validation and best choice would be convince 'other company' to use API prepared by you... Anyway if you haven't such possibility you can also handle their requests as required.
In general: the dispatcher approach seems to be right in this place, fortunately you don't need to declare all optional params in the routes and pass it between actions/methods as they can be fetched directly from request. In PHP it can be compared to $_GET['action'] and in Java version of Play 2 controller - DynamicForm class - form().bindFromRequest.get("action").
Let's say that you have a route:
GET /dispatcher controllers.Application.dispatcher
In that case your dispatcher action (and additional methods) can look like:
def dispatcher = Action { implicit request =>
request.queryString.get("action").flatMap(_.headOption).getOrElse("invalid") match {
case "sayHello" => sayHelloMethod
case "newUser" => newUserMethod
case _ => BadRequest("Action not allowed!")
}
}
// http://localhost:9000/dispatcher?action=sayHello&name=John
def sayHelloMethod(implicit request: RequestHeader) = {
val name = request.queryString.get("name").flatMap(_.headOption).getOrElse("")
Ok("Hello " + name )
}
// http://localhost:9000/dispatcher?action=newUser&name=John+Doe&address=john#doe.com
def newUserMethod(implicit request: RequestHeader) = {
val name = request.queryString.get("name").flatMap(_.headOption).getOrElse("")
val address = request.queryString.get("address").flatMap(_.headOption).getOrElse("")
Ok("We are creating new user " + name + " with address " + address)
}
Of course you will need to validate incoming types and values 'manually', especially when actions will be operating on the DataBase, anyway biggest part of your problem you have resolved now.

Lift RewriteResponse not finding a valid url

Hi I'm having some trouble with Lift and URL rewriting. I've written a simple rewrite rule:
LiftRules.rewrite.append {
case RewriteRequest(
ParsePath(List("user", userID), _, _, _), _, _) => {
println(userID)
RewriteResponse(List("viewUser"), Map("userID" -> urlDecode(userID)))
}
}
So when I enter http://localhost:8080/user/brian I expect a call to be made to the viewUser.html file I have placed in the webroot directory.
The mark up of viewUser.html is very simple:
<lift:surround with="default" at="content">
<p>ViewUser</p>
</lift:surround>
But instead of seeing viewUser I get an error:
The Requested URL /user/brian was not found on this server
Also if I enter the URL of viewUser by hand: http://localhost:8080/user/brian I get the same error.
I am out of ideas on this one, I did find a similar error which happens through the SiteMap system.
I've tried this with a cleanly checked out lift-archetype-blank project, by adding the viewUser.html and adding the single chunk of rewrite code.
Make sure you've added "viewUser" to the site map. Without doing so Lift doesn't know where to find page.