添加火点数据

This commit is contained in:
DESKTOP-4U0TDEF\20371 2021-07-13 10:18:08 +08:00
parent 38ba7d3183
commit 1609ffb6f6
11 changed files with 245 additions and 207 deletions

View File

@ -147,6 +147,13 @@
<version>${poi-ooxml.version}</version> <version>${poi-ooxml.version}</version>
</dependency> </dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
</dependencies> </dependencies>

View File

@ -41,10 +41,7 @@ class WebSecurityConfig extends WebSecurityConfigurerAdapter {
// 所有 app 用户注册 的POST请求 都放行 // 所有 app 用户注册 的POST请求 都放行
.antMatchers(HttpMethod.POST, "/api/person-investigator/add").permitAll() .antMatchers(HttpMethod.POST, "/api/person-investigator/add").permitAll()
.antMatchers(HttpMethod.GET,"/api/user/booleanUserName").permitAll() .antMatchers(HttpMethod.GET,"/api/user/booleanUserName").permitAll()
.antMatchers(HttpMethod.POST,"/importRsProjectExcel").permitAll() .antMatchers(HttpMethod.POST,"/insertFirePoint").permitAll()
.antMatchers(HttpMethod.POST,"/importCvProjectExcel").permitAll()
.antMatchers(HttpMethod.GET,"/excelOutWork").permitAll()
.antMatchers(HttpMethod.GET,"/selectMemberAndWorkHour").permitAll()
// 所有其它请求需要身份认证 // 所有其它请求需要身份认证
.anyRequest().authenticated() .anyRequest().authenticated()
.and() .and()

View File

@ -0,0 +1,42 @@
package com.xkrs.controller;
import com.xkrs.common.encapsulation.PromptMessageEnum;
import com.xkrs.model.entity.FirePointEntity;
import com.xkrs.model.qo.FirePointQo;
import com.xkrs.service.FirePointService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.Locale;
import static com.xkrs.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
/**
* @author XinYi Song
*/
@RestController
public class FirePointServiceController {
@Resource
private FirePointService firePointService;
/**
* 添加火点数据
* @param firePointQo
* @return
*/
@PostMapping("/insertFirePoint")
public String insertFirePoint(@RequestBody FirePointQo firePointQo){
// 获取区域信息
Locale locale = LocaleContextHolder.getLocale();
FirePointEntity firePointEntity = firePointService.insertFirePoint(firePointQo);
if(firePointEntity == null){
return outputEncapsulationObject(PromptMessageEnum.PROCESS_FAIL,"添加数据失败",locale);
}else {
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"添加成功",locale);
}
}
}

View File

@ -0,0 +1,12 @@
package com.xkrs.dao;
import com.xkrs.model.entity.FirePointEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
/**
* @author XinYi Song
*/
@Component
public interface FirePointDao extends JpaRepository<FirePointEntity,Long> {
}

View File

