Ratpack: Prefix binding with multiple "components" in past binding - ratpack

I've got a Ratpack application and I'm trying to configure an endpoint for GET requests which delegates to a handler based on a prefix. However, my URL path may contain multiple slashes, which I'd want to capture and use in my handler.
Example:
Given the requests http://localhost:8080/myEndpoint/foo/bar/ and http://localhost:8080/myEndpoint/baz/qux/fred/, I'd like to delegate to my handler MyEndpointHandler in both cases since the request paths are prefixed by myEndpoint. Inside MyEndpointHandler, I'd need to retrieve /foo/bar and /baz/qux/fred/ respectively, since these are the remaining parts of the path after the /myEndpoint prefix.
My original thinking was to do something like:
chain.path("myEndpoint/:restOfPath?", new MyEndpointHandler());
However this only seems to work for one slash (i.e. a request to http://localhost:8080/myEndpoint/foo is fine and I have access to /foo, but a request to http://localhost:8080/myEndpoint/foo/bar returns a 404).
I have also tried:
chain.prefix("myEndpoint", c1 -> c1.path(new MyEndpointHandler()));
However this returned a 404 for all requests regardless of the path after /myEndpoint.
Looking at the docs, https://ratpack.io/manual/current/api/ratpack/core/path/PathBinding.html#getPastBinding() seems like exactly what I need to be able to get the /foo/bar part of these requests, but I'm struggling to bind my handler to the chain in the right way to be able to access this "past binding".
Thanks in advance for the help!

Related

How to reuse variables from previous request in the Paw rest client?

I need to reuse value which is generated for my previous request.
For example, at first request, I make a POST to the URL /api/products/{UUID} and get HTTP response with code 201 (Created) with an empty body.
And at second request I want to get that product by request GET /api/products/{UUID}, where UUID should be from the first request.
So, the question is how to store that UUID between requests and reuse it?
You can use the Request Sent Dynamic values https://paw.cloud/extensions?extension_type=dynamic_value&q=request+send these will get the value used last time you sent a requst for a given request.
In your case you will want to combine the URLSentValue with the RegExMatch (https://paw.cloud/extensions/RegExMatch) to first get the url as it was last sent for a request and then extract the UUID from the url.
e.g
REQUEST A)
REQUEST B)
The problem is in your first requests answer. Just dont return "[...] an empty body."
If you are talking about a REST design, you will return the UUID in the first request and the client will use it in his second call: GET /api/products/{UUID}
The basic idea behind REST is, that the server doesn't store any informations about previous requests and is "stateless".
I would also adjust your first query. In general the server should generate the UUID and return it (maybe you have reasons to break that, then please excuse me). Your server has (at least sometimes) a better random generator and you can avoid conflicts. So you would usually design it like this:
CLIENT: POST /api/products/ -> Server returns: 201 {product_id: UUID(1234...)}
Client: GET /api/products/{UUID} -> Server returns: 200 {product_detail1: ..., product_detail2: ...}
If your client "loses" the informations and you want him to be later able to get his products, you would usually implement an API endpoint like this:
Client: GET /api/products/ -> Server returns: 200 [{id:UUID(1234...), title:...}, {id:UUID(5678...),, title:...}]
Given something like this, presuming the {UUID} is your replacement "variable":
It is probably so simple it escaped you. All you need to do is create a text file, say UUID.txt:
(with sample data say "12345678U910" as text in the file)
Then all you need to do is replace the {UUID} in the URL with a dynamic token for a file. Delete the {UUID} portion, then right click in the URL line where it was and select
Add Dynamic Value -> File -> File Content :
You will get a drag-n-drop reception widget:
Either press the "Choose File..." or drop the file into the receiver widget:
Don't worry that the dynamic variable token (blue thing in URL) doesn't change yet... Then click elsewhere to let the drop receiver go away and you will have exactly what you want, a variable you can use across URLs or anywhere else for that matter (header fields, form fields, body, etc):
Paw is a great tool that goes asymptotic to awesome when you explore the dynamic value capability. The most powerful yet I have found is the regular expression parsing that can parse raw reply HTML and capture anything you want for the next request... For example, if you UUID came from some user input and was ingested into the server, then returned in a html reply, you could capture that from the reply HTML and re-inject it to the URL, or any field or even add it to the cookies using the Dynamic Value capabilities of Paw.
#chickahoona's answer touches on the more normal way of doing it, with the first request posting to an endpoint without a UUID and the server returning it. With that in place then you can use the RegExpMatch extension to extract the value from the servers's response and use it in subsequent requests.
Alternately, if you must generate the UUID on the client side, then again the RegExpMatch extension can help, simply choose the create request's url for the source and provide a regexp that will strip the UUID off the end of it, such as /([^/]+)$.
A third option I'll throw out to you, put the UUID in an environment variable and just have all of your requests reference it from there.

Is it possible to return HTTP code 200, but give a "better" url without using 3xx?

Consider StackOverflow, where each question has a unique ID, but URLs are often overridden to include a stub in the URL. For readability and other reasons the stub helps users know they are at the right place.
I have a site that returns 200 when calling a URL like:
http://stackoverflow.com/questions/28057406/
But want the URL to update to:
http://stackoverflow.com/questions/28057406/is-it-possible-to-return-http-code-200-but-give-a-better-url-without-using-3x
The first call is technically valid and the code can retrieve the object and render it perfectly fine, but I'd like to update the URL to use the stubified one.
I'd prefer to do this without a redirect as just getting the ID causes a database call to get the object. Which would mean with a redirect the process would be:
Call http://stackoverflow.com/questions/28057406/
Retrieve item 25257999 from the database to get the name to make the stub
Redirect to http://stackoverflow.com/questions/28057406/is-it-possible-to-return-http-code-200-but-give-a-better-url-without-using-3x
New HTTP Call, so retrieve item 25257999 from the database to render the final page.
If possible I'd like to not use Javascript either.
So, is it possible to return Location as part of a HTTP header with a status code of 200 and the actual page, or am I stuck using 3xx calls or Javascript?
If you are just doing HTTP, you can either choose to redirect, or not choose to redirect... You can also (with Content-Location) tell the client that the canonical address is actually somewhere else... but no browser will respond to that.
To avoid the database-call, you could of course just cache the result.
If you are in a browser however, you can dynamically update the current address without forcing a refresh, with window.history.pushState.
For more information about that call, see this other SO answer:
Modify the URL without reloading the page

Designing proper REST URIs

I have a Java component which scans through a set of folders (input/processing/output) and returns the list of files in JSON format.
The REST URL for the same is:
GET http://<baseurl>/files/<foldername>
Now, I need to perform certain actions on each of the files, like validate, process, delete, etc. I'm not sure of the best way to design the REST URLs for these actions.
Since its a direct file manipulation, I don't have any unique identifier for the files, except their paths. So I'm not sure if the following is a good URL:
POST http://<baseurl>/file/validate?path=<filepath>
Edit: I would have ideally liked to use something like /file/fileId/validate. But the only unique id for files is its path, and I don't think I can use that as part of the URL itself.
And finally, I'm not sure which HTTP verb to use for such custom actions like validate.
Thanks in advance!
Regards,
Anand
When you implement a route like http:///file/validate?path you encode the action in your resource that's not a desired effect when modelling a resource service.
You could do the following for read operations
GET http://api.example.com/files will return all files as URL reference such as
http://api.example.com/files/path/to/first
http://api.example.com/files/path/to/second
...
GET http://api.example.com/files/path/to/first will return validation results for the file (I'm using JSON for readability)
{
name : first,
valid : true
}
That was the simple read only part. Now to the write operations:
DELETE http://api.example.com/files/path/to/first will of course delete the file
Modelling the file processing is the hard part. But you could model that as top level resource. So that:
POST http://api.example.com/FileOperation?operation=somethingweird will create a virtual file processing resource and execute the operation given by the URL parameter 'operation'. Modelling these file operations as resources gives you the possibility to perform the operations asynchronous and return a result that gives additional information about the process of the operation and so on.
You can take a look at Amazon S3 REST API for additional examples and inspiration on how to model resources. I can highly recommend to read RESTful Web Services
Now, I need to perform certain actions on each of the files, like validate, process, delete, etc. I'm not sure of the best way to design the REST URLs for these actions. Since its a direct file manipulation, I don't have any unique identified for the files, except their paths. So I'm not sure if the following is a good URL: POST http:///file/validate?path=
It's not. /file/validate doesn't describe a resource, it describes an action. That means it is functional, not RESTful.
Edit: I would have ideally liked to use something like /file/fileId/validate. But the only unique id for files is its path, and I don't think I can use that as part of the URL itself.
Oh yes you can! And you should do exactly that. Except for that final validate part; that is not a resource in any way, and so should not be part of the path. Instead, clients should POST a message to the file resource asking it to validate itself. Luckily, POST allows you to send a message to the file as well as receive one back; it's ideal for this sort of thing (unless there's an existing verb to use instead, whether in standard HTTP or one of the extensions such as WebDAV).
And finally, I'm not sure which HTTP verb to use for such custom actions like validate.
POST, with the action to perform determined by the content of the message that was POSTed to the resource. Custom “do something non-standard” actions are always mapped to POST when they can't be mapped to GET, PUT or DELETE. (Alas, a clever POST is not hugely discoverable and so causes problems for the HATEOAS principle, but that's still better than violating basic REST principles.)
REST requires a uniform interface, which in HTTP means limiting yourself to GET, PUT, POST, DELETE, HEAD, etc.
One way you can check on each file's validity in a RESTful way is to think of the validity check not as an action to perform on the file, but as a resource in its own right:
GET /file/{file-id}/validity
This could return a simple True/False, or perhaps a list of the specific constraint violations. The file-id could be a file name, an integer file number, a URL-encoded path, or perhaps an unencoded path like:
GET /file/bob/dir1/dir2/somefile/validity
Another approach would be to ask for a list of the invalid files:
GET /file/invalid
And still another would be to prevent invalid files from being added to your service in the first place, ie, when your service processes a PUT request with bad data:
PUT /file/{file-id}
it rejects it with an HTTP 400 (Bad Request). The body of the 400 response could contain information on the specific error.
Update: To delete a file you would of course use the standard HTTP REST verb:
DELETE /file/{file-id}
To 'process' a file, does this create a new file (resource) from one that was uploaded? For example Flickr creates several different image files from each one you upload, each with a different size. In this case you could PUT an input file and then trigger the processing by GET-ing the corresponding output file:
PUT /file/input/{file-id}
GET /file/output/{file-id}
If the processing isn't near-instantaneous, you could generate the output files asynchronously: every time a new input file is PUT into the web service, the web service starts up an asynchronous activity that eventually results in the output file being created.

