com.sigopt.net.HeadersBuilder Maven / Gradle / Ivy
package com.sigopt.net;
import com.sigopt.Sigopt;
import com.sigopt.exception.AuthenticationException;
import com.squareup.okhttp.Request;
import org.apache.commons.codec.binary.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
class HeadersBuilder {
public static Map build(Map headers) throws AuthenticationException {
return build(headers, null, null);
}
public static Map build(Map headers, String apiKey) throws AuthenticationException {
return build(headers, apiKey, null);
}
public static Map build(Map headers, String apiKey, String authKey) throws AuthenticationException {
Map ret = new HashMap();
ret = MapHelper.merge(ret, defaultHeaders());
if(authKey != null && !authKey.isEmpty()) {
ret = MapHelper.merge(ret, customAuthHeader(authKey, apiKey));
} else if(apiKey != null && !apiKey.isEmpty()) {
ret = MapHelper.merge(ret, basicAuthHeader(apiKey));
}
if(headers != null) {
ret.putAll(headers);
}
return ret;
}
public static Map defaultHeaders() {
Map headers = new HashMap();
String userAgent = "Sigopt/" + Sigopt.apiVersion + " JavaBindings/" + Sigopt.VERSION;
headers.put("User-Agent", userAgent);
return headers;
}
public static Map customAuthHeader(String authKey, String apiKey) {
Map ret = new HashMap();
ret.put(authKey, apiKey);
return ret;
}
public static Map basicAuthHeader(String apiKey) throws AuthenticationException {
if(apiKey == null) {
throw new AuthenticationException("An API key is required but was never set. Please see https://sigopt.com/docs for more information.");
}
Map ret = new HashMap();
byte[] apiKeyBytes = String.format("%s:", apiKey).getBytes();
String base64Key = new String(Base64.encodeBase64(apiKeyBytes));
ret.put("Authorization", "Basic " + base64Key);
return ret;
}
}