package io.ljunggren.fedex.api.service;
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicHeader;
import io.ljunggren.fedex.api.model.CodeMessage;
import io.ljunggren.fedex.api.model.Debug;
import io.ljunggren.fedex.api.model.validate.request.ValidationRequest;
import io.ljunggren.fedex.api.model.validate.response.ValidationResponse;
import io.ljunggren.json.utils.JsonUtils;
public class AddressService extends BaseService {
public AddressService(String domain) {
super(domain);
}
private final String URI = domain + "/address/v1/addresses/resolve";
public ValidationResponse validate(ValidationRequest validationRequest, String accessToken) throws Exception {
return validate(validationRequest, accessToken, getHttpClient());
}
public ValidationResponse validate(ValidationRequest validationRequest, String accessToken, CloseableHttpClient httpClient) throws Exception {
try {
HttpPost post = new HttpPost(URI);
post.setHeaders(generateHeaders(accessToken));
post.setEntity(new StringEntity(JsonUtils.objectToJson(validationRequest)));
CloseableHttpResponse response = httpClient.execute(post);
int responseCode = response.getStatusLine().getStatusCode();
String json = getResult(response);
if (KNOWN_RESPONSE_CODES.contains(responseCode)) {
return parse(json, ValidationResponse.class);
}
if (THROTTLING_CODE == responseCode) {
return new ValidationResponse().addError(
new CodeMessage("Throttled", "Too many requests"));
}
return new ValidationResponse().addError(
new CodeMessage("Tracking Error", String.format("Unknown response code %d", responseCode)));
} catch(Exception e) {
return new ValidationResponse().addError(
new CodeMessage("Tracking Error", e.getMessage()));
} finally {
httpClient.close();
}
}
public Debug debug(ValidationRequest validationRequest, String accessToken) throws Exception {
String request = JsonUtils.objectToJson(validationRequest);
Debug debug = new Debug();
debug.setRequest(request);
HttpPost post = new HttpPost(URI);
post.setHeaders(generateHeaders(accessToken));
post.setEntity(new StringEntity(request));
return debug(post, getHttpClient(), debug);
}
private Header[] generateHeaders(String accessToken) {
return new Header[] {
new BasicHeader("content-type", "application/json"),
new BasicHeader("x-locale", "en_US"),
new BasicHeader("authorization", String.format("Bearer %s", accessToken))
};
}
}