com.nhl.link.rest.client.runtime.response.DataResponseHandler Maven / Gradle / Ivy
package com.nhl.link.rest.client.runtime.response;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nhl.link.rest.client.ClientDataResponse;
import com.nhl.link.rest.client.LinkRestClientException;
import com.nhl.link.rest.client.runtime.jackson.IJsonEntityReader;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @since 2.0
*/
public class DataResponseHandler extends BaseResponseHandler> {
private static final String DATA_NODE = "data";
private static final String TOTAL_NODE = "total";
private IJsonEntityReader jsonEntityReader;
public DataResponseHandler(JsonFactory jsonFactory, IJsonEntityReader jsonEntityReader) {
super(jsonFactory);
this.jsonEntityReader = jsonEntityReader;
}
@Override
protected ClientDataResponse doHandleResponse(Status status, Response response) {
List items;
long total;
String entity = response.readEntity(String.class);
JsonNode responseNode;
try {
responseNode = new ObjectMapper().readTree(jsonFactory.createParser(entity));
JsonNode dataNode = responseNode.get(DATA_NODE);
if (dataNode == null || !dataNode.isArray()) {
throw new LinkRestClientException(
"Failed to parse response -- '" + DATA_NODE + "' is missing or has a wrong type");
}
items = new ArrayList<>(dataNode.size() + 1);
for (JsonNode itemNode : dataNode) {
items.add(jsonEntityReader.readEntity(itemNode));
}
JsonNode totalNode = responseNode.get(TOTAL_NODE);
if (totalNode == null || !totalNode.isNumber()) {
throw new LinkRestClientException(
"Failed to parse response -- '" + TOTAL_NODE + "' is missing or has a wrong type");
}
total = totalNode.asLong();
} catch (IOException e) {
throw new LinkRestClientException("Failed to parse response", e);
}
return new ClientDataResponse<>(status, items, total);
}
}