Scalatra - how do we do an internal redirect / forward of request - redirect

I want to call another internal url from my scalatra 'controller'. I can't do a simple redirect, as there's some security settings that mean a user has access only to the first url.
Is there a way to do this?

get("/foo") {
servletContext.getRequestDispatcher("/bar").forward(request, response)
}

The get() method is defined as (similar to POST, et al):
def get(transformers : org.scalatra.RouteTransformer*)(action : => scala.Any) : org.scalatra.Route
Depends on what you mean by internal redirect, I presume you just want to execute another route's action. You have a few options of what you can do. This seems to be working for me:
val canonicalEndpoint = get("/first/route") {
//do things in here
}
Then you could subsequently do:
get("/second/route")( canonicalEndpoint.action )
And I think you would get your desired response.
I like saving the whole Route response of the get() as you may also want to use that with scalatra's url() function in routing.

Related

Parameter based redirect in nginx

I have http requests such as the one below being sent to an nginx server:
GET /app/handler?id=1234&param1=cbd&param2=234
Now, I want to rewrite the request to a different handler depending on the id param in the request. eg. redirect to handler_even for even ids and handler_odd for odd ids. This is shown below:
GET /app/handler?id=1234&param1=cbd&param2=234 => /app/handler_even?id=1234&param1=cbd&param2=234
GET /app/handler?id=123&param1=cbd&param2=234 => /app/handler_odd?id=123&param1=cbd&param2=234
I can do the rewrite using proxy_pass, but I'm unsure how to redirect using the id parameter value. Any idea how I could go about this? Would using "if" be the best way to go about this?
Any pointers would be useful
Rather than use an if directive, you could use a map. To internally rewrite the URI use:
map $arg_id $handler {
default /app/handler_even;
~[13579]$ /app/handler_odd;
}
server {
...
location = /app/handler {
rewrite ^ $handler last;
}
...
}
The map should be located at the same level as your server directive (as shown above), i.e. within the http container.
See this document for details.

How can I redirect to an error page in my Play app?

Or more precisely...
I already have an error page route defined like so:
GET /error controllers.pages.ErrorController.page(msg: String, returnTo: String)
And a controller method like this:
object ErrorController extends Controller {
def page(msg: String, returnTo: String) = ReceiverRestricted { implicit req =>
val action = List(Button(F8, "Continue", Call("GET", returnTo)))
Results.Ok(views.html.base(Html("Oops"), List(Html(msg)), None, action))
}
}
If I programmatically call, say, ErrorController.page("You did something daft!", "/home") I get to a page that looks like I want, ie:
Oops
You did something daft!
F8 Continue
However the url is ugly:
http://localhost:9000/error?msg=You%20did%20something%20daft!&returnTo=/home
I want to change this so the msg= query parameter doesn't appear in the url. How can I accomplish this? I tried removing the query parameter and redirecting to the error page with the message passed in via the flash cookie - that worked but reloading the browser page loses the message. I can't use the session cookie because I already store other data in the session almost upto its limit.
You can use flash feature.
Here is a sample:
In your controller you can redirect the user to error page with:
Redirect("/error").flashing(
"reason" -> "The item has been created"
)
And in Error action:
def error = Action { implicit request =>
Ok {
val reason = flash.get("reason").getOrElse("General Error")
//DO your stuff with reason variable
}
}
Obviously you can have as many as flash variables you want.
Since Play is restful and stateless, I can't see an easy way to pass on an error message during a redirect without using Play's flash. Of course you could store the message in an temporary cookie in the browser. Another possibility could be to store it in your database (or whatever persistence technology you use), but this seems to be like cracking a nut with a sledgehammer.

Restangular - how to cancel/implement my own request

