use of com.maxmind.geoip2.DatabaseReader in project quickutil by quickutil.
the class GeoUtil method init.
public static void init(String baiduKey, String amapKey) {
try {
// 读取IP库
baiduKeyIn = baiduKey;
amapKeyIn = amapKey;
String mmdbPath = FileUtil.getCurrentPath() + "/GeoIP2-City.mmdb";
File mmdbFile = new File(mmdbPath);
if (!mmdbFile.exists()) {
HttpResponse response = HttpUtil.httpGet("http://quickutil.oss-cn-shenzhen.aliyuncs.com/GeoIP2-City.mmdb");
byte[] mmdb = FileUtil.stream2byte(response.getEntity().getContent());
if (mmdb != null)
FileUtil.byte2File(mmdbPath, mmdb);
mmdbFile = new File(mmdbPath);
}
databaseReader = new DatabaseReader.Builder(mmdbFile).build();
// 读取国家地区库
String countryStatePath = FileUtil.getCurrentPath() + "/country_state.json";
File countryStateFile = new File(countryStatePath);
if (!countryStateFile.exists()) {
HttpResponse response = HttpUtil.httpGet("http://quickutil.oss-cn-shenzhen.aliyuncs.com/country_state.json");
byte[] countryState = FileUtil.stream2byte(response.getEntity().getContent());
if (countryState != null)
FileUtil.byte2File(countryStatePath, countryState);
}
// 生成缓存
List<Map<String, Object>> list = JsonUtil.toList(FileUtil.file2String(countryStatePath));
for (Map<String, Object> map : list) {
countryCodeByCountryNameMap.put((String) map.get("country_name"), (String) map.get("country_code"));
countryChineseByCountryCodeMap.put((String) map.get("country_code"), (String) map.get("country_chinese"));
stateNameByStateCodeMap.put((String) map.get("country_code") + "_" + (String) map.get("state_code"), (String) map.get("state_name"));
stateChineseByStateCodeMap.put((String) map.get("country_code") + "_" + (String) map.get("state_code"), (String) map.get("state_chinese"));
stateCodeByStateNameMap.put((String) map.get("country_code") + "_" + (String) map.get("state_name"), (String) map.get("state_code"));
stateCodeByStateNameChineseMap.put((String) map.get("country_code") + "_" + (String) map.get("state_chinese"), (String) map.get("state_code"));
}
System.out.println("GeoUtil loaded successfully");
} catch (Exception e) {
e.printStackTrace();
}
}
use of com.maxmind.geoip2.DatabaseReader in project nifi by apache.
the class GeoEnrichIP method onTrigger.
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
FlowFile flowFile = session.get();
if (flowFile == null) {
return;
}
final DatabaseReader dbReader = databaseReaderRef.get();
final String ipAttributeName = context.getProperty(IP_ADDRESS_ATTRIBUTE).evaluateAttributeExpressions(flowFile).getValue();
final String ipAttributeValue = flowFile.getAttribute(ipAttributeName);
if (StringUtils.isEmpty(ipAttributeName)) {
session.transfer(flowFile, REL_NOT_FOUND);
getLogger().warn("FlowFile '{}' attribute '{}' was empty. Routing to failure", new Object[] { flowFile, IP_ADDRESS_ATTRIBUTE.getDisplayName() });
return;
}
InetAddress inetAddress = null;
CityResponse response = null;
try {
inetAddress = InetAddress.getByName(ipAttributeValue);
} catch (final IOException ioe) {
session.transfer(flowFile, REL_NOT_FOUND);
getLogger().warn("Could not resolve the IP for value '{}', contained within the attribute '{}' in " + "FlowFile '{}'. This is usually caused by issue resolving the appropriate DNS record or " + "providing the processor with an invalid IP address ", new Object[] { ipAttributeValue, IP_ADDRESS_ATTRIBUTE.getDisplayName(), flowFile }, ioe);
return;
}
final StopWatch stopWatch = new StopWatch(true);
try {
response = dbReader.city(inetAddress);
stopWatch.stop();
} catch (final IOException | GeoIp2Exception ex) {
// Note IOException is captured again as dbReader also makes InetAddress.getByName() calls.
// Most name or IP resolutions failure should have been triggered in the try loop above but
// environmental conditions may trigger errors during the second resolution as well.
session.transfer(flowFile, REL_NOT_FOUND);
getLogger().warn("Failure while trying to find enrichment data for {} due to {}", new Object[] { flowFile, ex }, ex);
return;
}
if (response == null) {
session.transfer(flowFile, REL_NOT_FOUND);
return;
}
final Map<String, String> attrs = new HashMap<>();
attrs.put(new StringBuilder(ipAttributeName).append(".geo.lookup.micros").toString(), String.valueOf(stopWatch.getDuration(TimeUnit.MICROSECONDS)));
attrs.put(new StringBuilder(ipAttributeName).append(".geo.city").toString(), response.getCity().getName());
final Double latitude = response.getLocation().getLatitude();
if (latitude != null) {
attrs.put(new StringBuilder(ipAttributeName).append(".geo.latitude").toString(), latitude.toString());
}
final Double longitude = response.getLocation().getLongitude();
if (longitude != null) {
attrs.put(new StringBuilder(ipAttributeName).append(".geo.longitude").toString(), longitude.toString());
}
final Integer accuracy = response.getLocation().getAccuracyRadius();
if (accuracy != null) {
attrs.put(new StringBuilder(ipAttributeName).append(".accuracy").toString(), String.valueOf(accuracy));
}
int i = 0;
for (final Subdivision subd : response.getSubdivisions()) {
attrs.put(new StringBuilder(ipAttributeName).append(".geo.subdivision.").append(i).toString(), subd.getName());
attrs.put(new StringBuilder(ipAttributeName).append(".geo.subdivision.isocode.").append(i).toString(), subd.getIsoCode());
i++;
}
attrs.put(new StringBuilder(ipAttributeName).append(".geo.country").toString(), response.getCountry().getName());
attrs.put(new StringBuilder(ipAttributeName).append(".geo.country.isocode").toString(), response.getCountry().getIsoCode());
attrs.put(new StringBuilder(ipAttributeName).append(".geo.postalcode").toString(), response.getPostal().getCode());
flowFile = session.putAllAttributes(flowFile, attrs);
session.transfer(flowFile, REL_FOUND);
}
use of com.maxmind.geoip2.DatabaseReader in project nifi by apache.
the class ISPEnrichIP method onTrigger.
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
FlowFile flowFile = session.get();
if (flowFile == null) {
return;
}
final DatabaseReader dbReader = databaseReaderRef.get();
final String ipAttributeName = context.getProperty(IP_ADDRESS_ATTRIBUTE).evaluateAttributeExpressions(flowFile).getValue();
final String ipAttributeValue = flowFile.getAttribute(ipAttributeName);
if (StringUtils.isEmpty(ipAttributeName)) {
session.transfer(flowFile, REL_NOT_FOUND);
getLogger().warn("FlowFile '{}' attribute '{}' was empty. Routing to failure", new Object[] { flowFile, IP_ADDRESS_ATTRIBUTE.getDisplayName() });
return;
}
InetAddress inetAddress = null;
IspResponse response = null;
try {
inetAddress = InetAddress.getByName(ipAttributeValue);
} catch (final IOException ioe) {
session.transfer(flowFile, REL_NOT_FOUND);
getLogger().warn("Could not resolve the IP for value '{}', contained within the attribute '{}' in " + "FlowFile '{}'. This is usually caused by issue resolving the appropriate DNS record or " + "providing the processor with an invalid IP address ", new Object[] { ipAttributeValue, IP_ADDRESS_ATTRIBUTE.getDisplayName(), flowFile }, ioe);
return;
}
final StopWatch stopWatch = new StopWatch(true);
try {
response = dbReader.isp(inetAddress);
stopWatch.stop();
} catch (final IOException | GeoIp2Exception ex) {
// Note IOException is captured again as dbReader also makes InetAddress.getByName() calls.
// Most name or IP resolutions failure should have been triggered in the try loop above but
// environmental conditions may trigger errors during the second resolution as well.
session.transfer(flowFile, REL_NOT_FOUND);
getLogger().warn("Failure while trying to find enrichment data for {} due to {}", new Object[] { flowFile, ex }, ex);
return;
}
if (response == null) {
session.transfer(flowFile, REL_NOT_FOUND);
return;
}
final Map<String, String> attrs = new HashMap<>();
attrs.put(new StringBuilder(ipAttributeName).append(".isp.lookup.micros").toString(), String.valueOf(stopWatch.getDuration(TimeUnit.MICROSECONDS)));
// seem like good option to "final int asn ..." as with the other returned data.
if (!(response.getAutonomousSystemNumber() == null)) {
attrs.put(new StringBuilder(ipAttributeName).append(".isp.asn").toString(), String.valueOf(response.getAutonomousSystemNumber()));
}
final String asnOrg = response.getAutonomousSystemOrganization();
if (asnOrg != null) {
attrs.put(new StringBuilder(ipAttributeName).append(".isp.asn.organization").toString(), asnOrg);
}
final String ispName = response.getIsp();
if (ispName != null) {
attrs.put(new StringBuilder(ipAttributeName).append(".isp.name").toString(), ispName);
}
final String organisation = response.getOrganization();
if (organisation != null) {
attrs.put(new StringBuilder(ipAttributeName).append(".isp.organization").toString(), organisation);
}
flowFile = session.putAllAttributes(flowFile, attrs);
session.transfer(flowFile, REL_FOUND);
}
use of com.maxmind.geoip2.DatabaseReader in project nifi by apache.
the class IPLookupService method doLookup.
private Optional<Record> doLookup(final DatabaseReader databaseReader, final Map<String, Object> coordinates) throws LookupFailureException, InvalidDatabaseException {
if (coordinates.get(IP_KEY) == null) {
return Optional.empty();
}
final String ipAddress = coordinates.get(IP_KEY).toString();
final InetAddress inetAddress;
try {
inetAddress = InetAddress.getByName(ipAddress);
} catch (final IOException ioe) {
getLogger().warn("Could not resolve the IP for value '{}'. This is usually caused by issue resolving the appropriate DNS record or " + "providing the service with an invalid IP address", new Object[] { coordinates }, ioe);
return Optional.empty();
}
final Record geoRecord;
if (getProperty(LOOKUP_CITY).asBoolean()) {
final CityResponse cityResponse;
try {
cityResponse = databaseReader.city(inetAddress);
} catch (final InvalidDatabaseException idbe) {
throw idbe;
} catch (final Exception e) {
throw new LookupFailureException("Failed to lookup City information for IP Address " + inetAddress, e);
}
geoRecord = createRecord(cityResponse);
} else {
geoRecord = null;
}
final Record ispRecord;
if (getProperty(LOOKUP_ISP).asBoolean()) {
final IspResponse ispResponse;
try {
ispResponse = databaseReader.isp(inetAddress);
} catch (final InvalidDatabaseException idbe) {
throw idbe;
} catch (final Exception e) {
throw new LookupFailureException("Failed to lookup ISP information for IP Address " + inetAddress, e);
}
ispRecord = createRecord(ispResponse);
} else {
ispRecord = null;
}
final String domainName;
if (getProperty(LOOKUP_DOMAIN).asBoolean()) {
final DomainResponse domainResponse;
try {
domainResponse = databaseReader.domain(inetAddress);
} catch (final InvalidDatabaseException idbe) {
throw idbe;
} catch (final Exception e) {
throw new LookupFailureException("Failed to lookup Domain information for IP Address " + inetAddress, e);
}
domainName = domainResponse == null ? null : domainResponse.getDomain();
} else {
domainName = null;
}
final String connectionType;
if (getProperty(LOOKUP_CONNECTION_TYPE).asBoolean()) {
final ConnectionTypeResponse connectionTypeResponse;
try {
connectionTypeResponse = databaseReader.connectionType(inetAddress);
} catch (final InvalidDatabaseException idbe) {
throw idbe;
} catch (final Exception e) {
throw new LookupFailureException("Failed to lookup Domain information for IP Address " + inetAddress, e);
}
if (connectionTypeResponse == null) {
connectionType = null;
} else {
final ConnectionType type = connectionTypeResponse.getConnectionType();
connectionType = type == null ? null : type.name();
}
} else {
connectionType = null;
}
final Record anonymousIpRecord;
if (getProperty(LOOKUP_ANONYMOUS_IP_INFO).asBoolean()) {
final AnonymousIpResponse anonymousIpResponse;
try {
anonymousIpResponse = databaseReader.anonymousIp(inetAddress);
} catch (final InvalidDatabaseException idbe) {
throw idbe;
} catch (final Exception e) {
throw new LookupFailureException("Failed to lookup Anonymous IP Information for IP Address " + inetAddress, e);
}
anonymousIpRecord = createRecord(anonymousIpResponse);
} else {
anonymousIpRecord = null;
}
if (geoRecord == null && ispRecord == null && domainName == null && connectionType == null && anonymousIpRecord == null) {
return Optional.empty();
}
return Optional.ofNullable(createContainerRecord(geoRecord, ispRecord, domainName, connectionType, anonymousIpRecord));
}
use of com.maxmind.geoip2.DatabaseReader in project nutch by apache.
the class GeoIPDocumentCreator method createDocFromConnectionDb.
public static NutchDocument createDocFromConnectionDb(String serverIp, NutchDocument doc, DatabaseReader reader) throws UnknownHostException, IOException, GeoIp2Exception {
ConnectionTypeResponse response = reader.connectionType(InetAddress.getByName(serverIp));
doc.add("ip", serverIp);
doc.add("connType", response.getConnectionType().toString());
return doc;
}
Aggregations