@VisibleForTesting Optional<GeoLocationInformation> extractGeoLocationInformation(Object fieldValue) { final InetAddress ipAddress; if (fieldValue instanceof InetAddress) { ipAddress = (InetAddress) fieldValue; } else if (fieldValue instanceof String) { ipAddress = getIpFromFieldValue((String) fieldValue); } else { ipAddress = null; } GeoLocationInformation geoLocationInformation = null; if (ipAddress != null) { try (Timer.Context ignored = resolveTime.time()) { final CityResponse response = databaseReader.city(ipAddress); final Location location = response.getLocation(); final Country country = response.getCountry(); final City city = response.getCity(); geoLocationInformation = GeoLocationInformation.create( location.getLatitude(), location.getLongitude(), country.getGeoNameId() != null ? country.getIsoCode() : "N/A", city.getGeoNameId() != null ? city.getName() : "N/A" // calling to .getName() may throw a NPE ); } catch (Exception e) { LOG.debug("Could not get location from IP {}", ipAddress.getHostAddress(), e); } } return Optional.ofNullable(geoLocationInformation); }
case MAXMIND_CITY: try { final CityResponse city = reader.city(addr); if (city == null) { LOG.debug("No city data for IP address {}, returning empty result.", addr); final CountryResponse countryResponse = reader.country(addr); if (countryResponse == null) { LOG.debug("No country data for IP address {}, returning empty result.", addr);
private DatabaseReader openGeoIpDb(File geoDb) { try { DatabaseReader reader = new DatabaseReader(geoDb); LOG.info("Using geo ip database at [%s].", geoDb); return reader; } catch (IOException e) { throw new RuntimeException("Could not open geo db at [" + geoDb.getAbsolutePath() + "].", e); } }
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()); CountryResponse response = reader.country(ipInfo); if(response == null) { throw event.buildException("Country not found for " + ipInfo.toString()); throw event.buildException("Unknown database type: " + reader.getMetadata().getDatabaseType());
CityResponse cityResponse = databaseReader.city(InetAddress.getByName(remoteAddr)); session.setProperty("sessionAdminSubDiv2", cityResponse.getSubdivisions().get(1).getGeoNameId()); String isp = databaseReader.isp(InetAddress.getByName(remoteAddr)).getIsp(); if (isp != null) { session.setProperty("sessionIsp", isp);
public static void main(String[] args) throws Exception { if (args.length != 2) { System.err.println("Usage: DatabaseReader geoip2-file.mmdb ip"); System.exit(1); } File f = new File(args[0]); Builder b = new Builder(f); b.withCache(new CHMCache(256)); DatabaseReader r = b.build(); System.out.println("Database Metadata: " + r.getMetadata()); String c = r.country(args[1]); System.out.println("IP: " + args[1] + " country: " + c); } }
.withCache(new CHMCache()).build()) { CountryResponse response = reader.country(InetAddress.getByName(rp.getRemoteAddr())); Country country = response.getCountry(); rp.setRemoteAddrLocale(new Locale("", country.getIsoCode()));
String ipv4 = toV4(ipl); String uc = dbr.country(ipv4); if (uc != null) { String lc = uc.toLowerCase(Locale.US); String ipv6 = toV6(ipl); String uc = dbr.country(ipv6); if (uc != null) { String lc = uc.toLowerCase(Locale.US); if (dbr != null) try { dbr.close(); } catch (IOException ioe) {} _lock.set(false);
@Override protected void doStop() throws Exception { final DatabaseReader databaseReader = this.databaseReader.get(); if (databaseReader != null) { databaseReader.close(); } }
private void setIsp(InetAddress address, GenericRecord properties) { IspResponse isp; try { isp = ispLookup.isp(address); } catch (AddressNotFoundException e) { return; } catch (Exception e) { LOGGER.error(e, "Error while searching for location information."); return; } put(properties,"_isp", isp.getIsp()); }
/** * @param ipAddress IPv4 or IPv6 address to lookup. * @return A <T> object with the data for the IP address * @throws IOException if there is an error opening or reading from the file. * @throws AddressNotFoundException if the IP address is not in our database */ private <T> T get(InetAddress ipAddress, Class<T> cls, String type) throws IOException, AddressNotFoundException { String databaseType = this.getMetadata().getDatabaseType(); if (!databaseType.contains(type)) { String caller = Thread.currentThread().getStackTrace()[2] .getMethodName(); throw new UnsupportedOperationException( "Invalid attempt to open a " + databaseType + " database using the " + caller + " method"); } ObjectNode node = jsonNodeToObjectNode(reader.get(ipAddress)); // We throw the same exception as the web service when an IP is not in // the database if (node == null) { throw new AddressNotFoundException("The address " + ipAddress.getHostAddress() + " is not in the database."); } InjectableValues inject = new JsonInjector(locales, ipAddress.getHostAddress()); return this.om.reader(inject).treeToValue(node, cls); }
String type) throws IOException { String databaseType = this.getMetadata().getDatabaseType(); if (!databaseType.contains(type)) { String caller = Thread.currentThread().getStackTrace()[2]
public void dissect(final Parsable<?> parsable, final String inputname, final InetAddress ipAddress) throws DissectionFailure { CountryResponse response; try { response = reader.country(ipAddress); } catch (IOException | GeoIp2Exception e) { return; } extractCountryFields(parsable, inputname, response); }
@Override protected void doRefresh(LookupCachePurge cachePurge) throws Exception { try { final FileInfo.Change databaseFileCheck = fileInfo.checkForChange(); if (!databaseFileCheck.isChanged() && !getError().isPresent()) { return; } // file has different attributes, let's reload it LOG.debug("MaxMind database file has changed, reloading it from {}", config.path()); final DatabaseReader oldReader = this.databaseReader.get(); try { this.databaseReader.set(loadReader(Paths.get(config.path()).toFile())); cachePurge.purgeAll(); if (oldReader != null) { oldReader.close(); } fileInfo = databaseFileCheck.fileInfo(); clearError(); } catch (IOException e) { LOG.warn("Unable to load changed database file, leaving old one intact. Error message: {}", e.getMessage()); setError(e); } } catch (IllegalArgumentException iae) { LOG.error("Unable to refresh MaxMind database file: {}", iae.getMessage()); setError(iae); } }
public boolean contains(String key) { try { InetAddress ip = InetAddress.getByName(key); IspResponse r = reader.isp(ip); String test = r.getIsp().toLowerCase(); if (test.contains("hosting")) { return false; } } catch (Exception error) { error.printStackTrace(); } return true; }
/** * @param ipAddress IPv4 or IPv6 address to lookup. * @return A <T> object with the data for the IP address * @throws IOException if there is an error opening or reading from the file. * @throws AddressNotFoundException if the IP address is not in our database */ private <T> T get(InetAddress ipAddress, Class<T> cls, String type) throws IOException, AddressNotFoundException { String databaseType = this.getMetadata().getDatabaseType(); if (!databaseType.contains(type)) { String caller = Thread.currentThread().getStackTrace()[2] .getMethodName(); throw new UnsupportedOperationException( "Invalid attempt to open a " + databaseType + " database using the " + caller + " method"); } ObjectNode node = jsonNodeToObjectNode(reader.get(ipAddress)); // We throw the same exception as the web service when an IP is not in // the database if (node == null) { throw new AddressNotFoundException("The address " + ipAddress.getHostAddress() + " is not in the database."); } InjectableValues inject = new JsonInjector(locales, ipAddress.getHostAddress()); return this.om.reader(inject).treeToValue(node, cls); }
/** * Open a GeoIP2 database * @since 0.9.38 */ private DatabaseReader openGeoIP2(File geoFile) throws IOException { DatabaseReader.Builder b = new DatabaseReader.Builder(geoFile); b.withCache(new CHMCache(256)); DatabaseReader rv = b.build(); if (_log.shouldDebug()) _log.debug("Opened GeoIP2 Database, Metadata: " + rv.getMetadata()); return rv; }
CityResponse response = reader.city(InetAddress.getByName(ipAddress));
private Map<String, Object> ip2SpatialData(InetAddress ip) { if (!enabled) { return null; } if (reader == null) { LOG.warn("Location database is not initialized. Exiting."); return null; } try { Map<String, Object> holder = new HashMap<>(3); if (dbType == LocationDatabaseType.COUNTRY) { Country country = reader.country(ip).getCountry(); holder.put(ObjectEsParameterFactory.GEOLOC_COUNTRY_CODE.getName(), country.getIsoCode()); } else { CityResponse city = reader.city(ip); Location loc = city.getLocation(); holder.put(ObjectEsParameterFactory.GEOLOC_COUNTRY_CODE.getName(), city.getCountry().getIsoCode()); holder.put(ObjectEsParameterFactory.GEOLOC_CITY_NAME.getName(), city.getCity().getName()); holder.put(ObjectEsParameterFactory.GEOLOC_GEO_POINT.getName(), new GeoPoint(loc.getLatitude(), loc.getLongitude())); } return holder; } catch (Throwable e) { LOG.warn("Can't convert IP to GeoIp", e); } return null; }
public Optional<Country> getCountry(String ipAddress) { if (reader != null) { try { CountryResponse country = reader.country(InetAddress.getByName(ipAddress)); if (country != null) return Optional.of(country.getCountry()); } catch (AddressNotFoundException | UnknownHostException ex) { LOGGER.debug("Error geo-locating country.", ex); } catch (Exception ex) { LOGGER.error("Error geo-locating country.", ex); } } return Optional.empty(); } }