Search in sources :

Example 1 with Country

use of com.maxmind.geoip2.record.Country in project elasticsearch by elastic.

the class GeoIpProcessor method retrieveCityGeoData.

private Map<String, Object> retrieveCityGeoData(InetAddress ipAddress) {
    SpecialPermission.check();
    CityResponse response = AccessController.doPrivileged((PrivilegedAction<CityResponse>) () -> {
        try {
            return dbReader.city(ipAddress);
        } catch (AddressNotFoundException e) {
            throw new AddressNotFoundRuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    });
    Country country = response.getCountry();
    City city = response.getCity();
    Location location = response.getLocation();
    Continent continent = response.getContinent();
    Subdivision subdivision = response.getMostSpecificSubdivision();
    Map<String, Object> geoData = new HashMap<>();
    for (Property property : this.properties) {
        switch(property) {
            case IP:
                geoData.put("ip", NetworkAddress.format(ipAddress));
                break;
            case COUNTRY_ISO_CODE:
                String countryIsoCode = country.getIsoCode();
                if (countryIsoCode != null) {
                    geoData.put("country_iso_code", countryIsoCode);
                }
                break;
            case COUNTRY_NAME:
                String countryName = country.getName();
                if (countryName != null) {
                    geoData.put("country_name", countryName);
                }
                break;
            case CONTINENT_NAME:
                String continentName = continent.getName();
                if (continentName != null) {
                    geoData.put("continent_name", continentName);
                }
                break;
            case REGION_NAME:
                String subdivisionName = subdivision.getName();
                if (subdivisionName != null) {
                    geoData.put("region_name", subdivisionName);
                }
                break;
            case CITY_NAME:
                String cityName = city.getName();
                if (cityName != null) {
                    geoData.put("city_name", cityName);
                }
                break;
            case TIMEZONE:
                String locationTimeZone = location.getTimeZone();
                if (locationTimeZone != null) {
                    geoData.put("timezone", locationTimeZone);
                }
                break;
            case LOCATION:
                Double latitude = location.getLatitude();
                Double longitude = location.getLongitude();
                if (latitude != null && longitude != null) {
                    Map<String, Object> locationObject = new HashMap<>();
                    locationObject.put("lat", latitude);
                    locationObject.put("lon", longitude);
                    geoData.put("location", locationObject);
                }
                break;
        }
    }
    return geoData;
}
Also used : HashMap(java.util.HashMap) City(com.maxmind.geoip2.record.City) Subdivision(com.maxmind.geoip2.record.Subdivision) ConfigurationUtils.newConfigurationException(org.elasticsearch.ingest.ConfigurationUtils.newConfigurationException) IOException(java.io.IOException) AddressNotFoundException(com.maxmind.geoip2.exception.AddressNotFoundException) ElasticsearchParseException(org.elasticsearch.ElasticsearchParseException) CityResponse(com.maxmind.geoip2.model.CityResponse) Continent(com.maxmind.geoip2.record.Continent) AddressNotFoundException(com.maxmind.geoip2.exception.AddressNotFoundException) Country(com.maxmind.geoip2.record.Country) ConfigurationUtils.readStringProperty(org.elasticsearch.ingest.ConfigurationUtils.readStringProperty) ConfigurationUtils.readBooleanProperty(org.elasticsearch.ingest.ConfigurationUtils.readBooleanProperty) Location(com.maxmind.geoip2.record.Location)

Example 2 with Country

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

the class GeoUtil method geoCodeyByBaidu.

/**
 * 根据经纬度查询地理信息-百度世界
 *
 * @param latitude-纬度
 * @param longitude-经度
 * @return
 */
public static GeoDef geoCodeyByBaidu(double latitude, double longitude) {
    try {
        double[] delta = WGSToGCJPointer(latitude, longitude);
        delta = GCJToBDPointer(delta[0], delta[1]);
        String queryUrl = String.format("http://api.map.baidu.com/geocoder/v2/?ak=%s&location=%s,%s&output=json", baiduKeyIn, delta[0], delta[1]);
        JsonObject object = JsonUtil.toJsonMap(FileUtil.stream2string(HttpUtil.httpGet(queryUrl).getEntity().getContent()));
        String country = object.getAsJsonObject("result").getAsJsonObject("addressComponent").get("country").getAsString();
        if (country.equals("中国"))
            country = "China";
        if (country.equals("England"))
            country = "United Kingdom";
        String countryCode = countryCodeByCountryName(country);
        String countryChinese = countryChineseByCountryCode(countryCode);
        String state = object.getAsJsonObject("result").getAsJsonObject("addressComponent").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);
        String city = object.getAsJsonObject("result").getAsJsonObject("addressComponent").get("city").getAsString();
        String description = object.getAsJsonObject("result").getAsJsonObject("addressComponent").get("district").getAsString();
        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) {
        e.printStackTrace();
    }
    return null;
}
Also used : JsonObject(com.google.gson.JsonObject) GeoDef(com.quickutil.platform.def.GeoDef) UnknownHostException(java.net.UnknownHostException) AddressNotFoundException(com.maxmind.geoip2.exception.AddressNotFoundException)