@ -74,6 +74,11 @@ public class FirePointEntity implements Serializable {
@Column(length = 32, columnDefinition = "varchar(32)") @Column(length = 32, columnDefinition = "varchar(32)")
private String confidence; private String confidence;
/**
* 详细地址
*/
private String firePointAddress;
/** /**
* 火点状态 0 发现 1预警 2核查 -1,3结案 * 火点状态 0 发现 1预警 2核查 -1,3结案
*/ */
@ -83,7 +88,7 @@ public class FirePointEntity implements Serializable {
public FirePointEntity() { public FirePointEntity() {
} }
public FirePointEntity(Integer id, String fireCode, double longitude, double latitude, String countyCode, String countyName, String satelliteTime, String satelliteType, String landType, String addTime, String confidence, String fireType) { public FirePointEntity(Integer id, String fireCode, double longitude, double latitude, String countyCode, String countyName, String satelliteTime, String satelliteType, String landType, String addTime, String confidence, String firePointAddress, String fireType) {
this.id = id; this.id = id;
this.fireCode = fireCode; this.fireCode = fireCode;
this.longitude = longitude; this.longitude = longitude;
@ -95,6 +100,7 @@ public class FirePointEntity implements Serializable {
this.landType = landType; this.landType = landType;
this.addTime = addTime; this.addTime = addTime;
this.confidence = confidence; this.confidence = confidence;
this.firePointAddress = firePointAddress;
this.fireType = fireType; this.fireType = fireType;
} }
@ -186,6 +192,14 @@ public class FirePointEntity implements Serializable {
this.confidence = confidence; this.confidence = confidence;
} }
public String getFirePointAddress() {
return firePointAddress;
}
public void setFirePointAddress(String firePointAddress) {
this.firePointAddress = firePointAddress;
}
public String getFireType() { public String getFireType() {
return fireType; return fireType;
} }
@ -208,6 +222,7 @@ public class FirePointEntity implements Serializable {
", landType='" + landType + '\'' + ", landType='" + landType + '\'' +
", addTime='" + addTime + '\'' + ", addTime='" + addTime + '\'' +
", confidence='" + confidence + '\'' + ", confidence='" + confidence + '\'' +
", firePointAddress='" + firePointAddress + '\'' +
", fireType='" + fireType + '\'' + ", fireType='" + fireType + '\'' +
'}'; '}';
} }

View File

@ -14,7 +14,7 @@ public class FirePointQo {
/** /**
* 省市区的编码 * 省市区的编码
*/ */
private String countyCode; private Integer countyCode;
/** /**
* 省市区的名称 * 省市区的名称
@ -24,7 +24,7 @@ public class FirePointQo {
/** /**
* 卫星监测的时间戳 * 卫星监测的时间戳
*/ */
private Long satelliteTimeTs; private Integer satelliteTimeTs;
/** /**
* 经度 * 经度
@ -54,7 +54,7 @@ public class FirePointQo {
public FirePointQo() { public FirePointQo() {
} }
public FirePointQo(String fireCode, String countyCode, String countyName, Long satelliteTimeTs, Double longitude, Double latitude, String satelliteType, String landType, String confidence) { public FirePointQo(String fireCode, Integer countyCode, String countyName, Integer satelliteTimeTs, Double longitude, Double latitude, String satelliteType, String landType, String confidence) {
this.fireCode = fireCode; this.fireCode = fireCode;
this.countyCode = countyCode; this.countyCode = countyCode;
this.countyName = countyName; this.countyName = countyName;
@ -74,11 +74,11 @@ public class FirePointQo {
this.fireCode = fireCode; this.fireCode = fireCode;
} }
public String getCountyCode() { public Integer getCountyCode() {
return countyCode; return countyCode;
} }
public void setCountyCode(String countyCode) { public void setCountyCode(Integer countyCode) {
this.countyCode = countyCode; this.countyCode = countyCode;
} }
@ -90,11 +90,11 @@ public class FirePointQo {
this.countyName = countyName; this.countyName = countyName;
} }
public Long getSatelliteTimeTs() { public Integer getSatelliteTimeTs() {
return satelliteTimeTs; return satelliteTimeTs;
} }
public void setSatelliteTimeTs(Long satelliteTimeTs) { public void setSatelliteTimeTs(Integer satelliteTimeTs) {
this.satelliteTimeTs = satelliteTimeTs; this.satelliteTimeTs = satelliteTimeTs;
} }

View File

@ -0,0 +1,18 @@
package com.xkrs.service;
import com.xkrs.dao.FirePointDao;
import com.xkrs.model.entity.FirePointEntity;
import com.xkrs.model.qo.FirePointQo;
/**
* @author XinYi Song
*/
public interface FirePointService {
/**
* 添加火点信息
* @param firePointQo
* @return
*/
FirePointEntity insertFirePoint(FirePointQo firePointQo);
}

View File

@ -0,0 +1,46 @@
package com.xkrs.service.impl;
import com.xkrs.dao.FirePointDao;
import com.xkrs.model.entity.FirePointEntity;
import com.xkrs.model.qo.FirePointQo;
import com.xkrs.service.FirePointService;
import com.xkrs.utils.AddressUtils;
import com.xkrs.utils.DateTimeUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDateTime;
/**
* @author XinYi Song
*/
@Service
public class FirePointServiceImpl implements FirePointService {
@Resource
private FirePointDao firePointDao;
/**
* 添加火点信息
* @param firePointQo
* @return
*/
@Override
public FirePointEntity insertFirePoint(FirePointQo firePointQo) {
FirePointEntity firePointEntity = new FirePointEntity();
firePointEntity.setFireCode(firePointQo.getFireCode());
firePointEntity.setCountyCode(firePointQo.getCountyCode().toString());
firePointEntity.setCountyName(firePointQo.getCountyName());
firePointEntity.setSatelliteTime(DateTimeUtil.timeMillisToString(firePointQo.getSatelliteTimeTs().longValue()));
firePointEntity.setLongitude(firePointQo.getLongitude());
firePointEntity.setLatitude(firePointQo.getLatitude());
firePointEntity.setFirePointAddress(AddressUtils.getLatAndLng(firePointQo.getLatitude().toString(),firePointQo.getLongitude().toString()));
firePointEntity.setSatelliteType(firePointQo.getSatelliteType());
firePointEntity.setLandType(firePointQo.getLandType());
firePointEntity.setConfidence(firePointQo.getConfidence());
firePointEntity.setAddTime(DateTimeUtil.dateTimeToString(LocalDateTime.now()));
firePointEntity.setFireType("0");
return firePointDao.save(firePointEntity);
}
}

View File

@ -1,31 +1,13 @@
package com.xkrs.utils; package com.xkrs.utils;
import com.fasterxml.jackson.core.JsonProcessingException; import net.sf.json.JSONObject;
import com.fasterxml.jackson.databind.JsonNode; import io.micrometer.core.instrument.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader; import javax.net.ssl.*;
import java.io.IOException; import java.io.*;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.nio.charset.StandardCharsets; import java.security.cert.CertificateException;
import java.util.HashMap; import java.security.cert.X509Certificate;
import java.util.Map;
/** /**
* 根据经纬度获取地址: 位置名称 * 根据经纬度获取地址: 位置名称
@ -33,179 +15,91 @@ import java.util.Map;
*/ */
public class AddressUtils { public class AddressUtils {
private static final Logger log = LoggerFactory.getLogger(AddressUtils.class); public static String getLatAndLng(String lat, String lng) {
private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + String key = "O7QBZ-ZYDKI-EMKGN-53UHG-5XSJF-AAFBP";
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36";
/**
* 获取指定经纬度的地理位置
* @param latitude 纬度
* @param longitude 经度
* @return
*/
public static String getLocal(String latitude, String longitude) {
String ok = "ok";
String msg = "msg";
String info = getAdd(latitude, longitude);
ObjectMapper mapper = new ObjectMapper();
JsonNode node = null;
try { try {
node = mapper.readTree(info); String hsUrl = "https://apis.map.qq.com/ws/geocoder/v1/?location=" + lat + "," + lng + "&key=" + key + "&get_poi=1";
} catch (JsonProcessingException e) {
URL url;
url = new URL(hsUrl);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
// 提交模式
con.setRequestMethod("GET");
X509TrustManager xtm = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}
};
TrustManager[] tm = {xtm};
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, tm, null);
con.setSSLSocketFactory(ctx.getSocketFactory());
con.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
InputStream inStream = con.getInputStream();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
//网页的二进制数据
byte[] b = outStream.toByteArray();
outStream.close();
inStream.close();
String rtn = new String(b, "utf-8");
if (StringUtils.isNotBlank(rtn)) {
JSONObject object = JSONObject.fromObject(rtn);
if (object != null) {
if (object.has("status") && object.getInt("status") == 0) {
JSONObject result = JSONObject.fromObject(object.get("result"));
if (result != null) {
JSONObject addressComponent = JSONObject.fromObject(result.get("address_component"));
if (addressComponent != null) {
String province = (String) addressComponent.get("province");
String city = (String) addressComponent.get("city");
String district = (String) addressComponent.get("district");
String street = (String) addressComponent.get("street");
String street_number = (String) addressComponent.get("street_number");
String address = province + city + district + street + street_number;
return address;
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
assert node != null; return null;
String province = null;
String city = null;
String county = null;
String road = null;
String address = null;
if (ok.equals(node.path(msg).asText())) {
province = node.path("result").path("addressComponent").path("province").asText();
city = node.path("result").path("addressComponent").path("city").asText();
county = node.path("result").path("addressComponent").path("county").asText();
road = node.path("result").path("addressComponent").path("road").asText();
address = node.path("result").path("addressComponent").path("address").asText();
}
String fireAddress = province + city + county + road + address;
return fireAddress;
}
/**
* 根据经纬度获取位置信息
* @param latitude 纬度
* @param longitude 经度
* @return
*/
public static String getAdd(String latitude, String longitude) {
// 读取成功标志
boolean isSuccess = false;
// 重复次数
int count = 10;
ObjectMapper mapper = new ObjectMapper();
Map<String, String> paramMap = new HashMap<>(3);
paramMap.put("lon", longitude);
paramMap.put("lat", latitude);
paramMap.put("ver", "1");
String paramStr = null;
try {
paramStr = mapper.writeValueAsString(paramMap);
} catch (JsonProcessingException e) {
log.error("转json失败,{}", (Object) e.getStackTrace());
}
String url = String.format("http://api.tianditu.gov.cn/geocoder?type=geocode&tk=5a1d34815475f88e6d8802da6be832ae&postStr=%s",
paramStr);
// 创建http对象
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(60000).setConnectTimeout(60000)
.setConnectionRequestTimeout(60000)
.build();
CloseableHttpClient client = HttpClients.custom()
.setDefaultRequestConfig(defaultRequestConfig).build();
// 创建并设置URI
URIBuilder uri = null;
// 创建Get请求
HttpGet get = null;
try {
URL url1 = new URL(url);
URI uri1 = new URI(url1.getProtocol(), url1.getHost(), url1.getPath(), url1.getQuery(), null);
uri = new URIBuilder(uri1);
get = new HttpGet(uri.build());
// 设置请求头
setGet(get);
} catch (URISyntaxException | MalformedURLException e) {
log.info("错误{}", (Object) e.getStackTrace());
}
//发送请求
HttpEntity entity = null;
InputStream is = null;
BufferedReader br = null;
// 创建响应对象
CloseableHttpResponse response = null;
String line;
String sLine = null;
String json = null;
while (!isSuccess && count > 0) {
try {
response = client.execute(get);
// 获取请求结果
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
log.info("实时定位数据未请求成功");
count--;
//close(is, br, response, client);
continue;
}
entity = response.getEntity();
is = entity.getContent();
br = new BufferedReader(
new InputStreamReader(is, StandardCharsets.UTF_8)
);
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
sLine = sb.toString();
sLine = sLine.substring(sLine.indexOf("{"));
//使用ObjectMapper对象对 User对象进行转换
try {
json = mapper.writeValueAsString(sLine);
} catch (JsonProcessingException e) {
log.info("json字符串转化异常{}", (Object) e.getStackTrace());
}
isSuccess = true;
} catch (ClientProtocolException e) {
log.info("请求超时等问题:{}", (Object) e.getStackTrace());
} catch (IOException e) {
log.info("I/O问题:{}", (Object) e.getStackTrace());
} finally {
close(is, br, response, client);
}
}
return sLine;
}
private static void close(InputStream is, BufferedReader br, CloseableHttpResponse response, CloseableHttpClient client){
try {
if (null != is){
is.close();
}
if (null != br){
br.close();
}
if (null != response){
response.close();
}
if (null != client){
client.close();
}
} catch (IOException e) {
log.info("IO错误{}", (Object) e.getStackTrace());
}
}
private static HttpGet setGet(HttpGet get) {
get.setHeader("Accept"
, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
get.setHeader("Accept-Encoding"
, "gzip, deflate");
get.setHeader("Accept-Language"
, "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-TW;q=0.6");
get.setHeader("Connection"
, "keep-alive");
get.setHeader("Cache-Control"
, "no-cache");
get.setHeader("Upgrade-Insecure-Requests"
, "1");
get.setHeader("User-Agent", USER_AGENT);
return get;
} }
public static void main(String[] args) { public static void main(String[] args) {
String map = getAdd("35.150684", "115.84691"); String latAndLng = getLatAndLng("36.8685", "116.6510");
String local = getLocal("36.90033", "117.752853"); System.out.println(latAndLng);
System.out.println(local);
} }
} }

View File

@ -139,8 +139,9 @@ public class DateTimeUtil {
* @return * @return
*/ */
public static String timeMillisToString(long timeMillis){ public static String timeMillisToString(long timeMillis){
LocalDateTime dateTime =LocalDateTime.ofEpochSecond(timeMillis,0, DEFAULT_ZONE_OFFSET); Instant instant = Instant.ofEpochMilli(timeMillis);
return COMMON_FORMATTER_DATETIME.format(dateTime); LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, DEFAULT_ZONE_OFFSET);
return COMMON_FORMATTER_DATETIME.format(localDateTime);
} }
/** /**
@ -212,4 +213,10 @@ public class DateTimeUtil {
return matcher.matches(); return matcher.matches();
} }
public static void main(String[] args) {
//long l = dateToTimeMillis(LocalDateTime.now());
//timeMillisToString(1626082306233)
//System.out.println(l);
}
} }

View File

@ -24,7 +24,7 @@ spring.datasource.hikari.validation-timeout = 3000
## Spring Data JPA 配置 ## Spring Data JPA 配置
spring.jpa.database = POSTGRESQL spring.jpa.database = POSTGRESQL
spring.jpa.database-platform = org.hibernate.dialect.PostgreSQLDialect spring.jpa.database-platform = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.show-sql = false spring.jpa.show-sql = true
# 指定 ddl mode (none, validate, create, create-drop, update) # 指定 ddl mode (none, validate, create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update spring.jpa.hibernate.ddl-auto = update
# 命名策略 # 命名策略