EDIT: Why the down-votes? Been googling this at length, without success...
I have some groovy-classes, I'm trying to rewrite to Java.
The groovy-code uses wslite for REST-calls, and follows this pattern:
JsonBuilder request = createRequest();
Map<String, Object> params = createParams();
RESTClient client = new RESTClient(endpoint);
Response response = client.put(params) ( it -> { text(request); });
How do I rewrite the final line with the Closure part?
What is the Java equivalent?
Can't understand the goal because it's better to change rest-client if you are switching to java.
wslite library designed for groovy and using it for java will add complexity to your code.
However, in this particular case java code will look like this:
(it's groovy but with java-like syntax)
@Grab(group='com.github.groovy-wslite', module='groovy-wslite', version='1.1.2', transitive=false)
import groovy.json.*
import wslite.rest.*
@groovy.transform.CompileStatic
class TextBodyClosure extends Closure<Object> {
Object body;
public TextBodyClosure(Object owner, Object body) {
super(owner);
this.body = body;
}
public Object call() {
ContentBuilder cb = (ContentBuilder)this.getDelegate();
cb.text(body);
return null;
}
}
def content = ["hello": "world"];
JsonBuilder request = new JsonBuilder(content);
Map<String, Object> params = [:];
RESTClient client = new RESTClient("http://httpbin.org/put");
//Response response = client.put(params){ it -> text(request) };
Response response = client.put(params, new TextBodyClosure(this, request));
assert response.parsedResponseContent.json.json == content
println "SUCCESS"
this conversion based on a source code of wslite library.
when you are calling client.put(params, content)
the following code executed to transform content-closure to bytes:
as you can see - the content-closure passed into ContentBuilder that executes closure against itself - so, the delegate object is ContentBuilder at moment of execution...