All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sigopt.net.HeadersBuilder Maven / Gradle / Ivy

There is a newer version: 6.3.0
Show newest version
package com.sigopt.net;

import com.sigopt.Sigopt;
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) {
        return build(headers, null, null);
    }

    public static Map build(Map headers, String apiKey) {
        return build(headers, apiKey, null);
    }

    public static Map build(Map headers, String apiKey, String authKey) {
        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) {
        Map ret = new HashMap();
        if (apiKey != null) {
            byte[] apiKeyBytes = String.format("%s:", apiKey).getBytes();
            String base64Key = new String(Base64.encodeBase64(apiKeyBytes));
            ret.put("Authorization", "Basic " + base64Key);
        }
        return ret;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy