Getting and using REST client instances
restfn
templating functions
The restfn
templating functions allow you to obtain and use REST clients. This works only for clients that have been configured and declared with the RESTEasy client.
[#assign jokesService = restfn.getService("icndbClient", "info.magnolia.documentation.modules.restclientexamples.client.IcndbService")] (1)
[#assign response = jokesService.joke("random", "Tiger", "Lilly") /] (2)
<i>${response.get("value").get("joke").getTextValue()!"Nix found"}</i>
Line 1 accesses an instance of the client interface. In this example, it is of the IcndbService
type.
|
Line 2 calls the method #joke
, which returns a JsonNode
object.
This is a simplified example. See Jackson Javadoc for how to process
|
During installation of the magnolia-resteasy-client module, RestEasyClientModuleVersionHandler adds restfn to renderer configurations. Make sure that the renderType of your template definition points to a renderer that is configured to use restfn . See Configure the functions in a renderer for how to add templating functions to a renderer.
|
Java using client registry
To learn how to obtain and use a REST client, here is a model class that uses the same client as in the above example:
-
Add info.magnolia.rest.client.registry.RestClientRegistry as a parameter to the constructor and assign it as a final instance variable.
-
Obtain a info.magnolia.resteasy.client.RestEasyClient object from
RestClientRegistry
. Note that#getRestClient
requires the configured name of the rest client definition. -
Create an instance of the declared interface
IcndbService
. -
Call the declared method(s) on the service.
Component example
You have the option to configure components (filters) to be executed on every request. One use case could be authentication.
Client request filter
Here is an example filter that would handle authorization for each request.
package org.example.filters;
import info.magnolia.context.Context;
import info.magnolia.context.MgnlContext;
import java.io.IOException;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.ext.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Interceptor for RESTEasy to handle authentication with an access token.
*/
@Provider
public class AuthenticationInterceptor implements ClientRequestFilter {
private static final Logger log = LoggerFactory.getLogger(AuthenticationInterceptor.class);
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
if (MgnlContext.hasInstance() && MgnlContext.hasAttribute("ACCESS_TOKEN", Context.APPLICATION_SCOPE)) {
requestContext.getHeaders().putSingle("Authorization",
"OAuth " + MgnlContext.getAttribute("ACCESS_TOKEN", Context.APPLICATION_SCOPE));
log.trace("Authorization : {}",
(String) MgnlContext.getAttribute("ACCESS_TOKEN", Context.APPLICATION_SCOPE));
}
}
}