Example 3 with Country

use of com.maxmind.geoip2.record.Country in project JFramework by gugumall.

the class I18N method changeLanguage.

/**
 * @param httpRequest
 * @param session
 */
public static void changeLanguage(HttpServletRequest httpRequest, HttpSession session) {
    // 请求改变系统语言的参数
    String language = httpRequest.getParameter(Constants.I18N_LANGUAGE);
    if (language == null || !I18N.languages.containsKey(language)) {
        if (cookieEnabled)
            language = SysUtil.getCookie(httpRequest, Constants.I18N_LANGUAGE);
    }
    // 保存在session中的当前系统语言对象
    Object languageObj = session.getAttribute(Constants.I18N_LANGUAGE);
    if (language == null || !I18N.languages.containsKey(language)) {
        // 不是初次访问
        if (languageObj != null)
            return;
        // 初次访问,根据国家确定语言
        String ip = IP.getRemoteIp(httpRequest);
        CountryResponse country = IP.geoIpGetCountry(ip);
        if (country == null || country.getCountry() == null || country.getCountry().getIsoCode() == null) {
            // 未获得国家数据,使用默认语言
            return;
        }
        List langs = languages.listValues();
        for (int i = 0; i < langs.size(); i++) {
            Language lang = (Language) langs.get(i);
            if (lang.matches(country.getCountry().getIsoCode())) {
                language = lang.getCode();
                break;
            }
        }
        if (language == null) {
            // 未匹配多国家,使用默认语言
            return;
        }
    }
    /**
     * 如果系统使用的当前语言为空,则设置为默认语言
     */
    if (language != null && I18N.languages.containsKey(language)) {
        session.setAttribute(Constants.I18N_LANGUAGE, language);
    } else if (languageObj == null) {
        session.setAttribute(Constants.I18N_LANGUAGE, I18N.defaultLanguage);
    }
}
Also used : CountryResponse(com.maxmind.geoip2.model.CountryResponse) LinkedList(java.util.LinkedList) List(java.util.List) ConcurrentList(j.util.ConcurrentList)

Example 4 with Country

use of com.maxmind.geoip2.record.Country in project LogHub by fbacchella.

the class Geoip2 method processMessage.

