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

io.ipinfo.api.IPInfoBuilder Maven / Gradle / Ivy

There is a newer version: 3.0.0
Show newest version
package io.ipinfo.api;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import io.ipinfo.api.cache.Cache;
import io.ipinfo.api.cache.SimpleCache;
import io.ipinfo.api.context.Context;
import okhttp3.OkHttpClient;

import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Type;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class IPInfoBuilder {
    private File countryFile = new File(this.getClass().getClassLoader().getResource("en_US.json").getFile());
    private OkHttpClient client = new OkHttpClient.Builder().build();
    private String token = "";
    private Cache cache = new SimpleCache(Duration.ofDays(1));

    public IPInfoBuilder setClient(OkHttpClient client) {
        this.client = client;
        return this;
    }

    public IPInfoBuilder setToken(String token) {
        this.token = token;
        return this;
    }

    public IPInfoBuilder setCountryFile(File file) {
        this.countryFile = file;
        return this;
    }

    public IPInfoBuilder setCache(Cache cache) {
        this.cache = cache;
        return this;
    }

    public IPInfo build() {
        Type type = new TypeToken>() {
        }.getType();

        Gson gson = new Gson();
        Map map;

        try {
            map = Collections.unmodifiableMap(gson.fromJson(new FileReader(countryFile), type));
        } catch (Exception e) {
            map = Collections.unmodifiableMap(new HashMap<>());
        }

        return new IPInfo(client, new Context(map), token, cache);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy