Search in sources :

Example 6 with Location

use of com.maxmind.geoip2.record.Location in project divolte-collector by divolte.

the class DatabaseLookupService method loadExternalDatabase.

private static DatabaseReader loadExternalDatabase(final Path location) throws IOException {
    /*
         * We have 2 strategies here.
         * 1) If compressed, we load via a stream (which means into memory).
         * 2) If it's not compressed, we pass a File in directly which allows DatabaseReader
         *    to mmap(2) the file.
         */
    final DatabaseReader reader;
    if ("gz".equals(com.google.common.io.Files.getFileExtension(location.toString()))) {
        try (final InputStream rawStream = Files.newInputStream(location);
            final InputStream bufferedStream = new BufferedInputStream(rawStream);
            final InputStream dbStream = new GZIPInputStream(bufferedStream)) {
            logger.debug("Loading compressed GeoIP database: {}", location);
            reader = new DatabaseReader.Builder(dbStream).build();
        }
    } else {
        logger.debug("Loading GeoIP database: {}", location);
        reader = new DatabaseReader.Builder(location.toFile()).build();
    }
    logger.info("Loaded GeoIP database: {}", location);
    return reader;
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) BufferedInputStream(java.io.BufferedInputStream) GZIPInputStream(java.util.zip.GZIPInputStream) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) DatabaseReader(com.maxmind.geoip2.DatabaseReader)

Example 7 with Location

use of com.maxmind.geoip2.record.Location in project bender by Nextdoor.

the class GeoIpOperation method perform.

@Override
public InternalEvent perform(InternalEvent ievent) {
    String ipStr = null;
    /*
     * Get field containing an IP address
     */
    try {
        ipStr = ievent.getEventObj().getField(this.pathToIpAddress);
    } catch (NoSuchElementException e) {
        if (!this.required) {
            return ievent;
        }
        throw new OperationException("ip address field " + this.pathToIpAddress + " does not exist");
    }
    if (ipStr == null) {
        if (!this.required) {
            return ievent;
        }
        throw new OperationException("ip address field " + this.pathToIpAddress + " was null");
    }
    /*
     * Sometimes the field contains comma separated ip addresses (ie forwarded web requests). In
     * this case pick the first value in the list which is typically the user.
     */
    if (!ipStr.isEmpty() && ipStr.contains(",")) {
        ipStr = ipStr.split(",")[0];
    }
    InetAddress ipAddress = null;
    try {
        ipAddress = InetAddress.getByName(ipStr);
    } catch (UnknownHostException e) {
        if (!this.required) {
            return ievent;
        }
        throw new OperationException(e);
    }
    if (ipAddress == null) {
        if (!this.required) {
            return ievent;
        }
        throw new OperationException("ip address " + ipStr + " did not resolve");
    }
    CityResponse response = null;
    try {
        response = this.databaseReader.city(ipAddress);
    } catch (IOException | GeoIp2Exception e) {
        if (!this.required) {
            return ievent;
        }
        throw new OperationException(e);
    }
    HashMap<String, Object> geo = new HashMap<String, Object>(1);
    for (GeoProperty property : this.geoProperties) {
        switch(property) {
            case COUNTRY_NAME:
                if (response.getCountry() == null) {
                    if (!this.required) {
                        return ievent;
                    }
                    throw new OperationException("country returned null");
                }
                geo.put("country_name", response.getCountry().getName());
                break;
            case COUNTRY_ISO_CODE:
                if (response.getCountry() == null) {
                    if (!this.required) {
                        return ievent;
                    }
                    throw new OperationException("country returned null");
                }
                geo.put("country_iso_code", response.getCountry().getIsoCode());
                break;
            case SUBDIVISION_NAME:
                if (response.getMostSpecificSubdivision() == null) {
                    if (!this.required) {
                        return ievent;
                    }
                    throw new OperationException("MostSpecificSubdivision returned null");
                }
                geo.put("subdivision_name", response.getMostSpecificSubdivision().getName());
                break;
            case SUBDIVISION_ISO_CODE:
                if (response.getMostSpecificSubdivision() == null) {
                    if (!this.required) {
                        return ievent;
                    }
                    throw new OperationException("MostSpecificSubdivision returned null");
                }
                geo.put("subdivision_iso_code", response.getMostSpecificSubdivision().getIsoCode());
                break;
            case CITY_NAME:
                if (response.getCity() == null) {
                    if (!this.required) {
                        return ievent;
                    }
                    throw new OperationException("city returned null");
                }
                geo.put("city_name", response.getCity().getName());
                break;
            case POSTAL_CODE:
                if (response.getPostal() == null) {
                    if (!this.required) {
                        return ievent;
                    }
                    throw new OperationException("postal returned null");
                }
                geo.put("postal_code", response.getPostal().getCode());
                break;
            case LOCATION:
                if (response.getLocation() == null) {
                    if (!this.required) {
                        return ievent;
                    }
                    throw new OperationException("location returned null");
                }
                Double lat = response.getLocation().getLatitude();
                Double lon = response.getLocation().getLongitude();
                if (lat == null || lon == null) {
                    if (!this.required) {
                        return ievent;
                    }
                    throw new OperationException("error getting lat/lon");
                }
                HashMap<String, Object> location = new HashMap<String, Object>(2);
                location.put("lat", lat);
                location.put("lon", lon);
                geo.put("location", location);
                break;
        }
    }
    ievent.getEventObj().setField(this.destFieldName, geo);
    return ievent;
}
Also used : UnknownHostException(java.net.UnknownHostException) HashMap(java.util.HashMap) IOException(java.io.IOException) GeoIp2Exception(com.maxmind.geoip2.exception.GeoIp2Exception) CityResponse(com.maxmind.geoip2.model.CityResponse) InetAddress(java.net.InetAddress) GeoProperty(com.nextdoor.bender.operations.geo.GeoIpOperationConfig.GeoProperty) NoSuchElementException(java.util.NoSuchElementException) OperationException(com.nextdoor.bender.operation.OperationException)

