io.relayr.java.api.ApiHelper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-sdk Show documentation
Show all versions of java-sdk Show documentation
Java SDK for connecting to the Relayr Cloud
The newest version!
package io.relayr.java.api;
import com.squareup.okhttp.Cache;
import com.squareup.okhttp.OkHttpClient;
import java.io.File;
import retrofit.Endpoint;
import retrofit.ErrorHandler;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.RestAdapter.LogLevel;
import retrofit.RetrofitError;
import retrofit.client.Client;
import retrofit.client.Response;
import static io.relayr.java.RelayrJavaApp.getToken;
import static io.relayr.java.RelayrJavaApp.getUserAgent;
import static io.relayr.java.api.ApiHelper.InterceptorType.MODELS;
import static io.relayr.java.api.ApiHelper.InterceptorType.OAUTH;
public class ApiHelper {
public ApiHelper() {}
public enum InterceptorType {API, OAUTH, MODELS}
private static final int DISK_CACHE_SIZE = 10 * 1024 * 1024; // 10MB
private static final RequestInterceptor defaultInterceptor = new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader("User-Agent", getUserAgent());
request.addHeader("Authorization", getToken());
request.addHeader("Content-Type", "application/json; charset=UTF-8");
}
};
private static final RequestInterceptor modelsInterceptor = new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader("User-Agent", getUserAgent());
request.addHeader("Authorization", getToken());
request.addHeader("Content-Type", "application/hal+json");
}
};
private static final RequestInterceptor oauthInterceptor = new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader("User-Agent", getUserAgent());
}
};
public OkHttpClient createOkHttpClient() {
OkHttpClient client = new OkHttpClient();
client.setCache(new Cache(new File("/", "https"), DISK_CACHE_SIZE));
return client;
}
public RestAdapter createAdapter(Client client, Endpoint endpoint, InterceptorType type, LogLevel level) {
return new RestAdapter.Builder()
.setClient(client)
.setEndpoint(endpoint)
.setErrorHandler(new ApiErrorHandler())
.setLogLevel(level)
.setRequestInterceptor(
type == OAUTH ? oauthInterceptor :
type == MODELS ? modelsInterceptor :
defaultInterceptor)
.build();
}
class ApiErrorHandler implements ErrorHandler {
@Override public Throwable handleError(RetrofitError cause) {
Response response = cause.getResponse();
if (response != null && response.getStatus() == 401)
return new UnauthorizedException(cause);
if (response != null && response.getStatus() > 301)
return new Exception(cause);
return cause;
}
}
public class UnauthorizedException extends Throwable {
public UnauthorizedException(RetrofitError cause) {
super(cause);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy