From 0bb952c4e638494d4a5d640f88182604ae842e74 Mon Sep 17 00:00:00 2001 From: vladp Date: Wed, 15 Apr 2026 10:17:47 +0700 Subject: [PATCH] dev add geo country service --- .../nocopy/service/geo/GeoCountryService.java | 58 +++++++------------ 1 file changed, 22 insertions(+), 36 deletions(-) diff --git a/src/main/java/ru/soune/nocopy/service/geo/GeoCountryService.java b/src/main/java/ru/soune/nocopy/service/geo/GeoCountryService.java index 08a0ba4..1a2e662 100644 --- a/src/main/java/ru/soune/nocopy/service/geo/GeoCountryService.java +++ b/src/main/java/ru/soune/nocopy/service/geo/GeoCountryService.java @@ -2,63 +2,49 @@ package ru.soune.nocopy.service.geo; import com.maxmind.geoip2.DatabaseReader; import com.maxmind.geoip2.model.CountryResponse; -import jakarta.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; import org.springframework.stereotype.Service; +import java.io.IOException; import java.net.InetAddress; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; @Service @Slf4j public class GeoCountryService { - private DatabaseReader dbReader; - private final Map cache = new ConcurrentHashMap<>(); + private final DatabaseReader dbReader; - @PostConstruct - public void init() { - try { - var resource = new ClassPathResource("geo/GeoLite2-Country.mmdb"); - this.dbReader = new DatabaseReader.Builder(resource.getInputStream()).build(); - } catch (Exception e) { - log.error("Failed to load Geo DB", e); - } + public GeoCountryService() throws IOException { + Resource resource = new ClassPathResource("geo/GeoLite2-Country.mmdb"); + this.dbReader = new DatabaseReader.Builder(resource.getInputStream()).build(); } public String getCountry(String input) { - if (input == null || input.isBlank()) { - return null; - } - - String host = extractHost(input); - - if (cache.containsKey(host)) { - return cache.get(host); - } - try { - InetAddress ip = InetAddress.getByName(host); + String domain = extractDomain(input); + + InetAddress ip = InetAddress.getByName(domain); + CountryResponse response = dbReader.country(ip); - String country = response.getCountry().getIsoCode(); - - cache.put(host, country != null ? country : ""); - log.debug("{} → {}", host, country); - return country; + return response.getCountry().getName(); } catch (Exception e) { - cache.put(host, ""); - return null; + log.error("Failed for input: {}", input, e); + return "UNKNOWN"; } } - private String extractHost(String input) { - String s = input.replaceFirst("^https?://", ""); - s = s.split("/")[0]; - s = s.split(":")[0]; + private String extractDomain(String input) { + if (input == null || input.isEmpty()) { + throw new IllegalArgumentException("Input is empty"); + } - return s; + String cleaned = input.replaceAll("^https?://", ""); + cleaned = cleaned.split("/")[0]; + cleaned = cleaned.split(":")[0]; + + return cleaned; } } \ No newline at end of file