Example 8 with Location

use of com.maxmind.geoip2.record.Location in project cas by apereo.

the class MaxmindDatabaseGeoLocationServiceTests method verifyOperation.

@Test
public void verifyOperation() throws Exception {
    val city = mock(DatabaseReader.class);
    val cityResponse = new CityResponse(new City(), new Continent(), new Country(), new Location(), new MaxMind(), new Postal(), new Country(), new RepresentedCountry(), new ArrayList<>(), new Traits());
    when(city.city(any(InetAddress.class))).thenReturn(cityResponse);
    val country = mock(DatabaseReader.class);
    val countryResponse = new CountryResponse(new Continent(), new Country(), new MaxMind(), new Country(), new RepresentedCountry(), new Traits());
    when(country.country(any(InetAddress.class))).thenReturn(countryResponse);
    val service = new MaxmindDatabaseGeoLocationService(city, country);
    val response = service.locate("127.0.0.1");
    assertNotNull(response);
    val response2 = service.locate(100D, 100D);
    assertNull(response2);
}
Also used : lombok.val(lombok.val) RepresentedCountry(com.maxmind.geoip2.record.RepresentedCountry) City(com.maxmind.geoip2.record.City) Traits(com.maxmind.geoip2.record.Traits) CityResponse(com.maxmind.geoip2.model.CityResponse) Continent(com.maxmind.geoip2.record.Continent) MaxMind(com.maxmind.geoip2.record.MaxMind) RepresentedCountry(com.maxmind.geoip2.record.RepresentedCountry) Country(com.maxmind.geoip2.record.Country) CountryResponse(com.maxmind.geoip2.model.CountryResponse) InetAddress(java.net.InetAddress) Postal(com.maxmind.geoip2.record.Postal) Location(com.maxmind.geoip2.record.Location) Test(org.junit.jupiter.api.Test)

Example 9 with Location

use of com.maxmind.geoip2.record.Location in project graylog2-server by Graylog2.

the class MaxMindIpLocationResolver method doGetGeoIpData.

@Override
public Optional<GeoLocationInformation> doGetGeoIpData(InetAddress address) {
    GeoLocationInformation info;
    try (Timer.Context ignored = resolveTime.time()) {
        final CityResponse response = databaseReader.city(address);
        final Location location = response.getLocation();
        final Country country = response.getCountry();
        final City city = response.getCity();
        info = GeoLocationInformation.create(location.getLatitude(), location.getLongitude(), country.getGeoNameId() == null ? "N/A" : country.getIsoCode(), country.getGeoNameId() == null ? "N/A" : country.getName(), // calling to .getName() may throw a NPE
        city.getGeoNameId() == null ? "N/A" : city.getName(), "N/A", "N/A");
    } catch (IOException | GeoIp2Exception | UnsupportedOperationException e) {
        info = null;
        if (!(e instanceof AddressNotFoundException)) {
            LOG.debug("Could not get location from IP {}", address.getHostAddress(), e);
            lastError = e.getMessage();
        }
    }
    return Optional.ofNullable(info);
}
Also used : CityResponse(com.maxmind.geoip2.model.CityResponse) Timer(com.codahale.metrics.Timer) AddressNotFoundException(com.maxmind.geoip2.exception.AddressNotFoundException) Country(com.maxmind.geoip2.record.Country) City(com.maxmind.geoip2.record.City) IOException(java.io.IOException) GeoIp2Exception(com.maxmind.geoip2.exception.GeoIp2Exception) Location(com.maxmind.geoip2.record.Location)