How to apply the PUT verb in a REST request?

I'm working on a REST server. I have an order RESOURCE.
From my understanding the PUT verb should create a new order based on the URL. My question is: How can this work if the resource is new and you don't know the ID of the new order?
I know the debate about POST vs PUT, but I'm quoting the w3 specs for PUT http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
"If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI"
In RESTful APIs, PUT is typically used to update a resource or create one if it doesn't exist at the specified URL (i.e. the client provides the id). If the server generates the id, RESTful APIs typically use a POST to create new resources. In the latter scenario, the generated id/url is usually returned or specified in a redirect.
Example: POST /orders/
According to W3C Both PUT and POST can be used for update and/or create.
The basic difference between them is how the server handles the Request-URI. PUT URI identifies the entity and the server should't try to map it to another URL, while POST URI can be a handler for that content. Examples:
It's OK to POST a new order to /order, but not a PUT. You can update order 1 with a PUT or POST to /order/1.
To put it simply POST is for creating and PUT is for updating. If you don't have an ID for an object because it isn't created yet, you should be using a POST. If an object DOES exist and you just don't have the ID for it, you're going to have to search for it using a GET of some kind.
The thing to remember is Idempotence. A PUT (and GET for that matter) is idempotent. Basically meaning, you can hit the same URL over and over and it shouldn't make a difference the 2nd or 3rd time (It edits the data once, and calling it again it doesn't make that change again). However a POST is not idempotent. Meaning, you hit the same URL 3 or 4 times in a row and it's going to keep changing data (creating more and more objects). This is why a browser will warn you if you click back to a POST url.
You say, "don't know the ID of the new order" therefore the following is not true "URI is capable of being defined as a new resource by the requesting user agent", therefore PUT is not appropriate in your scenario.
Where is the confusion? I am of course assuming the Id would be part of the URL.

Cancel an HTTP GET request from Firefox Extension

I have a firefox extension that listens to "http-on-modify-request" and inspects all GET requests coming from firefox. I'd like to be able to cancel the request (say return a fail code to the page) or modify the URI of the request but can't seem to do it. the nsiHttpChannel object just doesn't allow it - for instance
delete httpChannel;
or reseting to an empty request
httpChannel = Components.classes["#mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Components.interfaces.nsIXMLHttpRequest);
don't work (and you can't modify the URI).
So how do you both intercept and modify http GET requests in a firefox extension.
delete httpChannel; just deletes the variable, sort of like saying httpChannel = undefined;. The request itself is unchanged. Similarly, your second idea just sets the variable to point at a new nsIHttpChannel instance, but the old request is still unchanged.
To modify the request, use its properties and methods. See nsIHttpChannel or nsIChannel or nsIRequest. As you say, you can't modify the URI so you might want to cancel it (see below) and replace it with a new one. I'm not sure exactly how to do that but I imagine one of those three pages has the answer.
To cancel it, use nsIRequest.cancel()

Resources