@Override
public boolean processMessage(Event event, String field, String destination) throws ProcessorException {
    Object addr = event.get(field);
    InetAddress ipInfo = null;
    if (addr instanceof InetAddress) {
        ipInfo = (InetAddress) addr;
    } else if (addr instanceof String) {
        try {
            ipInfo = Helpers.parseIpAddres((String) addr);
            if (ipInfo == null) {
                throw event.buildException("can't read ip address " + addr);
            }
        } catch (UnknownHostException e) {
            throw event.buildException("can't read ip address " + addr, e);
        }
    }
    Country country = null;
    Country registred_country = null;
    Country represented_country = null;
    City city = null;
    Continent continent = null;
    Location location = null;
    Postal postal = null;
    List<Subdivision> subdivision = null;
    Map<String, Object> informations = new HashMap<>();
    try {
        switch(reader.getMetadata().getDatabaseType()) {
            case "GeoIP2-City":
            case "GeoLite2-City":
                {
                    CityResponse response = reader.city(ipInfo);
                    if (response == null) {
                        throw event.buildException("City not found for " + ipInfo.toString());
                    }
                    country = response.getCountry();
                    city = response.getCity();
                    continent = response.getContinent();
                    location = response.getLocation();
                    postal = response.getPostal();
                    registred_country = response.getRegisteredCountry();
                    represented_country = response.getRepresentedCountry();
                    subdivision = response.getSubdivisions();
                    break;
                }
            case "GeoIP2-Country":
            case "GeoLite2-Country":
                {
                    CountryResponse response = reader.country(ipInfo);
                    if (response == null) {
                        throw event.buildException("Country not found for " + ipInfo.toString());
                    }
                    country = response.getCountry();
                    continent = response.getContinent();
                    registred_country = response.getRegisteredCountry();
                    represented_country = response.getRepresentedCountry();
                    break;
                }
        }
    } catch (AddressNotFoundException e) {
        // not an error, just return a failure
        return false;
    } catch (IOException | GeoIp2Exception e) {
        throw event.buildException("can't read geoip database", e);
    }
    for (LocationType type : types) {
        switch(type) {
            case COUNTRY:
                if (country != null) {
                    Map<String, Object> infos = new HashMap<>(2);
                    Helpers.putNotEmpty(infos, "code", country.getIsoCode());
                    Helpers.putNotEmpty(infos, "name", country.getNames().get(locale));
                    if (infos.size() > 0) {
                        informations.put("country", infos);
                    }
                }
                break;
            case REPRESENTEDCOUNTRY:
                if (represented_country != null) {
                    Map<String, Object> infos = new HashMap<>(2);
                    Helpers.putNotEmpty(infos, "code", represented_country.getIsoCode());
                    Helpers.putNotEmpty(infos, "name", represented_country.getNames().get(locale));
                    if (infos.size() > 0) {
                        informations.put("represented_country", infos);
                    }
                }
                break;
            case REGISTREDCOUNTRY:
                if (registred_country != null) {
                    Map<String, Object> infos = new HashMap<>(2);
                    Helpers.putNotEmpty(infos, "code", registred_country.getIsoCode());
                    Helpers.putNotEmpty(infos, "name", registred_country.getNames().get(locale));
                    if (infos.size() > 0) {
                        informations.put("registred_country", infos);
                    }
                }
                break;
            case CITY:
                {
                    if (city != null) {
                        Helpers.putNotEmpty(informations, "city", city.getNames().get(locale));
                    }
                    break;
                }
            case LOCATION:
                Map<String, Object> infos = new HashMap<>(10);
                if (location != null) {
                    Helpers.putNotEmpty(infos, "latitude", location.getLatitude());
                    Helpers.putNotEmpty(infos, "longitude", location.getLongitude());
                    Helpers.putNotEmpty(infos, "timezone", location.getTimeZone());
                    Helpers.putNotEmpty(infos, "accuray_radius", location.getAccuracyRadius());
                    Helpers.putNotEmpty(infos, "metro_code", location.getMetroCode());
                    Helpers.putNotEmpty(infos, "average_income", location.getAverageIncome());
                    Helpers.putNotEmpty(infos, "population_density", location.getPopulationDensity());
                    if (infos.size() > 0) {
                        informations.put("location", infos);
                    }
                }
            case CONTINENT:
                if (continent != null) {
                    Helpers.putNotEmpty(informations, "continent", continent.getNames().get(locale));
                }
                break;
            case POSTAL:
                if (postal != null) {
                    Helpers.putNotEmpty(informations, "postal", postal.getCode());
                }
                break;
            case SUBDIVISION:
                if (subdivision != null) {
                    List<Map<String, Object>> all = new ArrayList<>(subdivision.size());
                    for (Subdivision sub : subdivision) {
                        Map<String, Object> subdivisioninfo = new HashMap<>(2);
                        Helpers.putNotEmpty(subdivisioninfo, "code", sub.getIsoCode());
                        Helpers.putNotEmpty(subdivisioninfo, "name", sub.getNames().get(locale));
                        if (subdivisioninfo.size() > 0) {
                            all.add(subdivisioninfo);
                        }
                    }
                    if (all.size() > 0) {
                        informations.put("subdivisions", all);
                    }
                }
                break;
        }
    }
    event.put(destination, informations);
    return true;
}
Also used : UnknownHostException(java.net.UnknownHostException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) City(com.maxmind.geoip2.record.City) Subdivision(com.maxmind.geoip2.record.Subdivision) IOException(java.io.IOException) GeoIp2Exception(com.maxmind.geoip2.exception.GeoIp2Exception) CityResponse(com.maxmind.geoip2.model.CityResponse) Continent(com.maxmind.geoip2.record.Continent) AddressNotFoundException(com.maxmind.geoip2.exception.AddressNotFoundException) Country(com.maxmind.geoip2.record.Country) CountryResponse(com.maxmind.geoip2.model.CountryResponse) InetAddress(java.net.InetAddress) HashMap(java.util.HashMap) Map(java.util.Map) Postal(com.maxmind.geoip2.record.Postal) Location(com.maxmind.geoip2.record.Location)

Example 5 with Country

use of com.maxmind.geoip2.record.Country 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)

Aggregations

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