|
| 1 | +package com.siftscience; |
| 2 | + |
| 3 | +import com.siftscience.exception.MerchantAPIException; |
| 4 | +import okhttp3.HttpUrl; |
| 5 | +import okhttp3.OkHttpClient; |
| 6 | +import okhttp3.Request; |
| 7 | +import okhttp3.Response; |
| 8 | +import okhttp3.Credentials; |
| 9 | +import okhttp3.RequestBody; |
| 10 | +import okhttp3.MediaType; |
| 11 | + |
| 12 | +import java.io.IOException; |
| 13 | + |
| 14 | +public abstract class SiftMerchantRequest<T extends SiftMerchantResponse> { |
| 15 | + private final String accountId; |
| 16 | + FieldSet fieldSet; |
| 17 | + private OkHttpClient okClient; |
| 18 | + private HttpUrl baseUrl; |
| 19 | + |
| 20 | + protected abstract HttpUrl path(HttpUrl baseUrl); |
| 21 | + |
| 22 | + public HttpUrl url() { |
| 23 | + return path(baseUrl); |
| 24 | + } |
| 25 | + |
| 26 | + SiftMerchantRequest(HttpUrl baseUrl, String accountId, OkHttpClient okClient, FieldSet fields) { |
| 27 | + this.baseUrl = baseUrl; |
| 28 | + this.accountId = accountId; |
| 29 | + this.okClient = okClient; |
| 30 | + this.fieldSet = fields; |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * By default, the request is a JSON encoded POST. |
| 35 | + */ |
| 36 | + protected void modifyRequestBuilder(Request.Builder builder) { |
| 37 | + builder.header("Authorization", Credentials.basic(fieldSet.getApiKey(), "")).get(); |
| 38 | + builder.post(RequestBody.create(MediaType.parse("application/json"), fieldSet.toJson())); |
| 39 | + } |
| 40 | + |
| 41 | + abstract T buildResponse(Response response, FieldSet requestFields) throws IOException; |
| 42 | + |
| 43 | + public T send() throws IOException { |
| 44 | + fieldSet.validate(); |
| 45 | + |
| 46 | + Request.Builder okRequestBuilder = new Request.Builder().url(this.url()); |
| 47 | + modifyRequestBuilder(okRequestBuilder); |
| 48 | + Request request = okRequestBuilder.build(); |
| 49 | + T response = buildResponse(okClient.newCall(request).execute(), fieldSet); |
| 50 | + |
| 51 | + if (!response.isOk()) { |
| 52 | + throw new MerchantAPIException(response.getApiErrorMessage()); |
| 53 | + } |
| 54 | + |
| 55 | + return response; |
| 56 | + } |
| 57 | + |
| 58 | + public FieldSet getFieldSet() { |
| 59 | + return fieldSet; |
| 60 | + } |
| 61 | + |
| 62 | + protected String getAccountId() { |
| 63 | + return accountId; |
| 64 | + } |
| 65 | +} |
0 commit comments