Skip to content

Instantly share code, notes, and snippets.

@sizovs
Created February 26, 2021 13:20
Show Gist options
  • Select an option

  • Save sizovs/08dd7e8dcd7de6de5b37a1fabf8ab5c4 to your computer and use it in GitHub Desktop.

Select an option

Save sizovs/08dd7e8dcd7de6de5b37a1fabf8ab5c4 to your computer and use it in GitHub Desktop.
package com.homework.services;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.homework.exceptions.CountryResolverException;
import com.homework.models.Country;
import com.homework.repositories.CountryRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
@Service
@Configurable
@PropertySource("classpath:application.properties")
public class CountryResolver {
@Value("${api.notASecret}")
private String accessToken;
private final ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
public Country resolveCountry(String ip) throws CountryResolverException {
try {
return tryResolveCountry(ip);
} catch (Exception e) {
throw new CountryResolverException("Couldn't resolve country", e);
}
}
private Country tryResolveCountry(String ip) throws URISyntaxException, java.io.IOException, InterruptedException {
var request = HttpRequest.newBuilder()
.uri(new URI(String.format("http://api.ipstack.com/%s?access_key=%s", ip, accessToken))).GET()
.build();
var response = HttpClient.newHttpClient().send(request,
HttpResponse.BodyHandlers.ofString());
var resp = mapper.readValue(response.body(), CountryDto.class);
return new Country(resp.code, resp.name);
}
static class CountryDto {
@JsonProperty("country_code")
public String code;
@JsonProperty("country_name")
public String name;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment