package com.niyamit.spreedly;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.ParameterizedType;
import java.util.Scanner;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import org.apache.commons.codec.binary.Base64;
/**
* Helper class for invoking the calls to spreedly. The intent of this class is
* to provide a consistent implementation of the calls to spreedly across the
* board.
*
* @author bsneade
*/
public class SpreedlyInvoker {
private final String environmentKey;
private final String accessSecret;
private final Client client;
public SpreedlyInvoker(String environmentKey, String accessSecret, Client client) {
this.environmentKey = environmentKey;
this.accessSecret = accessSecret;
this.client = client;
}
public<R> R invoke(final String targetUrl, final String method, Object inputObject, Class<R> resultClass) throws WebApplicationException {
final WebTarget target = client.target(targetUrl);
final Invocation.Builder builder = target.request()
.header("Authorization", new StringBuilder("Basic ")
.append(Base64.encodeBase64String(new StringBuilder(environmentKey)
.append(":")
.append(accessSecret).toString().getBytes())).toString());
final Response response;
if (inputObject == null) {
response = builder.method(method);
} else {
response = builder.method(method, Entity.xml(inputObject));
}
if (!(response.getStatus() >= 200 && response.getStatus() < 300)) {
//not a 200 response.. so fail
final InputStream inputStream = response.readEntity(InputStream.class);
try {
final Scanner scanner = new Scanner(inputStream).useDelimiter("\\A");
throw new WebApplicationException(scanner.hasNext() ? scanner.next() : "Unknown problem", response);
} finally {
try {
inputStream.close();
} catch (IOException ex) {
//Silently ignore this, which sucks.
}
}
}
return response.readEntity(resultClass);
}
}