I found a few examples of using fullRequestInterceptor and httpConfig.timeout to allow canceling requests in restangular.
example 1 | example 2
this is how I'm adding the interceptor:
app.run(function (Restangular, $q) {
Restangular.addFullRequestInterceptor(function (element, operation, what, url, headers, params, httpConfig) {
I managed to abort the request by putting a resolved promise in timeout (results in an error being logged and the request goes out but is canceled), which is not what I want.
What I'm trying to do - I want to make the AJAX request myself with my own requests and pass the result back to whatever component that used Restangular. Is this possible?
I've been looking a restangular way to solve it, but I should have been looking for an angular way :)
Overriding dependency at runtime in AngularJS
Looks like you can extend $http before it ever gets to Restangular. I haven't tried it yet, but it looks like it would fit my needs 100%.
I'm using requestInterceptor a lot, but only to change parameters and headers of my request.
Basically addFullRequestInterceptor is helping you making change on your request before sending it. So why not changing the url you want to call ?
There is the httpConfig object that you can modify and return, and if it's close to the config of $http (and I bet it is) you can change the url and even method, and so change the original request to another one, entirely knew.
After that you don't need timeout only returning an httpConfig customise to your need.
RestangularConfigurer.addFullRequestInterceptor(function (element, operation, route, url, headers, params, httpConfig) {
httpConfig.url = "http://google.com";
httpConfig.method = "GET";
httpConfig.params = "";
return {
httpConfig: httpConfig
};
});
It will be pass on and your service or controller won't know that something change, that's the principle of interceptor, it allow you to change stuff and returning to be use by the next process a bit like a middleware. And so it will be transparent to the one making the call but the call will be made to what you want.

Play 2 reverse routing, get route from controller method

Using the Play 2.2.3 framework, given I have a route like this one in my routes file :
GET /event controllers.Event.events
How can I programatically get the "/event" knowing the method I am trying to reach, in this case 'controllers.Authentication.authenticate' ?
I need it for test purpose, because I would like to have better test waiting not for the route itself but for the controllers method really called. So maybe there is another solution than getting the route and test it this way like I do for now :
//Login with good password and login
val Some(loginResult) = route(FakeRequest(POST, "/login").withFormUrlEncodedBody(
("email", email)
, ("password", password)))
status(loginResult)(10.seconds) mustBe 303
redirectLocation(loginResult).get mustBe "/event"
You construct the reverse route in this way:
[full package name].routes.[controller].[method]
In your example:
controllers.routes.Authentication.authenticate
controllers.routes.Events.events
But say you broke your packages out like controllers.auth and controllers.content, then they would be:
controllers.auth.routes.Authentication.authenticate
controllers.content.routes.Events.events
The reverse routes return a Call, which contains an HTTP method and URI. In your tests you can construct a FakeRequest with a Call:
FakeRequest(controllers.routes.Authentication.authenticate)
And you can also use it to test the redirect URI:
val call: Call = controllers.routes.Events.events
redirectLocation(loginResult) must beSome(call.url)

Play Framework - Redirect with params

I am trying to figure out how to do a redirect within a controller action in Play (2.0) using Scala.
The redirect using
Redirect(routes.Application.index)
works just fine.
What I cannot figure out from the docs, API, or Google is how to add parameters to the call.
I am coming from Grails where this could be done easily as follows:
redirect action: "index", params: ["key": "value"]
.
The only way I have found is to call Redirect using a string url and a query string, which seems awkward.
Basically I would like to make use of Redirect(Call) somehow, but I do not how to create the Call object using reverse routing.
Am I missing something/not getting the concept in Play/Scala?
Thanks in Advance!
Ellou'
A route is just a function, so you can pass arguments as usual:
// Redirect to /hello/Bob
def helloBob = Action {
Redirect(routes.Application.hello("Bob"))
}
This snippet comes from http://www.playframework.org/documentation/2.0/ScalaRouting (at the bottom)
You can also avoid creating another function just for this in your controller. In your route config, you can simply add something like this:
GET /google #controllers.Default.redirect(to = "http://google.com")