Example 10 with Location

use of com.maxmind.geoip2.record.Location in project quickutil by quickutil.

the class GeoUtil method geoGpsByAmap.

/**
 * 根据经纬度查询地理信息-高德中国
 */
public static GeoDef geoGpsByAmap(double latitude, double longitude) {
    try {
        double[] delta = WGSToGCJPointer(latitude, longitude);
        String queryUrl = String.format("http://restapi.amap.com/v3/geocode/regeo?output=json&location=%s,%s&key=%s", delta[1], delta[0], amapKeyIn);
        JsonObject object = JsonUtil.toJsonObject(FileUtil.stream2string(HttpUtil.httpGet(queryUrl).getEntity().getContent()));
        String country = object.getAsJsonObject("regeocode").getAsJsonObject("addressComponent").get("country").getAsString();
        if (country.equals("中国")) {
            country = "China";
        }
        if (country.equals("England")) {
            country = "United Kingdom";
        }
        String city = "";
        if (!object.getAsJsonObject("regeocode").getAsJsonObject("addressComponent").get("city").isJsonArray()) {
            city = object.getAsJsonObject("regeocode").getAsJsonObject("addressComponent").get("city").getAsString();
        }
        String description = object.getAsJsonObject("regeocode").get("formatted_address").getAsString();
        String countryCode = countryCodeByCountryName(country);
        String countryChinese = countryChineseByCountryCode(countryCode);
        String state = object.get("province").getAsString();
        String stateCode = "";
        if (country.equals("China")) {
            stateCode = stateCodeByStateChinese(countryCode, state);
        } else {
            stateCode = stateCodeByStateName(countryCode, state);
        }
        state = stateNameByStateCode(countryCode, stateCode);
        String stateChinese = stateChineseByStateCode(countryCode, stateCode);
        countryCode = (countryCode == null) ? UNKNOWN : countryCode;
        country = (country == null) ? UNKNOWN : country;
        countryChinese = (countryChinese == null) ? UNKNOWN : countryChinese;
        stateCode = (stateCode == null) ? UNKNOWN : stateCode;
        state = (state == null) ? UNKNOWN : state;
        stateChinese = (stateChinese == null) ? UNKNOWN : stateChinese;
        city = (city == null) ? UNKNOWN : city;
        return new GeoDef(latitude, longitude, countryCode, country, countryChinese, stateCode, state, stateChinese, city, description);
    } catch (Exception e) {
        LOGGER.error(Symbol.BLANK, e);
    }
    return null;
}
Also used : JsonObject(com.google.gson.JsonObject) GeoDef(com.quickutil.platform.entity.GeoDef) UnknownHostException(java.net.UnknownHostException) AddressNotFoundException(com.maxmind.geoip2.exception.AddressNotFoundException)

Aggregations

CityResponse (com.maxmind.geoip2.model.CityResponse)12 AddressNotFoundException (com.maxmind.geoip2.exception.AddressNotFoundException)11 Location (com.maxmind.geoip2.record.Location)10 Country (com.maxmind.geoip2.record.Country)9 UnknownHostException (java.net.UnknownHostException)8 City (com.maxmind.geoip2.record.City)7 JsonObject (com.google.gson.JsonObject)6 Continent (com.maxmind.geoip2.record.Continent)6 IOException (java.io.IOException)6 HashMap (java.util.HashMap)6 Postal (com.maxmind.geoip2.record.Postal)5 Subdivision (com.maxmind.geoip2.record.Subdivision)5 GeoIp2Exception (com.maxmind.geoip2.exception.GeoIp2Exception)4 RepresentedCountry (com.maxmind.geoip2.record.RepresentedCountry)4 InetAddress (java.net.InetAddress)4 CountryResponse (com.maxmind.geoip2.model.CountryResponse)3 Traits (com.maxmind.geoip2.record.Traits)3 GeoDef (com.quickutil.platform.def.GeoDef)3 GeoDef (com.quickutil.platform.entity.GeoDef)3 JsonArray (com.google.gson.JsonArray)2