I'd like to achieve something like the following (from within JavaScript) in Rhino.
myService.http('http://localhost:9000')
.path('foo/bar')
.get();
And then having the final get() return the actual response. It's modeled after Jersey's web request builder in Java.
The Java code I have so far is:
class MyHttpRequestBuilder {
private final String baseUrl;
private final StringBuilder path = new StringBuilder();
private final Map<String, String> queryParams = new HashMap<>();
private final Map<String, String> headers = new HashMap<>();
public MyHttpRequestBuilder(String baseUrl) {
this.baseUrl = baseUrl;
}
public MyHttpRequestBuilder path(String path) {
this.path.append(path);
return this;
}
public MyHttpRequestBuilder header(String headerKey, String headerValue) {
headers.put(headerKey, headerValue);
return this;
}
public MyHttpRequestBuilder queryParam(String queryKey, String queryValue) {
queryParams.put(queryKey, queryValue);
return this;
}
public String get() {
return "Testing - Accessed " + baseUrl + " with path " + path;
}
}
I've registered this in a service class like so:
public class MyService {
public MyHttpRequestBuilder http(String baseUrl) {
return new MyHttpRequestBuilder(baseUrl);
}
}
I am then adding that into a Scriptable container in the Rhino context, as per various examples.
It works fine if I just call functions directly that simply return a String or another object.
Unfortunately the builder approach with "return this;" (which would allow for a more fluent code on the JS side) does not want to play ball. Is this even possible with Rhino?
I am using Java 8 and Rhino 1.7.7.1.