场景:
1.在安全性较高的场景中,程序部署在内网,无法通过地图api接口获取地理位置信息,如下程序通过解析json数据获取对应区域地理位置信息(注:地理位置信息精确度根据json数据详细度正相关)。
2.代码采用线程池(也可改为消息队列)异步执行经纬度转换为地理位置信息。
优点/缺点
优点:1.采用线程池,2.解决了在内网项目上地图中展示 标注(经纬度点)。
缺点:大量数据同时转化需要加锁,json地理位置数据详细度不够全面.
待改进:1.加载json地理位置数据应改为单列。2.json地理位置数据应该新建数据库表导入到表中,去数据表中查询,减少x响应速度。
//1.创建线程池 参数应该根据业务量、系统环境进行修改
private static ExecutorService executorService = new ThreadPoolExecutor(3, 10, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2048));
//2.封装转化方法 Address-业务数据对象里面有需要转化的经纬度 (这里就是举个列子 请读者自行修改)
public static void setCode(Address record,ExecutorService executorService){
if(StringUtils.notBlank(record.getLng())&&StringUtils.notBlank(record.getLat())){
executorService.execute(new Runnable() {
@Override
public void run() {
try {
Map<String, Object> position = AddressUtil.getPosition(record.getLng(), record.getLat(), null, null, null);
if(position!=null){
Map data = (Map)position.get("data");
//更新对应数据信息
//nation_name 国家名称(中国) nation_code-国家编码(我自定义的为:000000)
//province_name 省名称 province_code省编码
String provinceName=data.get("shortname").toString().replaceAll("\"","");
String provinceCode=data.get("parentid").toString();
//city_name 地市名称 city_code 地市编码
String cityName=data.get("areaname").toString().replaceAll("\"","");
String cityCode=data.get("id").toString();
//county_name 县/区域名称 county_code 县/区域编码
String countyName=((Map)data.get("county")).get("areaname").toString().replaceAll("\"","");
String countyCode=((Map)data.get("county")).get("id").toString();
//更新对应数据
......
//
}
} catch (Exception e) {
logger.error("kcode转化失败:",e);
} finally {
//不成功的业务处理
}
}
});
}
}
import com.cnksi.utils.LatAndLngUtil.IPSeeker;
import com.cnksi.utils.LatAndLngUtil.JsonUtil;
import lombok.Synchronized;
import java.util.*;
/**
* 经纬度转 地理位置(省市县)
*/
public class AddressUtil {
private static List<Map<String, Object>> list = new ArrayList();
private static Map<Integer, Map<String, Object>> map = new HashMap();
@Synchronized //lombok锁
public static Map<String, Object> getPosition(Double longitude, Double latitude, Double baseStationX, Double baseStationY, String IP)
{
Date d1 = new Date();
Map resultMap = new HashMap();
resultMap.put("code", Integer.valueOf(500));
resultMap.put("message", "失败");
Map shopAreaMap = new HashMap();
if ((longitude != null) && (latitude != null)) {
if (list.size() == 0) {
JsonUtil jsonUtil = JsonUtil.getInstance();
list = jsonUtil.readJson();
}
if (map.size() == 0) {
for (Map jsonMap : list) {
map.put(Integer.valueOf(jsonMap.get("id").toString()), jsonMap);
}
}
double num = 0.0D;
double min = 0.0D;
boolean flag=true;
for (Map areaMap : list)
{
if (!"1".equals(areaMap.get("level").toString())&&!"2".equals(areaMap.get("level").toString())&& (areaMap.get("lng") != null) && (!"".equals(areaMap.get("lng"))) && (!"null".equals(areaMap.get("lng").toString())) && (areaMap.get("lat") != null) &&
(!"".equals(areaMap.get("lat"))) && (!"null".equals(areaMap.get("lat").toString()))) {
String lng = areaMap.get("lng").toString().replace("\"", "");
String lat = areaMap.get("lat").toString().replace("\"", "");
/*num = CoordTransform.getDistance(longitude.doubleValue(), latitude.doubleValue(), Double.parseDouble(lng),
Double.parseDouble(lat)).doubleValue();*/
num = LocationUtils.getDistance(latitude,longitude, Double.parseDouble(lat), Double.parseDouble(lng));
if (min == 0.0D&&flag) {
min = num;
shopAreaMap = areaMap;
flag=false;
}else if (num < min) {
min = num;
shopAreaMap = areaMap;
}
}
}
if (shopAreaMap != null)
{
if(shopAreaMap.get("level")!=null){
int level = Integer.valueOf(shopAreaMap.get("level").toString()).intValue();
if (level == 4) {
Map parentMap = (Map)map.get(Integer.valueOf(shopAreaMap.get("parentid").toString()));
if (parentMap != null) {
Map cityMap = (Map)map.get(Integer.valueOf(parentMap.get("parentid").toString()));
if (cityMap != null)
{
shopAreaMap = cityMap;
}
shopAreaMap.put("county",parentMap);
}
}
if (level == 3) {
Map m = shopAreaMap;
Map parentMap = (Map)map.get(Integer.valueOf(shopAreaMap.get("parentid").toString()));
if (parentMap != null) {
shopAreaMap = parentMap;
}
shopAreaMap.put("county",m);
}
shopAreaMap.put("shortname", ((Map)map.get(Integer.valueOf(shopAreaMap.get("parentid").toString()))).get("areaname").toString());
}
}
resultMap.put("code", Integer.valueOf(200));
resultMap.put("message", "成功");
resultMap.put("data", shopAreaMap);
}
if ((IP != null) && (!"".equals(IP))) {
String ipInfo = IPSeeker.getAddressByCity(IP);
shopAreaMap = IPSeeker.jqCity(ipInfo);
resultMap.put("data", shopAreaMap);
resultMap.put("code", Integer.valueOf(200));
resultMap.put("message", "成功");
}
return resultMap;
}
public static void main(String[] args) {
//System.err.println(getPosition(104.391251, 31.129335, null, null, null).get("data"));
Map<String, Object> position = getPosition(103.8239234539004, 29.481175402142373, null, null, null);
Map data = (Map)position.get("data");
System.err.println("省:"+data.get("shortname"));
System.err.println("省id:"+data.get("parentid"));
System.err.println("市:"+data.get("areaname"));
System.err.println("市id:"+data.get("id"));
System.err.println("县:"+((Map)data.get("county")).get("areaname"));
System.err.println("县id:"+((Map)data.get("county")).get("id"));
/*String p="1234-9999-0909";
if(String.valueOf(p).matches("(?:[0-9]){4}-(?:[0-9]){4}-(?:[0-9]){4}")){
System.out.println("true");
}else{
System.out.println("false");
}*/
//double num = LocationUtils.getDistance(30.660275,104.103081, 30.573242, 103.922707);
//System.out.println("距离:"+num);
//System.err.println(getPosition(null, null, null, null, "219.137.148.0"));
}
}
import java.util.*;
public class AddressApi
{
private static List<Map<String, Object>> list = new ArrayList();
private static Map<Integer, Map<String, Object>> map = new HashMap();
public static Map<String, Object> getPosition(Double longitude, Double latitude, Double baseStationX, Double baseStationY, String IP)
{
Date d1 = new Date();
Map resultMap = new HashMap();
resultMap.put("code", Integer.valueOf(500));
resultMap.put("message", "失败");
Map shopAreaMap = new HashMap();
if ((longitude != null) && (latitude != null)) {
if (list.size() == 0) {
JsonUtil jsonUtil = JsonUtil.getInstance();
list = jsonUtil.readJson();
}
if (map.size() == 0) {
for (Map jsonMap : list) {
map.put(Integer.valueOf(jsonMap.get("id").toString()), jsonMap);
}
}
double num = 0.0D;
double min = 0.0D;
for (Map areaMap : list)
{
if ((areaMap.get("lng") != null) && (!"".equals(areaMap.get("lng"))) && (!"null".equals(areaMap.get("lng").toString())) && (areaMap.get("lat") != null) &&
(!"".equals(areaMap.get("lat"))) && (!"null".equals(areaMap.get("lat").toString()))) {
String lng = areaMap.get("lng").toString().replace("\"", "");
String lat = areaMap.get("lat").toString().replace("\"", "");
num = CoordTransform.getDistance(longitude.doubleValue(), latitude.doubleValue(), Double.parseDouble(lng),
Double.parseDouble(lat)).doubleValue();
if (min == 0.0D) {
min = num;
shopAreaMap = areaMap;
}
if (num <= min) {
min = num;
shopAreaMap = areaMap;
}
}
}
if (shopAreaMap != null)
{
int level = Integer.valueOf(shopAreaMap.get("level").toString()).intValue();
if (level == 4) {
Map parentMap = (Map)map.get(Integer.valueOf(shopAreaMap.get("parentid").toString()));
if (parentMap != null) {
Map cityMap = (Map)map.get(Integer.valueOf(parentMap.get("parentid").toString()));
if (cityMap != null)
{
shopAreaMap = cityMap;
}
}
}
if (level == 3) {
Map parentMap = (Map)map.get(Integer.valueOf(shopAreaMap.get("parentid").toString()));
if (parentMap != null) {
shopAreaMap = parentMap;
}
}
shopAreaMap.put("shortname", ((Map)map.get(Integer.valueOf(shopAreaMap.get("parentid").toString()))).get("areaname").toString());
}
resultMap.put("code", Integer.valueOf(200));
resultMap.put("message", "成功");
resultMap.put("data", shopAreaMap);
}
if ((IP != null) && (!"".equals(IP))) {
String ipInfo = IPSeeker.getAddressByCity(IP);
shopAreaMap = IPSeeker.jqCity(ipInfo);
resultMap.put("data", shopAreaMap);
resultMap.put("code", Integer.valueOf(200));
resultMap.put("message", "成功");
}
return resultMap;
}
public static void main(String[] args) {
System.err.println(getPosition(Double.valueOf(114.085945D), Double.valueOf(22.547001000000002D), null, null, null).get("data"));
}
}
public class CoordTransform
{
private static Double x_PI = Double.valueOf(52.359877559829883D);
private static Double PI = Double.valueOf(3.141592653589793D);
private static Double a = Double.valueOf(6378245.0D);
private static Double ee = Double.valueOf(0.006693421622965943D);
public static void main(String[] args) {
String[] s = bd09togcj02(Double.valueOf(105.090675D), Double.valueOf(29.606079000000001D)).split(",");
System.out.println(gcj02towgs84(Double.valueOf(s[0]), Double.valueOf(s[1])));
}
public static String bd09togcj02(Double bd_lon, Double bd_lat)
{
Double x = Double.valueOf(bd_lon.doubleValue() - 0.0065D);
Double y = Double.valueOf(bd_lat.doubleValue() - 0.006D);
Double z = Double.valueOf(Math.sqrt(x.doubleValue() * x.doubleValue() + y.doubleValue() * y.doubleValue()) - 2.E-005D * Math.sin(y.doubleValue() * x_PI.doubleValue()));
Double theta = Double.valueOf(Math.atan2(y.doubleValue(), x.doubleValue()) - 3.E-006D * Math.cos(x.doubleValue() * x_PI.doubleValue()));
Double gg_lng = Double.valueOf(z.doubleValue() * Math.cos(theta.doubleValue()));
Double gg_lat = Double.valueOf(z.doubleValue() * Math.sin(theta.doubleValue()));
return gg_lng + "," + gg_lat;
}
public static String gcj02tobd09(Double lng, Double lat)
{
Double z = Double.valueOf(Math.sqrt(lng.doubleValue() * lng.doubleValue() + lat.doubleValue() * lat.doubleValue()) + 2.E-005D *
Math.sin(lat.doubleValue() * x_PI.doubleValue()));
Double theta = Double.valueOf(Math.atan2(lat.doubleValue(), lng.doubleValue()) + 3.E-006D * Math.cos(lng.doubleValue() * x_PI.doubleValue()));
Double bd_lng = Double.valueOf(z.doubleValue() * Math.cos(theta.doubleValue()) + 0.0065D);
Double bd_lat = Double.valueOf(z.doubleValue() * Math.sin(theta.doubleValue()) + 0.006D);
return bd_lng + "," + bd_lat;
}
public static String wgs84togcj02(Double lng, Double lat)
{
if (out_of_china(lng, lat)) {
return null;
}
Double dlat = transformlat(Double.valueOf(lng.doubleValue() - 105.0D), Double.valueOf(lat.doubleValue() - 35.0D));
Double dlng = transformlng(Double.valueOf(lng.doubleValue() - 105.0D), Double.valueOf(lat.doubleValue() - 35.0D));
Double radlat = Double.valueOf(lat.doubleValue() / 180.0D * PI.doubleValue());
Double magic = Double.valueOf(Math.sin(radlat.doubleValue()));
magic = Double.valueOf(1.0D - ee.doubleValue() * magic.doubleValue() * magic.doubleValue());
Double sqrtmagic = Double.valueOf(Math.sqrt(magic.doubleValue()));
dlat = Double.valueOf(dlat.doubleValue() * 180.0D / (a.doubleValue() * (1.0D - ee.doubleValue()) / (magic.doubleValue() * sqrtmagic.doubleValue()) * PI.doubleValue()));
dlng = Double.valueOf(dlng.doubleValue() * 180.0D / (a.doubleValue() / sqrtmagic.doubleValue() * Math.cos(radlat.doubleValue()) * PI.doubleValue()));
Double mglat = Double.valueOf(lat.doubleValue() + dlat.doubleValue());
Double mglng = Double.valueOf(lng.doubleValue() + dlng.doubleValue());
return mglng + "," + mglat;
}
public static String gcj02towgs84(Double lng, Double lat)
{
if (out_of_china(lng, lat)) {
return null;
}
Double dlat = transformlat(Double.valueOf(lng.doubleValue() - 105.0D), Double.valueOf(lat.doubleValue() - 35.0D));
Double dlng = transformlng(Double.valueOf(lng.doubleValue() - 105.0D), Double.valueOf(lat.doubleValue() - 35.0D));
Double radlat = Double.valueOf(lat.doubleValue() / 180.0D * PI.doubleValue());
Double magic = Double.valueOf(Math.sin(radlat.doubleValue()));
magic = Double.valueOf(1.0D - ee.doubleValue() * magic.doubleValue() * magic.doubleValue());
Double sqrtmagic = Double.valueOf(Math.sqrt(magic.doubleValue()));
dlat = Double.valueOf(dlat.doubleValue() * 180.0D / (a.doubleValue() * (1.0D - ee.doubleValue()) / (magic.doubleValue() * sqrtmagic.doubleValue()) * PI.doubleValue()));
dlng = Double.valueOf(dlng.doubleValue() * 180.0D / (a.doubleValue() / sqrtmagic.doubleValue() * Math.cos(radlat.doubleValue()) * PI.doubleValue()));
Double mglat = Double.valueOf(lat.doubleValue() + dlat.doubleValue());
Double mglng = Double.valueOf(lng.doubleValue() + dlng.doubleValue());
return lng.doubleValue() * 2.0D - mglng.doubleValue() + "," + (lat.doubleValue() * 2.0D - mglat.doubleValue());
}
public static Double transformlat(Double lng, Double lat)
{
Double ret = Double.valueOf(-100.0D + 2.0D * lng.doubleValue() + 3.0D * lat.doubleValue() + 0.2D * lat.doubleValue() * lat.doubleValue() + 0.1D *
lng.doubleValue() * lat.doubleValue() + 0.2D * Math.sqrt(Math.abs(lng.doubleValue())));
ret = Double.valueOf(ret.doubleValue() + (20.0D * Math.sin(6.0D * lng.doubleValue() * PI.doubleValue()) + 20.0D * Math.sin(2.0D * lng.doubleValue() *
PI.doubleValue())) * 2.0D / 3.0D);
ret = Double.valueOf(ret.doubleValue() + (20.0D * Math.sin(lat.doubleValue() * PI.doubleValue()) + 40.0D * Math.sin(lat.doubleValue() / 3.0D * PI.doubleValue())) * 2.0D / 3.0D);
ret = Double.valueOf(ret.doubleValue() + (160.0D * Math.sin(lat.doubleValue() / 12.0D * PI.doubleValue()) + 320.0D * Math.sin(lat.doubleValue() * PI.doubleValue() /
30.0D)) * 2.0D / 3.0D);
return ret;
}
public static Double transformlng(Double lng, Double lat) {
Double ret = Double.valueOf(300.0D + lng.doubleValue() + 2.0D * lat.doubleValue() + 0.1D * lng.doubleValue() * lng.doubleValue() + 0.1D * lng.doubleValue() *
lat.doubleValue() + 0.1D * Math.sqrt(Math.abs(lng.doubleValue())));
ret = Double.valueOf(ret.doubleValue() + (20.0D * Math.sin(6.0D * lng.doubleValue() * PI.doubleValue()) + 20.0D * Math.sin(2.0D * lng.doubleValue() *
PI.doubleValue())) * 2.0D / 3.0D);
ret = Double.valueOf(ret.doubleValue() + (20.0D * Math.sin(lng.doubleValue() * PI.doubleValue()) + 40.0D * Math.sin(lng.doubleValue() / 3.0D * PI.doubleValue())) * 2.0D / 3.0D);
ret = Double.valueOf(ret.doubleValue() + (150.0D * Math.sin(lng.doubleValue() / 12.0D * PI.doubleValue()) + 300.0D * Math.sin(lng.doubleValue() / 30.0D *
PI.doubleValue())) * 2.0D / 3.0D);
return ret;
}
public static boolean out_of_china(Double lng, Double lat)
{
return (lng.doubleValue() <= 73.659999999999997D) || (lng.doubleValue() >= 135.05000000000001D) || (lat.doubleValue() <= 3.86D) || (lat.doubleValue() >= 53.549999999999997D);
}
public static Double getDistance(double x1, double y1, double x2, double y2)
{
double x = (x1 - x2) * PI.doubleValue() * a.doubleValue() *
Math.cos((y1 + y2) / 2.0D * PI.doubleValue() / 180.0D) / 180.0D;
double y = (y2 - y1) * PI.doubleValue() * a.doubleValue() / 180.0D;
return Double.valueOf(Math.sqrt(x * x + y * y));
}
}
public class IPEntry
{
public String beginIp;
public String endIp;
public String country;
public String area;
public IPEntry()
{
this.beginIp = (this.endIp = this.country = this.area = "");
}
public String toString() {
return this.area + " " + this.country + "IP范围:" + this.beginIp + "-" +
this.endIp;
}
}
public class IPSeeker
{
private static final String IP_FILE = PropertiesUtil.getProperty("IP_DATA_URL");
private static final int IP_RECORD_LENGTH = 7;
private static final byte AREA_FOLLOWED = 1;
private static final byte NO_AREA = 2;
private static Hashtable<String, Object> ipCache;
private static RandomAccessFile ipFile;
private static MappedByteBuffer mbb;
private static IPSeeker instance = new IPSeeker();
private static long ipBegin;
private static long ipEnd;
private static IPLocation loc;
private static byte[] buf;
private static byte[] b4;
private static byte[] b3;
private IPSeeker()
{
ipCache = new Hashtable();
loc = new IPLocation();
buf = new byte[100];
b4 = new byte[4];
b3 = new byte[3];
try {
ipFile = new RandomAccessFile(IP_FILE, "r");
} catch (FileNotFoundException e) {
System.out.println(IP_FILE);
System.out.println("IP地址信息文件没有找到,IP显示功能将无法使用");
ipFile = null;
}
if (ipFile != null)
try {
ipBegin = readLong4(0L);
ipEnd = readLong4(4L);
if ((ipBegin == -1L) || (ipEnd == -1L)) {
ipFile.close();
ipFile = null;
}
} catch (IOException e) {
System.out.println("IP地址信息文件格式有错误,IP显示功能将无法使用");
ipFile = null;
}
}
public static IPSeeker getInstance()
{
return instance;
}
public List<IPEntry> getIPEntriesDebug(String s)
{
List ret = new ArrayList();
long endOffset = ipEnd + 4L;
for (long offset = ipBegin + 4L; offset <= endOffset; offset += 7L)
{
long temp = readLong3(offset);
if (temp != -1L) {
IPLocation loc = getIPLocation(temp);
if ((loc.country.indexOf(s) != -1) || (loc.area.indexOf(s) != -1)) {
IPEntry entry = new IPEntry();
entry.country = loc.country;
entry.area = loc.area;
readIP(offset - 4L, b4);
entry.beginIp = Utils.getIpStringFromBytes(b4);
readIP(temp, b4);
entry.endIp = Utils.getIpStringFromBytes(b4);
ret.add(entry);
}
}
}
return ret;
}
public List<IPEntry> getIPEntries(String s)
{
List ret = new ArrayList();
try
{
if (mbb == null) {
FileChannel fc = ipFile.getChannel();
mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0L, ipFile.length());
mbb.order(ByteOrder.LITTLE_ENDIAN);
}
int endOffset = (int)ipEnd;
for (int offset = (int)ipBegin + 4; offset <= endOffset; offset += 7) {
int temp = readInt3(offset);
if (temp != -1) {
IPLocation loc = getIPLocation(temp);
if ((loc.country.indexOf(s) != -1) ||
(loc.area.indexOf(s) != -1)) {
IPEntry entry = new IPEntry();
entry.country = loc.country;
entry.area = loc.area;
readIP(offset - 4, b4);
entry.beginIp = Utils.getIpStringFromBytes(b4);
readIP(temp, b4);
entry.endIp = Utils.getIpStringFromBytes(b4);
ret.add(entry);
}
}
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
return ret;
}
private int readInt3(int offset)
{
mbb.position(offset);
return mbb.getInt() & 0xFFFFFF;
}
private int readInt3()
{
return mbb.getInt() & 0xFFFFFF;
}
public static String getCountry(byte[] ip)
{
if (ipFile == null) {
return "错误的IP数据库文件";
}
String ipStr = Utils.getIpStringFromBytes(ip);
if (ipCache.containsKey(ipStr)) {
IPLocation loc = (IPLocation)ipCache.get(ipStr);
return loc.country;
}
IPLocation loc = getIPLocation(ip);
ipCache.put(ipStr, loc.getCopy());
return loc.country;
}
public static String getCountry(String ip)
{
return getCountry(Utils.getIpByteArrayFromString(ip));
}
public String getArea(byte[] ip)
{
if (ipFile == null) {
return "错误的IP数据库文件";
}
String ipStr = Utils.getIpStringFromBytes(ip);
if (ipCache.containsKey(ipStr)) {
IPLocation loc = (IPLocation)ipCache.get(ipStr);
return loc.area;
}
IPLocation loc = getIPLocation(ip);
ipCache.put(ipStr, loc.getCopy());
return loc.area;
}
public String getArea(String ip)
{
return getArea(Utils.getIpByteArrayFromString(ip));
}
private static IPLocation getIPLocation(byte[] ip)
{
IPLocation info = null;
long offset = locateIP(ip);
if (offset != -1L)
info = getIPLocation(offset);
if (info == null) {
info.country = "未知国家";
info.area = "未知地区";
}
return info;
}
private long readLong4(long offset)
{
long ret = 0L;
try {
ipFile.seek(offset);
ret |= ipFile.readByte() & 0xFF;
ret |= ipFile.readByte() << 8 & 0xFF00;
ret |= ipFile.readByte() << 16 & 0xFF0000;
return ret | ipFile.readByte() << 24 & 0xFF000000;
} catch (IOException e) {
}
return -1L;
}
private static long readLong3(long offset)
{
long ret = 0L;
try {
ipFile.seek(offset);
ipFile.readFully(b3);
ret |= b3[0] & 0xFF;
ret |= b3[1] << 8 & 0xFF00;
return ret | b3[2] << 16 & 0xFF0000;
} catch (IOException e) {
}
return -1L;
}
private static long readLong3()
{
long ret = 0L;
try {
ipFile.readFully(b3);
ret |= b3[0] & 0xFF;
ret |= b3[1] << 8 & 0xFF00;
return ret | b3[2] << 16 & 0xFF0000;
} catch (IOException e) {
}
return -1L;
}
private static void readIP(long offset, byte[] ip)
{
try
{
ipFile.seek(offset);
ipFile.readFully(ip);
byte temp = ip[0];
ip[0] = ip[3];
ip[3] = temp;
temp = ip[1];
ip[1] = ip[2];
ip[2] = temp;
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private void readIP(int offset, byte[] ip)
{
mbb.position(offset);
mbb.get(ip);
byte temp = ip[0];
ip[0] = ip[3];
ip[3] = temp;
temp = ip[1];
ip[1] = ip[2];
ip[2] = temp;
}
private static int compareIP(byte[] ip, byte[] beginIp)
{
for (int i = 0; i < 4; i++) {
int r = compareByte(ip[i], beginIp[i]);
if (r != 0)
return r;
}
return 0;
}
private static int compareByte(byte b1, byte b2)
{
if ((b1 & 0xFF) > (b2 & 0xFF))
return 1;
if ((b1 ^ b2) == 0) {
return 0;
}
return -1;
}
private static long locateIP(byte[] ip)
{
long m = 0L;
readIP(ipBegin, b4);
int r = compareIP(ip, b4);
if (r == 0)
return ipBegin;
if (r < 0) {
return -1L;
}
long i = ipBegin; for (long j = ipEnd; i < j; ) {
m = getMiddleOffset(i, j);
readIP(m, b4);
r = compareIP(ip, b4);
if (r > 0)
i = m;
else if (r < 0) {
if (m == j) {
j -= 7L;
m = j;
} else {
j = m;
}
} else return readLong3(m + 4L);
}
m = readLong3(m + 4L);
readIP(m, b4);
r = compareIP(ip, b4);
if (r <= 0) {
return m;
}
return -1L;
}
private static long getMiddleOffset(long begin, long end)
{
long records = (end - begin) / 7L;
records >>= 1;
if (records == 0L)
records = 1L;
return begin + records * 7L;
}
private static IPLocation getIPLocation(long offset)
{
try
{
ipFile.seek(offset + 4L);
byte b = ipFile.readByte();
if (b == 1)
{
long countryOffset = readLong3();
ipFile.seek(countryOffset);
b = ipFile.readByte();
if (b == 2) {
loc.country = readString(readLong3());
ipFile.seek(countryOffset + 4L);
} else {
loc.country = readString(countryOffset);
}
loc.area = readArea(ipFile.getFilePointer());
} else if (b == 2) {
loc.country = readString(readLong3());
loc.area = readArea(offset + 8L);
} else {
loc.country = readString(ipFile.getFilePointer() - 1L);
loc.area = readArea(ipFile.getFilePointer());
}
return loc; } catch (IOException e) {
}
return null;
}
private IPLocation getIPLocation(int offset)
{
mbb.position(offset + 4);
byte b = mbb.get();
if (b == 1)
{
int countryOffset = readInt3();
mbb.position(countryOffset);
b = mbb.get();
if (b == 2) {
loc.country = readString(readInt3());
mbb.position(countryOffset + 4);
} else {
loc.country = readString(countryOffset);
}
loc.area = readArea(mbb.position());
} else if (b == 2) {
loc.country = readString(readInt3());
loc.area = readArea(offset + 8);
} else {
loc.country = readString(mbb.position() - 1);
loc.area = readArea(mbb.position());
}
return loc;
}
private static String readArea(long offset)
throws IOException
{
ipFile.seek(offset);
byte b = ipFile.readByte();
if ((b == 1) || (b == 2)) {
long areaOffset = readLong3(offset + 1L);
if (areaOffset == 0L) {
return "未知地区";
}
return readString(areaOffset);
}
return readString(offset);
}
private String readArea(int offset)
{
mbb.position(offset);
byte b = mbb.get();
if ((b == 1) || (b == 2)) {
int areaOffset = readInt3();
if (areaOffset == 0) {
return "未知地区";
}
return readString(areaOffset);
}
return readString(offset);
}
private static String readString(long offset)
{
try
{
ipFile.seek(offset);
int i = 0; for (buf[i] = ipFile.readByte(); buf[i] != 0; ) buf[(++i)] = ipFile
.readByte();
if (i != 0)
return Utils.getString(buf, 0, i, "GBK");
} catch (IOException e) {
System.out.println(e.getMessage());
}
return "";
}
private String readString(int offset)
{
try
{
mbb.position(offset);
int i = 0; for (buf[i] = mbb.get(); buf[i] != 0; buf[(++i)] = mbb.get());
if (i != 0)
return Utils.getString(buf, 0, i, "GBK");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
return "";
}
public String getAddress(String ip)
{
String country = getCountry(ip).equals(" CZ88.NET") ? "null" :
getCountry(ip);
String area = getArea(ip).equals(" CZ88.NET") ? "null" : getArea(ip);
String address = country + "|" + area;
return address.trim();
}
public static String getAddressByCity(String ip)
{
String country = getCountry(ip).equals(" CZ88.NET") ? "null" :
getCountry(ip);
String address = country;
return address.trim();
}
public static Map<String, Object> jqCity(String str)
{
String shortname = "";
String areaname = "";
Map map = new HashMap();
boolean status = str.contains("省");
if (status)
{
String[] splitstr = str.split("省");
shortname = splitstr[0] + "省";
areaname = splitstr[1];
if (areaname.contains("市")) {
areaname = areaname.split("市")[0] + "市";
}
}
boolean xj = str.contains("新疆");
if (xj) {
String[] splitstr = str.split("新疆");
for (String string : splitstr) {
System.out.println(string);
}
shortname = "新疆";
areaname = splitstr[1];
}
boolean xz = str.contains("西藏");
if (xz) {
String[] splitstr = str.split("西藏");
for (String string : splitstr) {
System.out.println(string);
}
shortname = "西藏";
areaname = splitstr[1];
}
boolean nmg = str.contains("内蒙古");
if (nmg) {
String[] splitstr = str.split("内蒙古");
for (String string : splitstr) {
System.out.println(string);
}
shortname = "内蒙古";
areaname = splitstr[1];
}
boolean nx = str.contains("宁夏");
if (nx) {
String[] splitstr = str.split("宁夏");
for (String string : splitstr) {
System.out.println(string);
}
shortname = "宁夏";
areaname = splitstr[1];
}
boolean gx = str.contains("广西");
if (gx) {
String[] splitstr = str.split("广西");
for (String string : splitstr) {
System.out.println(string);
}
shortname = "广西";
areaname = splitstr[1];
}
boolean bjs = str.contains("北京市");
boolean tjs = str.contains("天津市");
boolean shs = str.contains("上海市");
boolean cqs = str.contains("重庆市");
boolean xg = str.contains("香港");
boolean am = str.contains("澳门");
if ((am) || (xg) || (cqs) || (shs) || (tjs) || (bjs)) {
System.out.println(str);
shortname = str;
areaname = str;
}
map.put("shortname", shortname);
map.put("areaname", areaname);
return map;
}
public static void main(String[] args)
{
IPSeeker is = new IPSeeker();
System.out.println(is.getAddress("119.123.225.83"));
System.out.println(is.getAddress("14.215.177.39"));
System.out.println(is.getAddress("113.78.255.221"));
System.out.println(is.getAddress("182.34.16.127"));
System.out.println(is.getAddress("180.118.240.225"));
System.out.println(is.getAddress("119.29.252.90"));
System.out.println(is.getAddress("61.128.101.255"));
System.out.println(is.getAddress("110.157.255.255"));
System.out.println(is.getAddress("220.182.44.228"));
System.out.println(is.getAddress("1.183.255.255"));
System.out.println(is.getAddress("123.125.71.38"));
System.out.println(is.getAddress("203.186.145.250"));
System.out.println(is.getAddress("111.113.255.255"));
System.out.println(is.getAddress("180.143.255.255"));
}
private class IPLocation
{
public String country;
public String area;
public IPLocation()
{
this.country = (this.area = "");
}
public IPLocation getCopy() {
IPLocation ret = new IPLocation();
ret.country = this.country;
ret.area = this.area;
return ret;
}
}
}
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.*;
public class JsonToMap
{
public static JsonObject parseJson(String json)
{
JsonParser parser = new JsonParser();
JsonObject jsonObj = parser.parse(json).getAsJsonObject();
return jsonObj;
}
public static Map<String, Object> toMap(String json)
{
return toMap(parseJson(json));
}
public static Map<String, Object> toMap(JsonObject json)
{
Map map = new HashMap();
Set entrySet = json.entrySet();
for (Iterator iter = entrySet.iterator(); iter.hasNext(); ) {
Map.Entry entry = (Map.Entry)iter.next();
String key = (String)entry.getKey();
Object value = entry.getValue();
if ((value instanceof JsonArray))
map.put(key, toList((JsonArray)value));
else if ((value instanceof JsonObject))
map.put(key, toMap((JsonObject)value));
else
map.put(key, value);
}
return map;
}
public static List<Object> toList(JsonArray json)
{
List list = new ArrayList();
for (int i = 0; i < json.size(); i++) {
Object value = json.get(i);
if ((value instanceof JsonArray)) {
list.add(toList((JsonArray)value));
}
else if ((value instanceof JsonObject)) {
list.add(toMap((JsonObject)value));
}
else {
list.add(value);
}
}
return list;
}
}
import com.google.gson.*;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class JsonUtil
{
private static final JsonUtil singleton = new JsonUtil();
private static InputStream in;
private JsonUtil()
{
if (in == null)
in = JsonUtil.class.getResourceAsStream("/shop_area.json");
}
public static JsonUtil getInstance()
{
return singleton;
}
public List<Map<String, Object>> readJson() {
List list = new ArrayList();
try {
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject)parser.parse(readStream(in));
JsonArray array = object.get("RECORDS").getAsJsonArray();
for (int i = 0; i < array.size(); i++) {
JsonObject subObject = array.get(i).getAsJsonObject();
list.add(JsonToMap.toMap(subObject));
}
} catch (JsonIOException e) {
e.printStackTrace();
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
return list;
}
public static String readStream(InputStream in)
{
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = in.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
String content = baos.toString();
in.close();
baos.close();
return content;
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
}
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
public class PropertiesUtil
{
private static Properties props;
static
{
String fileName = "test.properties";
props = new Properties();
try {
props.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName), "UTF-8"));
} catch (IOException e) {
System.out.print("配置文件读取异常");
}
}
public static String getProperty(String key) {
String value = props.getProperty(key.trim());
if ((value == null) || ("".equals(value))) {
return null;
}
return value.trim();
}
public static String getProperty(String key, String defaultValue)
{
String value = props.getProperty(key.trim());
if ((value == null) || ("".equals(value))) {
value = defaultValue;
}
return value.trim();
}
}
import java.io.UnsupportedEncodingException;
import java.util.StringTokenizer;
public class Utils
{
public static byte[] getIpByteArrayFromString(String ip)
{
byte[] ret = new byte[4];
StringTokenizer st = new StringTokenizer(ip, ".");
try {
ret[0] = ((byte)(Integer.parseInt(st.nextToken()) & 0xFF));
ret[1] = ((byte)(Integer.parseInt(st.nextToken()) & 0xFF));
ret[2] = ((byte)(Integer.parseInt(st.nextToken()) & 0xFF));
ret[3] = ((byte)(Integer.parseInt(st.nextToken()) & 0xFF));
} catch (Exception e) {
System.out.println(e.getMessage());
}
return ret;
}
public static void main(String[] args) {
byte[] a = getIpByteArrayFromString(args[0]);
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
System.out.println(getIpStringFromBytes(a));
}
public static String getString(String s, String srcEncoding, String destEncoding)
{
try
{
return new String(s.getBytes(srcEncoding), destEncoding); } catch (UnsupportedEncodingException e) {
}
return s;
}
public static String getString(byte[] b, String encoding)
{
try
{
return new String(b, encoding); } catch (UnsupportedEncodingException e) {
}
return new String(b);
}
public static String getString(byte[] b, int offset, int len, String encoding)
{
try
{
return new String(b, offset, len, encoding); } catch (UnsupportedEncodingException e) {
}
return new String(b, offset, len);
}
public static String getIpStringFromBytes(byte[] ip)
{
StringBuffer sb = new StringBuffer();
sb.append(ip[0] & 0xFF);
sb.append('.');
sb.append(ip[1] & 0xFF);
sb.append('.');
sb.append(ip[2] & 0xFF);
sb.append('.');
sb.append(ip[3] & 0xFF);
return sb.toString();
}
}
百度网盘获取json数据
提取码:o73l