I have written some code using RESTEasy to handle RESTful service calls and parse the response XML into relevant JAXB annotated classes. At the moment I have seperate methods for each return type:
public class RestBase {
protected final RestClient restClient;
public RestBase() {
restClient = RestManager.getClient();
}
protected List<GridNodeDTO> getGridNodes(String path, List<String[]> params){
Response entity = getEntity(path, params);
return entity.readEntity(new GenericType<List<GridNodeDTO>>() {});
}
protected UnauthorizedAgentDTO getAgent(String path, List<String[]> params){
Response entity = getEntity(path, params);
return entity.readEntity(new GenericType<UnauthorizedAgentDTO>() {});
}
// other types skipped ...
protected Response getEntity(String path, List<String[]> params) {
ResteasyWebTarget target = getTarget();
target = target.path(path);
if (params != null) {
for (String[] s : params) {
target = target.queryParam(s[0], s[1]);
}
}
Response response = target.request(MediaType.APPLICATION_XML).get();
if (response.getStatus() != Response.Status.OK.getStatusCode()) {
throw new RuntimeException(String.format("Invalid response status: %d\n%s", response.getStatus(), response));
}
return response;
}
private ResteasyWebTarget getTarget() {
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target(UriBuilder.fromUri(PropertiesHandler.getPropertyByKey("restUrl")).build());
client.register(new AddAuthHeadersRequestFilter(restClient.getUser(), restClient.getPass()));
return target;
}
Could I reduce the amount of code by using generics? I have had some luck with using:
@SuppressWarnings("unchecked")
protected <T> T getRestResponse(String path, List<String[]> params, final Class<T> type) {
// skipped ... getResponse()
return (T)response.readEntity(new GenericType(type) {});
}
But this does not work with lists, because it seems, that the program knows nothing of generic type of list at runtime. And it seems that the compiler also kind of knows it (type erasure). What ways there are to optimize my routines?