Java Code Examples for com.maxmind.geoip2.DatabaseReader#city()

The following examples show how to use com.maxmind.geoip2.DatabaseReader#city() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Locator.java    From FXMaps with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Returns a {@link Location} object with location information which may
 * not have very strictly accurate information.
 * 
 * @param ipStr         the IP Address for which a {@link Location} will be obtained.
 * @return
 * @throws Exception
 */
public static Location getIPLocation(String ipStr) throws Exception {
    System.out.println("gres = " + Locator.class.getClassLoader().getResource("GeoLite2-City.mmdb"));
    InputStream is = Locator.class.getClassLoader().getResourceAsStream("GeoLite2-City.mmdb");
    DatabaseReader reader = new DatabaseReader.Builder(is).build();
    CityResponse response = reader.city(InetAddress.getByName(ipStr));

    System.out.println("City " +response.getCity());
    System.out.println("ZIP Code " +response.getPostal().getCode());
    System.out.println("Country " +response.getCountry());
    System.out.println("Location " +response.getLocation());
    
    return new Location(response.getCity().toString(), response.getPostal().getCode(), 
        response.getCountry().toString(), response.getLocation().getTimeZone(), response.getLocation().getLatitude(), 
            response.getLocation().getLongitude(), response.getPostal().getConfidence(),
                response.getLocation().getAccuracyRadius(), response.getLocation().getPopulationDensity(),
                    response.getLocation().getAverageIncome());
}
 
Example 2
Source File: GeoIpIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenIP_whenFetchingCity_thenReturnsCityData() throws IOException, GeoIp2Exception {
    
    ClassLoader classLoader = getClass().getClassLoader();
    File database = new File(classLoader.getResource("GeoLite2-City.mmdb").getFile());
    DatabaseReader dbReader = new DatabaseReader.Builder(database).build();

    InetAddress ipAddress = InetAddress.getByName("google.com");
    CityResponse response = dbReader.city(ipAddress);

    String countryName = response.getCountry().getName();
    String cityName = response.getCity().getName();
    String postal = response.getPostal().getCode();
    String state = response.getLeastSpecificSubdivision().getName();

}
 
Example 3
Source File: Benchmark.java    From GeoIP2-java with Apache License 2.0 6 votes vote down vote up
private static void bench(DatabaseReader r, int count, int seed) throws GeoIp2Exception, UnknownHostException {
    Random random = new Random(seed);
    long startTime = System.nanoTime();
    byte[] address = new byte[4];
    for (int i = 0; i < count; i++) {
        random.nextBytes(address);
        InetAddress ip = InetAddress.getByAddress(address);
        CityResponse t;
        try {
            t = r.city(ip);
        } catch (AddressNotFoundException | IOException e) {
        }
        if (TRACE) {
            if (i % 50000 == 0) {
                System.out.println(i + " " + ip);
                System.out.println(t);
            }
        }
    }
    long endTime = System.nanoTime();

    long duration = endTime - startTime;
    long qps = count * 1000000000L / duration;
    System.out.println("Requests per second: " + qps);
}
 
Example 4
Source File: StreamProcessorsSession.java    From proxylive with MIT License 5 votes vote down vote up
public synchronized ClientInfo manage(IStreamProcessor iStreamProcessor, HttpServletRequest request) throws UnknownHostException {
    ClientInfo client = new ClientInfo();
    request.getQueryString();
    MultiValueMap<String, String> parameters = UriComponentsBuilder.fromUriString(ProxyLiveUtils.getURL(request)).build().getQueryParams();
    String clientUser = parameters.getFirst("user");
    if (clientUser == null || clientUser.trim().equals("null")) {
        clientUser = "guest";
    }
    client.setClientUser(clientUser);
    client.setIp(InetAddress.getByName(ProxyLiveUtils.getRequestIP(request)));
    client.setBrowserInfo(ProxyLiveUtils.getBrowserInfo(request));
    client = addClientInfo(client);
    if (geoIPService.isServiceEnabled()) {
        try {
            DatabaseReader geoDBReader = geoIPService.geoGEOInfoReader();
            CityResponse cityResponse = geoDBReader.city(client.getIp());

            if (cityResponse.getLocation() != null) {
                GEOInfo geoInfo = new GEOInfo();
                geoInfo.setCity(cityResponse.getCity());
                geoInfo.setCountry(cityResponse.getCountry());
                geoInfo.setLocation(cityResponse.getLocation());
                client.setGeoInfo(geoInfo);
            }
        }catch(AddressNotFoundException anfe){
        }catch(Exception ex ){
            logger.error("Error parsing user geodata", ex);
        }
    }
    if (!client.getStreams().contains(iStreamProcessor)) {
        client.getStreams().add(iStreamProcessor);
    }
    return client;
}
 
Example 5
Source File: MaxMind2HostGeoLookup.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
public HostGeoInfo getHostGeoInfo(InetAddress address) throws MalformedURLException, IOException {
    if (lookupFailed) return null;
    
    DatabaseReader ll = getDatabaseReader();
    if (ll==null) return null;
    
    InetAddress extAddress = address;
    if (Networking.isPrivateSubnet(extAddress)) extAddress = InetAddress.getByName(LocalhostExternalIpLoader.getLocalhostIpQuicklyOrDefault());
    
    try {
        CityResponse l = ll.city(extAddress);
        if (l==null) {
            if (log.isDebugEnabled()) log.debug("Geo info failed to find location for address {}, using {}", extAddress, ll);
            return null;
        }
        
        StringBuilder name = new StringBuilder();
        
        if (l.getCity()!=null && l.getCity().getName()!=null) name.append(l.getCity().getName());
        
        if (l.getSubdivisions()!=null) {
            for (Subdivision subd: Lists.reverse(l.getSubdivisions())) {
                if (name.length()>0) name.append(", ");
                // prefer e.g. USA state codes over state names
                if (!Strings.isBlank(subd.getIsoCode())) 
                    name.append(subd.getIsoCode());
                else
                    name.append(subd.getName());
            }
        }
        
        if (l.getCountry()!=null) {
            if (name.length()==0) {
                name.append(l.getCountry().getName());
            } else {
                name.append(" ("); name.append(l.getCountry().getIsoCode()); name.append(")");
            }
        }

        
        HostGeoInfo geo = new HostGeoInfo(address.getHostName(), name.toString(), l.getLocation().getLatitude(), l.getLocation().getLongitude());
        log.debug("Geo info lookup (MaxMind DB) for "+address+" returned: "+geo);
        return geo;
    } catch (Exception e) {
        if (log.isDebugEnabled())
            log.debug("Geo info lookup failed: "+e);
        throw Throwables.propagate(e);
    }
}