Commit dbd43d02 by 崔彦峰

svn to git

0 parents
Showing 48 changed files with 2119 additions and 0 deletions
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.com.glsx.framework</groupId>
<artifactId>framework-rpc-api</artifactId>
<version>2.0.0-SNAPSHOT</version>
</parent>
<groupId>cn.com.glsx.dj</groupId>
<artifactId>rpc-dj-device-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>rpc-dj-device-api</name>
<properties>
<deploy.scanPackage>cn.com.glsx.dj.device.remote</deploy.scanPackage>
</properties>
<build>
<plugins>
<plugin>
<groupId>cn.com.glsx.framework</groupId>
<artifactId>rpc-api-deploy-maven-plugin</artifactId>
<dependencies>
<dependency>
<groupId>cn.com.glsx.dj</groupId>
<artifactId>rpc-dj-device-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.dj.device.dto;
import cn.com.glsx.dj.device.model.OutDeviceEventMessage;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.SuperBuilder;
@Data
@ToString(callSuper = true)
@SuperBuilder
@AllArgsConstructor
@NoArgsConstructor
public class OutDeviceEventMessageDTO extends OutDeviceEventMessage{/**
*
*/
private static final long serialVersionUID = 4139446885195875549L;
private String sourceType;
}
package cn.com.glsx.dj.device.enums;
public class DeviceEnum {
public enum SourceType {
/** 万国**/
WG("WG", "万国");
private String value;
private String description;
SourceType(String value, String description) {
this.value = value;
this.description = description;
}
public String getValue() {
return value;
}
public String getDescription() {
return description;
}
}
}
package cn.com.glsx.dj.device.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.SuperBuilder;
@Data
@ToString
@SuperBuilder
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "dj_out_device_event_message")
public class OutDeviceEventMessage implements Serializable{
/**
*
*/
private static final long serialVersionUID = -6657962201434905059L;
/**
* 主键ID
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
/**
* 设备号
*/
private String sn;
/**
* 标题
*/
private String title;
/**
* 内容
*/
private String content;
/**
* 消息类型(10-碰撞消息)
*/
private Integer type;
/**
* 事件位置
*/
private String address;
/**
* 事件经度
*/
private String lng;
/**
* 事件纬度
*/
private String lat;
/**
* 事件时间
*/
@Column(name = "event_date")
private Date eventDate;
/**
* 事件媒体文件任务ID
*/
@Column(name = "task_id")
private String taskId;
/**
* 推送成功标识(Y:已成功,N:未成功)
*/
@Column(name = "push_success_flag")
private String pushSuccessFlag;
/**
* 创建时间
*/
@Column(name = "created_date")
private Date createdDate;
/**
* 修改时间
*/
@Column(name = "updated_date")
private Date updatedDate;
/**
* 删除标示:D 已删除;N 未删除
*/
@Column(name = "deleted_flag")
private String deletedFlag;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.dj.device.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@ToString
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "dj_out_device_info")
public class OutDeviceInfo implements Serializable{
/**
*
*/
private static final long serialVersionUID = -282238104431795830L;
/**
* 主键ID
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
/**
* 设备号
*/
private String sn;
/**
* 来源类型(WG:万国)
*/
@Column(name = "source_type")
private String sourceType;
/**
* 创建时间
*/
@Column(name = "created_date")
private Date createdDate;
/**
* 修改时间
*/
@Column(name = "updated_date")
private Date updatedDate;
/**
* 删除标示:D 已删除;N 未删除
*/
@Column(name = "deleted_flag")
private String deletedFlag;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.dj.device.remote;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import cn.com.glsx.dj.device.model.OutDeviceInfo;
import cn.com.glsx.framework.core.annotation.ApiMethod;
import cn.com.glsx.framework.core.annotation.ApiParam;
import cn.com.glsx.framework.core.annotation.ApiResponse;
import cn.com.glsx.framework.core.annotation.ApiService;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
@ApiService(value="外部设备接口",owner="zhoulm")
public interface OutDeviceInfoRemote {
@ApiMethod("添加外部设备")
@ApiParam(name="info",notes="要添加的设备信息",dataType= ApiParam.DataTypeEnum.OBJECT,required=true)
@ApiResponse("返回成功添加的外部设备")
RpcResponse<OutDeviceInfo> insert(@NotNull OutDeviceInfo info);
@ApiMethod("查询设备信息")
@ApiParam(name="sn",notes="设备号",dataType= ApiParam.DataTypeEnum.STRING,required=true)
@ApiResponse("返回设备信息")
RpcResponse<OutDeviceInfo> getBySn(@NotBlank String sn);
}
# framework-archetype-rpc-api
RPC-API项目骨架
一、项目结构说明:
└─src
├─main
├─java
├─cn.com.glsx.dj.oss.dto 数据传输模型层
├─cn.com.glsx.dj.oss.enums 枚举定义
├─cn.com.glsx.dj.oss.model 数据模型层
└─cn.com.glsx.dj.oss.remote RPC暴露服务层
└─resources 资源文件目录
└─rpc
└─dubbo.xml dubbo接口配置
└─pom.xml pom文件
二、使用说明:
1、API改动后,请及时deploy到Maven仓库
三、注意事项:
1、rpc-api-deploy-maven-plugin api上报插件需配置当前api的jar包的引用。
\ No newline at end of file \ No newline at end of file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.com.glsx.framework</groupId>
<artifactId>framework-rpc</artifactId>
<version>2.0.0-SNAPSHOT</version>
</parent>
<groupId>cn.com.glsx.dj</groupId>
<artifactId>rpc-dj-device</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>rpc-dj-device</name>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>cn.com.glsx.dj</groupId>
<artifactId>rpc-dj-device-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.oreframework.boot</groupId>
<artifactId>ore-boot-starter-distribute-lock</artifactId>
</dependency>
<dependency>
<groupId>cn.com.glsx.framework</groupId>
<artifactId>framework-rop-extension</artifactId>
</dependency>
<dependency>
<groupId>org.oreframework.boot</groupId>
<artifactId>ore-boot-starter-jms</artifactId>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.6.1</version>
</dependency>
<dependency>
<groupId>org.oreframework.boot</groupId>
<artifactId>ore-boot-starter-elasticjob</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.dj.device;
import org.oreframework.boot.main.AbsOreBootStarter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@SpringBootApplication
@ServletComponentScan
public class Main extends AbsOreBootStarter {
@Override
public void run(String[] args)
{
SpringApplication.run(Main.class, args);
}
public static void main(String[] args)
{
Main main = new Main();
main.run(args);
}
}
package cn.com.glsx.dj.device.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties("amap")
public class AmapProperty {
/**
* 地图秘钥
*/
private String key;
/**
* 逆地址解析接口地址
*/
private String geocodeUrl;
/**
* 距离计算接口地址
*/
private String distanceUrl;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getGeocodeUrl() {
return geocodeUrl;
}
public void setGeocodeUrl(String geocodeUrl) {
this.geocodeUrl = geocodeUrl;
}
public String getDistanceUrl() {
return distanceUrl;
}
public void setDistanceUrl(String distanceUrl) {
this.distanceUrl = distanceUrl;
}
}
package cn.com.glsx.dj.device.config;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import cn.com.glsx.framework.core.enums.DefaultErrorEnum;
import cn.com.glsx.framework.rop.response.RopResponse;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandlerConfig {
@ExceptionHandler(MethodArgumentNotValidException.class)
public RopResponse<?> methodArgumentNotValidException(MethodArgumentNotValidException e) {
BindingResult bindingResult = e.getBindingResult();
List<String> errorList = bindingResult.getFieldErrors().stream().map(fieldError ->{
String msg = String.format("参数[%s]%s", fieldError.getField(), fieldError.getDefaultMessage());
return msg;
}).collect(Collectors.toList());
return RopResponse.result(DefaultErrorEnum.VALIDATE_FAILED, StringUtils.join(errorList, ","));
}
@ExceptionHandler(Exception.class)
public RopResponse<?> unNoException(Exception e) {
log.warn(e.getMessage(),e);
return RopResponse.result(DefaultErrorEnum.UNKNOW_ERROR, e.getMessage());
}
}
package cn.com.glsx.dj.device.config;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.alibaba.druid.support.http.util.IPAddress;
import com.alibaba.druid.support.http.util.IPRange;
import cn.com.glsx.dj.device.util.CommonUtil;
import cn.com.glsx.framework.core.enums.DefaultErrorEnum;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SecurityInterceptor extends HandlerInterceptorAdapter {
@Autowired
private Environment env;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String requestIp = CommonUtil.getIpAddr(request);
log.info("当前IP:{}",requestIp);
String ipRangs = env.getProperty("allow.request.ip.range");
if(ipRangs != null){
boolean ipLimit = true;
String[] ipRandArr = ipRangs.split(",");
for(String r:ipRandArr){
IPRange range = new IPRange(r);
IPAddress address = new IPAddress(requestIp);
if(range.isIPAddressInRange(address)){
ipLimit = false;
break;
}
}
if(ipLimit){
log.info("当前IP:{},不在允许访问IP名单内:{}",requestIp,ipRangs);
throw new RpcServiceException(DefaultErrorEnum.VALIDATE_FAILED,"请求IP受限,请联系公司人员");
}
}
return true;
}
}
package cn.com.glsx.dj.device.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public SecurityInterceptor getSecurityInterceptor() {
return new SecurityInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());
// 拦截配置
addInterceptor.addPathPatterns("/**");
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.dj.device.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.com.glsx.dj.device.converter.OutDeviceInfoConvert;
import cn.com.glsx.dj.device.model.OutDeviceInfo;
import cn.com.glsx.dj.device.remote.OutDeviceInfoRemote;
import cn.com.glsx.dj.device.request.outDeviceInfo.DeviceRegisterRequest;
import cn.com.glsx.dj.device.util.CommonUtil;
import cn.com.glsx.framework.rop.response.RopResponse;
@RestController
@RequestMapping("/outDeviceInfo")
public class OutDeviceInfoController {
@Autowired
private OutDeviceInfoRemote outDeviceInfoRemote;
@PostMapping("/deviceRegister")
public RopResponse<Boolean> deviceRegister(@Validated @RequestBody DeviceRegisterRequest request){
OutDeviceInfo info = OutDeviceInfoConvert.INSTANCE.fromDeviceRegisterRequest(request);
return CommonUtil.convertRopResponse(outDeviceInfoRemote.insert(info), (data) ->{
return true;
});
}
}
package cn.com.glsx.dj.device.converter;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
import cn.com.glsx.dj.device.model.OutDeviceEventMessage;
import cn.com.glsx.dj.device.model.OutDeviceInfo;
import cn.com.glsx.dj.device.request.outDeviceInfo.DeviceRegisterRequest;
import cn.com.glsx.dj.device.request.outDeviceInfo.PushDeviceToWgRequest;
@Mapper
public interface OutDeviceInfoConvert {
OutDeviceInfoConvert INSTANCE = Mappers.getMapper(OutDeviceInfoConvert.class);
OutDeviceInfo fromDeviceRegisterRequest(DeviceRegisterRequest request);
@Mapping(target = "sendTime",source = "eventDate",dateFormat = "yyyy-MM-dd HH:mm:ss")
PushDeviceToWgRequest toPushDeviceToWgRequest(OutDeviceEventMessage message);
}
package cn.com.glsx.dj.device.job;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.oreframework.boot.autoconfigure.elasticjob.annotation.ElasticJobConf;
import org.springframework.beans.factory.annotation.Autowired;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import cn.com.glsx.dj.device.converter.OutDeviceInfoConvert;
import cn.com.glsx.dj.device.dto.OutDeviceEventMessageDTO;
import cn.com.glsx.dj.device.enums.DeviceEnum.SourceType;
import cn.com.glsx.dj.device.manager.WgApiManager;
import cn.com.glsx.dj.device.request.outDeviceInfo.PushDeviceToWgRequest;
import cn.com.glsx.dj.device.response.WgBaseResponse;
import cn.com.glsx.dj.device.service.OutDeviceEventMessageService;
import cn.com.glsx.framework.core.enums.StatusEnum;
import lombok.extern.slf4j.Slf4j;
/**
*
* @Description:推送设备事件到万国
* @author zhoulm
*/
@Slf4j
@ElasticJobConf(name = "PushDeviceEventToWgJob", cron = "0 0/5 * * * ?", description="推送设备事件到万国", overwrite = true)
public class PushDeviceEventToWgJob implements SimpleJob {
@Autowired
private OutDeviceEventMessageService outDeviceEventMessageService;
@Autowired
private WgApiManager wgApiManager;
@Override
public void execute(ShardingContext context) {
log.info("----------------推送设备事件到万国任务开始-----------------");
try{
this.exec();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
log.info("----------------推送设备事件到万国任务结束-----------------");
}
private void exec() {
OutDeviceEventMessageDTO condition = OutDeviceEventMessageDTO.builder()
.sourceType(SourceType.WG.getValue())
.pushSuccessFlag(StatusEnum.NO.getValue()).build();
List<OutDeviceEventMessageDTO> list = outDeviceEventMessageService.list(condition);
if(CollectionUtils.isEmpty(list)){
return;
}
for(OutDeviceEventMessageDTO event:list){
try {
boolean pushResult = push(OutDeviceInfoConvert.INSTANCE.toPushDeviceToWgRequest(event));
if(pushResult) {
outDeviceEventMessageService.updatePushSuccess(event.getSn());
}
}catch(Exception e) {
log.error(e.getMessage(),e);
}
}
}
private boolean push(PushDeviceToWgRequest request) {
try {
WgBaseResponse wgBaseResponse = wgApiManager.pushDevice(request);
return wgBaseResponse != null && wgBaseResponse.isSuccess();
}catch(Exception e) {
log.error(e.getMessage(),e);
}
return false;
}
}
package cn.com.glsx.dj.device.manager;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.oreframework.util.http.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import cn.com.glsx.dj.device.config.AmapProperty;
import cn.com.glsx.dj.device.response.AmapRegeoResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
*
* @Description:高德地图接口管理
*/
@Component
public class AmapManager {
Logger logger = Logger.getLogger(getClass());
@Autowired
private AmapProperty property;
final String STATUSTYPE = "1";
final String RESULTE_INFO = "OK";
final String OUTPUT = "JSON";
final String EXTENSIONS_ALL = "all";
/**
*
* @description 根据经纬度查地址
* @param lng:经度,lat:纬度
* @return 地址
* @author leiyj
* @date 2019年1月14日
*/
public String getAddrFromLngLat(String lng, String lat){
Map<String, String> params = new HashMap<String, String>(10);
params.put("location", lng + "," + lat);
params.put("output", OUTPUT);
params.put("key", property.getKey());
params.put("extensions", EXTENSIONS_ALL);
String result = null;
try {
result = HttpUtil.post(property.getGeocodeUrl(),params);
} catch (IOException e) {
logger.error("通过经纬度获取详细地址异常:" + e.getMessage() + e);
}
if(result == null){
logger.info("返回地址为空");
return "";
}
JSONObject json = JSONObject.fromObject(result);
String status = json.getString("status");
logger.info("解析地址的状态为:" + status);
String address = null;
if (STATUSTYPE.equals(status)) {
JSONObject regeocode = JSONObject.fromObject(json.get("regeocode"));
address = regeocode.getString("formatted_address");
}
return address;
}
/**
*
* @description 根据经纬度查地址
* @param lng:经度,lat:纬度
* @return 地址
* @author leiyj
* @date 2019年1月14日
*/
public AmapRegeoResponse getRegeoFromLngLat(String lng, String lat){
Map<String, String> params = new HashMap<String, String>(10);
params.put("location", lng + "," + lat);
params.put("output", OUTPUT);
params.put("key", property.getKey());
params.put("extensions", EXTENSIONS_ALL);
String result = null;
try {
result = HttpUtil.post(property.getGeocodeUrl(),params);
} catch (IOException e) {
logger.error("通过经纬度获取详细地址异常:" + e.getMessage() + e);
}
if(result == null){
logger.info("返回地址为空");
return null;
}
JSONObject json = JSONObject.fromObject(result);
String status = json.getString("status");
logger.info("解析地址的状态为:" + status);
AmapRegeoResponse dto = new AmapRegeoResponse();
if (STATUSTYPE.equals(status)) {
JSONObject regeocode = JSONObject.fromObject(json.get("regeocode"));
JSONObject addressComponent = regeocode.getJSONObject("addressComponent");
logger.info("addressComponent:" + addressComponent);
dto.setProvince(addressComponent.getString("province"));
dto.setCity(addressComponent.getString("city"));
dto.setDistrict(addressComponent.getString("district"));
}
return dto;
}
/**
*
* @description 根据起点和终点经纬度查询距离
* @param origins:起点经纬度,destination:终点经纬度
* @return 地址
* @author leiyj
* @date 2019年1月14日
*/
public Double getDistance(String origins, String destination){
Map<String, String> params = new HashMap<String, String>(10);
params.put("origins", origins);
params.put("destination", destination);
params.put("output", OUTPUT);
params.put("key", property.getKey());
params.put("type", "0");
String result = null;
try {
result = HttpUtil.post(property.getDistanceUrl(),params);
} catch (IOException e) {
logger.error("经纬度计算距离异常:" + e.getMessage() + e);
}
if(result == null){
logger.info("返回计算距离为空");
return 0D;
}
Double distance = 0D;
logger.info(result);
JSONObject json = JSONObject.fromObject(result);
String status = json.getString("status");
String info = json.getString("info");
// logger.info("据起点和终点经纬度查询返回状态:" + status);
if (STATUSTYPE.equals(status)) {
JSONArray results = JSONArray.fromObject(json.get("results"));
String r = results.getString(0);
JSONObject json1 = JSONObject.fromObject(r);
distance = Double.parseDouble(json1.getString("distance"));
logger.info("俩地相隔的距离:" + distance + "米");
}
return distance/1000;
}
}
package cn.com.glsx.dj.device.manager;
import org.oreframework.util.http.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import cn.com.glsx.dj.device.request.outDeviceInfo.PushDeviceToWgRequest;
import cn.com.glsx.dj.device.response.WgBaseResponse;
import cn.com.glsx.framework.core.enums.DefaultErrorEnum;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Component
public class WgApiManager {
@Autowired
private Environment env;
public WgBaseResponse pushDevice(PushDeviceToWgRequest request) {
request.setAccesstoken(env.getProperty("wg.request.accesstoken"));
String url = env.getProperty("wg.push.device.info.url");//"https://49av0in52014.vicp.fun/api/event";//
try {
String json = JSON.toJSONString(request);
log.info("pushDevice.request:{}",json);
String result = HttpUtil.postJson(url, json, 30000, "utf-8");
log.info("pushDevice.result:{}",result);
return JSON.parseObject(result, WgBaseResponse.class);
} catch (Exception e) {
log.error(e.getMessage(),e);
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR,e.getMessage());
}
}
public static void main(String[] argsr) {
PushDeviceToWgRequest request = new PushDeviceToWgRequest();
request.setAccesstoken("1ac2200a54741671125c09b5df5314d0");
request.setSn("123456");
request.setTitle("测试");
request.setContent("这是测试内容");
request.setLng("22.5648");
request.setLat("123.546");
request.setAddress("深圳市南山区桃园街道101号");
request.setSendTime("2024-07-15 13:41:03");
System.out.println( new WgApiManager().pushDevice(request));
}
}
package cn.com.glsx.dj.device.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.oreframework.datasource.mybatis.mapper.OreMapper;
import cn.com.glsx.dj.device.dto.OutDeviceEventMessageDTO;
import cn.com.glsx.dj.device.model.OutDeviceEventMessage;
@Mapper
public interface OutDeviceEventMessageMapper extends OreMapper<OutDeviceEventMessage> {
List<OutDeviceEventMessageDTO> list(OutDeviceEventMessageDTO condition);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.dj.device.mapper;
import cn.com.glsx.dj.device.model.OutDeviceInfo;
import org.apache.ibatis.annotations.Mapper;
import org.oreframework.datasource.mybatis.mapper.OreMapper;
@Mapper
public interface OutDeviceInfoMapper extends OreMapper<OutDeviceInfo> {
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.dj.device.queue;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.oreframework.jms.kafka.consumer.ConsumerProperty;
import org.oreframework.jms.kafka.consumer.KafkaConsumer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import com.alibaba.nacos.common.utils.Objects;
import cn.com.glsx.dj.device.converter.OutDeviceInfoConvert;
import cn.com.glsx.dj.device.manager.AmapManager;
import cn.com.glsx.dj.device.manager.WgApiManager;
import cn.com.glsx.dj.device.model.OutDeviceEventMessage;
import cn.com.glsx.dj.device.model.OutDeviceInfo;
import cn.com.glsx.dj.device.queue.proto.AlarmProto;
import cn.com.glsx.dj.device.request.outDeviceInfo.PushDeviceToWgRequest;
import cn.com.glsx.dj.device.response.WgBaseResponse;
import cn.com.glsx.dj.device.service.OutDeviceEventMessageService;
import cn.com.glsx.dj.device.service.OutDeviceInfoService;
import cn.com.glsx.dj.device.util.BaseGeoConv;
import cn.com.glsx.dj.device.util.BaseGeoConv.LngLatObj;
import cn.com.glsx.framework.core.enums.StatusEnum;
import lombok.extern.slf4j.Slf4j;
/**
*
* @Description:碰撞事件消费
* @author zhoulm
*/
@Slf4j
@Component
public class CollideEventConsumer extends KafkaConsumer{
@Autowired
private OutDeviceEventMessageService outDeviceEventMessageService;
@Autowired
private OutDeviceInfoService outDeviceInfoService;
@Autowired
private Environment env;
@Autowired
private AmapManager amapManager;
@Autowired
private WgApiManager wgApiManager;
public CollideEventConsumer() {
super("gps_alarm_collision", false);
}
@Override
public ConsumerProperty getConsumerProperty() {
return new ConsumerProperty() {
@Override
public Properties extend(Properties properties) {
String connect = env.getProperty("spring.kafka.consumer.gps_alarm_collision.zookeeper.connect");
if(StringUtils.isNotEmpty(connect)){
properties.setProperty("zookeeper.connect", connect);
}
return properties;
}
};
}
@Override
public void processMessage(Object message) {
try {
boolean collideSwitch = env.getProperty("collide.switch", Boolean.class, true);
if(!collideSwitch){
log.info("collide switch is close");
return;
}
AlarmProto.AlarmNotifyReq alarmNotifyReq = AlarmProto.AlarmNotifyReq.parseFrom(getMessage());
log.info("gps_alarm_collision:{}",alarmNotifyReq);
if(null == alarmNotifyReq) {
return;
}
OutDeviceInfo outDeviceInfo = outDeviceInfoService.getBySn(alarmNotifyReq.getDevicesn());
if(Objects.isNull(outDeviceInfo)) {
log.info("sn:{}不在此设备库,该事件不予处理");
return ;
}
OutDeviceEventMessage event = new OutDeviceEventMessage();
event.setSn(alarmNotifyReq.getDevicesn());
event.setLng(String.valueOf(Double.valueOf(alarmNotifyReq.getLongitude()) / 1000000));
event.setLat(String.valueOf(Double.valueOf(alarmNotifyReq.getLatitude()) / 1000000));
event.setEventDate(new Date(alarmNotifyReq.getGpstime() * 1000L));
event.setType(10);//碰撞消息
event.setTaskId(alarmNotifyReq.getTaskId());
setAddress(event);
event.setTitle("碰撞提醒");
event.setContent(MessageFormat.format("您的设备[{0}]在{1}疑似发生事故,请及时确定实情",event.getSn(),event.getAddress()));
boolean pushResult = push(OutDeviceInfoConvert.INSTANCE.toPushDeviceToWgRequest(event));
event.setPushSuccessFlag(pushResult ? StatusEnum.YES.getValue():StatusEnum.NO.getValue());
event = outDeviceEventMessageService.insert(event);
log.info("receive rescue event success:{}", event);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
private void setAddress(OutDeviceEventMessage event) {
try {
LngLatObj gLngLat = BaseGeoConv.transform(event.getLng() + "," + event.getLat());//将gps坐标转换为谷歌坐标
String address = amapManager.getAddrFromLngLat(String.valueOf(gLngLat.getLng()), String.valueOf(gLngLat.getLat()));
log.info("原始坐标:{},高德坐标:{},address:{}",event.getLng() + "," + event.getLat(),gLngLat.getLngLat(),address);
event.setAddress(address);
}catch(Exception e) {
log.error(e.getMessage(),e);
}
}
private boolean push(PushDeviceToWgRequest request) {
try {
WgBaseResponse wgBaseResponse = wgApiManager.pushDevice(request);
return wgBaseResponse != null && wgBaseResponse.isSuccess();
}catch(Exception e) {
log.error(e.getMessage(),e);
}
return false;
}
}
package cn.com.glsx.dj.device.remote;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import cn.com.glsx.dj.device.model.OutDeviceInfo;
import cn.com.glsx.dj.device.service.OutDeviceInfoService;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import lombok.extern.slf4j.Slf4j;
@DubboService(validation = "true",version = "1.0.0")
@Slf4j
public class OutDeviceInfoRemoteImpl implements OutDeviceInfoRemote {
@Autowired
private OutDeviceInfoService outDeviceInfoService;
@Override
public RpcResponse<OutDeviceInfo> insert(@NotNull OutDeviceInfo info) {
try{
return RpcResponse.success(outDeviceInfoService.insert(info));
}catch(Exception e){
log.error(e.getMessage(),e);
return RpcResponse.error(e);
}
}
@Override
public RpcResponse<OutDeviceInfo> getBySn(@NotBlank String sn) {
try{
return RpcResponse.success(outDeviceInfoService.getBySn(sn));
}catch(Exception e){
log.error(e.getMessage(),e);
return RpcResponse.error(e);
}
}
}
package cn.com.glsx.dj.device.request.outDeviceInfo;
import java.io.Serializable;
import javax.validation.constraints.NotBlank;
import lombok.Data;
import lombok.ToString;
@Data
@ToString
public class DeviceRegisterRequest implements Serializable{/**
*
*/
private static final long serialVersionUID = -3971631001076486283L;
@NotBlank(message = "不能为空")
private String sn;
@NotBlank(message = "不能为空")
private String sourceType;
}
package cn.com.glsx.dj.device.request.outDeviceInfo;
import java.io.Serializable;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
@Data
@ToString
public class PushDeviceToWgRequest implements Serializable{/**
*
*/
private static final long serialVersionUID = -2600172236703718193L;
@ApiModelProperty(notes = "鉴权令牌")
private String accesstoken;
@ApiModelProperty(notes = "设备号")
private String sn;
@ApiModelProperty(notes = "标题")
private String title;
@ApiModelProperty(notes = "消息内容")
private String content;
@ApiModelProperty(notes = "经度")
private String lng;
@ApiModelProperty(notes = "纬度")
private String lat;
@ApiModelProperty(notes = "碰撞发生的地址")
private String address;
@ApiModelProperty(notes = "消息类型(10-碰撞消息)")
private Integer type = 10;
@ApiModelProperty(notes = "消息发送时间|碰撞发生时间")
private String sendTime;
}
package cn.com.glsx.dj.device.response;
import java.io.Serializable;
import lombok.Data;
import lombok.ToString;
@Data
@ToString
public class AmapRegeoResponse implements Serializable{
/**
*
*/
private static final long serialVersionUID = -1116313663363605725L;
private String province;
private String city;
private String district;
}
package cn.com.glsx.dj.device.response;
import java.io.Serializable;
import java.util.Objects;
import lombok.Data;
import lombok.ToString;
@Data
@ToString
public class WgBaseResponse implements Serializable{/**
*
*/
private static final long serialVersionUID = -8660800586414488398L;
public static final int SUCCESS_CODE = 0;
private Integer code;
private String message;
public boolean isSuccess() {
return Objects.equals(code, SUCCESS_CODE);
}
}
package cn.com.glsx.dj.device.service;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import cn.com.glsx.dj.device.dto.OutDeviceEventMessageDTO;
import cn.com.glsx.dj.device.mapper.OutDeviceEventMessageMapper;
import cn.com.glsx.dj.device.model.OutDeviceEventMessage;
import cn.com.glsx.framework.core.beans.BaseModel.DeletedFlagEnum;
import cn.com.glsx.framework.core.enums.DefaultErrorEnum;
import cn.com.glsx.framework.core.enums.StatusEnum;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import cn.com.glsx.framework.core.util.RpcAssert;
import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;
@Service
@Slf4j
@Transactional(propagation = Propagation.SUPPORTS, rollbackFor = {RpcServiceException.class})
public class OutDeviceEventMessageService {
@Autowired
private OutDeviceEventMessageMapper outDeviceEventMessageMapper;
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {RpcServiceException.class})
public OutDeviceEventMessage insert(OutDeviceEventMessage info) {
RpcAssert.assertNotNull(info, DefaultErrorEnum.PARAMETER_NULL);
RpcAssert.assertNotEmpty(info.getSn(), DefaultErrorEnum.PARAMETER_NULL,"sn must not be null");
RpcAssert.assertNotEmpty(info.getTitle(), DefaultErrorEnum.PARAMETER_NULL,"title must not be null");
RpcAssert.assertNotEmpty(info.getContent(), DefaultErrorEnum.PARAMETER_NULL,"content must not be null");
RpcAssert.assertNotNull(info.getType(), DefaultErrorEnum.PARAMETER_NULL,"type must not be null");
log.info("OutDeviceEventMessage:{}",info);
try{
if(StringUtils.isBlank(info.getPushSuccessFlag())) {
info.setPushSuccessFlag(StatusEnum.NO.getValue());
}
info.setCreatedDate(new Date());
info.setUpdatedDate(info.getCreatedDate());
info.setDeletedFlag(DeletedFlagEnum.N.name());
outDeviceEventMessageMapper.insertUseGeneratedKeys(info);
return info;
}catch(Exception e){
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR, e);
}
}
public List<OutDeviceEventMessageDTO> list(OutDeviceEventMessageDTO condition){
RpcAssert.assertNotNull(condition, DefaultErrorEnum.PARAMETER_NULL);
try{
return outDeviceEventMessageMapper.list(condition);
}catch(Exception e){
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR, e);
}
}
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {RpcServiceException.class})
public boolean updatePushSuccess(String sn) {
RpcAssert.assertNotEmpty(sn, DefaultErrorEnum.PARAMETER_NULL,"sn must not be null");
log.info("updatePushSuccess:{}",sn);
try{
OutDeviceEventMessage info = OutDeviceEventMessage.builder().updatedDate(new Date())
.pushSuccessFlag(StatusEnum.YES.getValue())
.build();
Example example = new Example(OutDeviceEventMessage.class);
example.createCriteria().andEqualTo("sn", sn)
.andEqualTo("pushSuccessFlag", StatusEnum.NO.getValue())
.andEqualTo("deletedFlag", DeletedFlagEnum.N.name());
return outDeviceEventMessageMapper.updateByExampleSelective(info, example) > 0;
}catch(Exception e){
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR, e);
}
}
}
package cn.com.glsx.dj.device.service;
import java.util.Date;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.oreframework.distribute.lock.annotation.GlsxDistributeLockable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import cn.com.glsx.dj.device.mapper.OutDeviceInfoMapper;
import cn.com.glsx.dj.device.model.OutDeviceInfo;
import cn.com.glsx.framework.core.beans.BaseModel.DeletedFlagEnum;
import cn.com.glsx.framework.core.enums.DefaultErrorEnum;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import cn.com.glsx.framework.core.util.RpcAssert;
import lombok.extern.slf4j.Slf4j;
@Service
@Slf4j
@Transactional(propagation = Propagation.SUPPORTS, rollbackFor = {RpcServiceException.class})
public class OutDeviceInfoService {
@Lazy
@Autowired
private OutDeviceInfoService thiz;
@Autowired
private OutDeviceInfoMapper outDeviceInfoMapper;
@GlsxDistributeLockable(name="'OutDeviceInfoService_insert' + #info.sn",timeoutException=RpcServiceException.class)
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {RpcServiceException.class})
public OutDeviceInfo insert(OutDeviceInfo info) {
RpcAssert.assertNotNull(info, DefaultErrorEnum.PARAMETER_NULL);
RpcAssert.assertNotEmpty(info.getSn(), DefaultErrorEnum.PARAMETER_NULL,"sn must not be null");
RpcAssert.assertNotEmpty(info.getSourceType(), DefaultErrorEnum.PARAMETER_NULL,"sourceType must not be null");
log.info("OutDeviceInfo:{}",info);
try{
OutDeviceInfo old = thiz.getBySn(info.getSn());
if(old != null) {
return old;
}
info.setCreatedDate(new Date());
info.setUpdatedDate(info.getCreatedDate());
info.setDeletedFlag(DeletedFlagEnum.N.name());
outDeviceInfoMapper.insertUseGeneratedKeys(info);
return info;
}catch(Exception e){
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR, e);
}
}
public OutDeviceInfo getBySn(String sn) {
RpcAssert.assertNotEmpty(sn, DefaultErrorEnum.PARAMETER_NULL,"sn must not be null");
try{
OutDeviceInfo condition = OutDeviceInfo.builder().sn(sn).deletedFlag(DeletedFlagEnum.N.name()).build();
List<OutDeviceInfo> list = outDeviceInfoMapper.select(condition);
if(CollectionUtils.isNotEmpty(list)) {
return list.get(0);
}
return null;
}catch(Exception e){
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR, e);
}
}
}
package cn.com.glsx.dj.device.util;
import static java.lang.Math.*;
/**
* @Title: GeoConv工具类
* @Description:GeoConv工具类
* @author huanggl
* @version V1.0
* @Company: Didihu.com.cn
* @history 2019-04-28 11:02:04
*/
public abstract class BaseGeoConv {
/**
* <p> 圆周率
*/
private static final double PI = 3.14159265358979324;
/**
* <p> WGS 长轴半径
*/
private static final double RADIUS = 6378245.0;
/**
* <p> WGS 偏心率的平方
*/
private static final double EE = 0.00669342162296594323;
private static final double X_PI = 3.14159265358979324 * 3000.0 / 180.0;
static private double transformLat(double x, double y){
double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * sqrt(abs(x));
ret += (20.0 * sin(6.0 * x * PI) + 20.0 * sin(2.0 * x * PI)) * 2.0 / 3.0;
ret += (20.0 * sin(y * PI) + 40.0 * sin(y / 3.0 * PI)) * 2.0 / 3.0;
ret += (160.0 * sin(y / 12.0 * PI) + 320 * sin(y * PI / 30.0)) * 2.0 / 3.0;
return ret;
}
static private double transformLng(double x, double y){
double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * sqrt(abs(x));
ret += (20.0 * sin(6.0 * x * PI) + 20.0 * sin(2.0 * x * PI)) * 2.0 / 3.0;
ret += (20.0 * sin(x * PI) + 40.0 * sin(x / 3.0 * PI)) * 2.0 / 3.0;
ret += (150.0 * sin(x / 12.0 * PI) + 300.0 * sin(x / 30.0 * PI)) * 2.0 / 3.0;
return ret;
}
static public LngLatObj transform(String lngLat){
double wgLng = Double.parseDouble(lngLat.split(",")[0]);
double wgLat = Double.parseDouble(lngLat.split(",")[1]);
double dLat = transformLat(wgLng - 105.0, wgLat - 35.0);
double dLon = transformLng(wgLng - 105.0, wgLat - 35.0);
double radLat = wgLat/180.0 * PI;
double magic = sin(radLat);
magic = 1 - EE * magic * magic;
double sqrtMagic = sqrt(magic);
dLat = (dLat * 180.0) / ((RADIUS * (1 - EE)) / (magic * sqrtMagic) * PI);
dLon = (dLon * 180.0) / (RADIUS / sqrtMagic * cos(radLat) * PI);
return new LngLatObj(wgLng + dLon, wgLat + dLat);
}
public static double transformGGLat(double wgLng, double wgLat){
double dLat = transformLat(wgLng - 105.0, wgLat - 35.0);
double radLat = wgLat/180.0 * PI;
double magic = sin(radLat);
magic = 1 - EE * magic * magic;
double sqrtMagic = sqrt(magic);
dLat = (dLat * 180.0) / ((RADIUS * (1 - EE)) / (magic * sqrtMagic) * PI);
return wgLat + dLat;
}
public static double transformGGLng(double wgLng, double wgLat){
double dLon = transformLng(wgLng - 105.0, wgLat - 35.0);
double radLat = wgLat/180.0 * PI;
double magic = sin(radLat);
magic = 1 - EE * magic * magic;
double sqrtMagic = sqrt(magic);
dLon = (dLon * 180.0) / (RADIUS / sqrtMagic * cos(radLat) * PI);
return wgLng + dLon;
}
public static void main(String[] args) {
System.out.println(BaseGeoConv.transformGGLng(119.63177,32.291477) + "," + BaseGeoConv.transformGGLat(119.63177,32.291477));
System.out.println(BaseGeoConv.transform("119.63177,32.291477"));
//System.out.println(GeoConv.transform("113.874829,22.569914").getLng() + ", " + GeoConv.transform("113.874829,22.569914").getLat());
//System.out.println(GeoConv.transform("114.398416,38.058380").getLngLat());
String kk = BaseGeoConv.transform("103.992372,30.63103").getLngLat();
double lat0 = Double.parseDouble(kk.split(",")[1]);
double lon0 = Double.parseDouble(kk.split(",")[0]);
//104.14635851597282,31.086821202789974
//103.992372 30.63103
//String aa = GeoConv.transform("103.992372,30.63103").getLngLat();
double lat1 = 31.086821202789974;
double lon1 = 104.14635851597282;
double[] bearings = new double[3];
BearingToUtils.computeDistanceAndBearing(lat0,lon0,lat1,lon1,bearings);
System.out.println(bearings[1]);
System.out.println(bearings[2]);
double bearing = 0;
if(bearings[1] < 0) {
bearing = 360 - Math.abs(bearings[1]);
} else {
bearing = bearings[1];
}
/*
String azimuthDesc = "";
if(bearing > 0.0 && bearing <= 10.0) {
azimuthDesc="北方";
} else if(bearing > 10.0 && bearing <= 80.0) {
azimuthDesc="东北";
} else if(bearing > 80.0 && bearing <= 100.0) {
azimuthDesc="东方";
} else if(bearing > 100.0 && bearing <= 170.0) {
azimuthDesc="东南";
} else if(bearing > 170.0 && bearing <= 190.0) {
azimuthDesc="南方";
} else if(bearing > 190.0 && bearing <= 260.0) {
azimuthDesc="西南";
} else if(bearing > 260.0 && bearing <= 280.0) {
azimuthDesc="西方";
} else if(bearing > 280.0 && bearing <= 350.0) {
azimuthDesc="西北";
} else if(bearing > 350.0 && bearing <= 360.0) {
azimuthDesc="北方";
}
*/
System.out.println(bearing);
//System.out.println(azimuthDesc);
//System.out.println(GeoConv.transformGGLng(113.938671,22.551195) + "," + GeoConv.transformGGLat(113.938671,22.551195));
}
static public class LngLatObj {
private double lng;
private double lat;
LngLatObj(double lng, double lat) {
this.lng = lng;
this.lat = lat;
}
public double getLng() {
return lng;
}
public double getLat() {
return lat;
}
public String getLngLat(){
return lng + "," + lat;
}
@Override
public String toString() {
return "LngLatObj [lng=" + lng + ", lat=" + lat + "]";
}
}
}
package cn.com.glsx.dj.device.util;
/**
* @Title: 计算方位角工具类
* @Description:计算方位角工具类
* @author huanggl
* @version V1.0
* @Company: Didihu.com.cn
* @history 2019-5-1
*/
public class BearingToUtils {
private static int COUNT2 = 2;
public static void computeDistanceAndBearing(double lat1, double lon1,double lat2, double lon2, double[] results) {
int maxIters = 20;
lat1 *= Math.PI / 180.0;
lat2 *= Math.PI / 180.0;
lon1 *= Math.PI / 180.0;
lon2 *= Math.PI / 180.0;
double a = 6378137.0;
double b = 6356752.3142;
double f = (a - b) / a;
double aSqMinusBSqOverBSq = (a * a - b * b) / (b * b);
double l = lon2 - lon1;
double zheOne = 0.0;
double u1 = Math.atan((1.0 - f) * Math.tan(lat1));
double u2 = Math.atan((1.0 - f) * Math.tan(lat2));
double cosU1 = Math.cos(u1);
double cosU2 = Math.cos(u2);
double sinU1 = Math.sin(u1);
double sinU2 = Math.sin(u2);
double cosU1cosU2 = cosU1 * cosU2;
double sinU1sinU2 = sinU1 * sinU2;
double sigma = 0.0;
double deltaSigma = 0.0;
double cosSqAlpha = 0.0;
double cos2SM = 0.0;
double cosSigma = 0.0;
double sinSigma = 0.0;
double cosLambda = 0.0;
double sinLambda = 0.0;
double lambda = l;
for (int iter = 0; iter < maxIters; iter++) {
double lambdaOrig = lambda;
cosLambda = Math.cos(lambda);
sinLambda = Math.sin(lambda);
double t1 = cosU2 * sinLambda;
double t2 = cosU1 * sinU2 - sinU1 * cosU2 * cosLambda;
double sinSqSigma = t1 * t1 + t2 * t2;
sinSigma = Math.sqrt(sinSqSigma);
cosSigma = sinU1sinU2 + cosU1cosU2 * cosLambda;
sigma = Math.atan2(sinSigma, cosSigma);
double sinAlpha = (sinSigma == 0) ? 0.0 : cosU1cosU2 * sinLambda / sinSigma;
cosSqAlpha = 1.0 - sinAlpha * sinAlpha;
cos2SM = (cosSqAlpha == 0) ? 0.0 : cosSigma - 2.0 * sinU1sinU2 / cosSqAlpha;
double uSquared = cosSqAlpha * aSqMinusBSqOverBSq;
zheOne = 1 + (uSquared / 16384.0) * (4096.0 + uSquared * (-768 + uSquared * (320.0 - 175.0 * uSquared)));
double theTwo = (uSquared / 1024.0) * (256.0 + uSquared * (-128.0 + uSquared * (74.0 - 47.0 * uSquared)));
double theThree = (f / 16.0) * cosSqAlpha * (4.0 + f * (4.0 - 3.0 * cosSqAlpha));
double cos2SMSq = cos2SM * cos2SM;
deltaSigma = theTwo * sinSigma * (cos2SM + (theTwo / 4.0) * (cosSigma * (-1.0 + 2.0 * cos2SMSq) - (theTwo / 6.0) * cos2SM * (-3.0 + 4.0 * sinSigma * sinSigma) * (-3.0 + 4.0 * cos2SMSq)));
lambda = l + (1.0 - theThree) * f * sinAlpha * (sigma + theThree * sinSigma * (cos2SM + theThree * cosSigma * (-1.0 + 2.0 * cos2SM * cos2SM)));
double delta = (lambda - lambdaOrig) / lambda;
if (Math.abs(delta) < 1.0e-12) {
break;
}
}
double distance = (b * zheOne * (sigma - deltaSigma));
results[0] = distance;
if (results.length > 1) {
double initialBearing = (float) Math.atan2(cosU2 * sinLambda,cosU1 * sinU2 - sinU1 * cosU2 * cosLambda);
initialBearing *= 180.0 / Math.PI;
results[1] = initialBearing;
if (results.length > COUNT2) {
double finalBearing = (float) Math.atan2(cosU1 * sinLambda, -sinU1 * cosU2 + cosU1 * sinU2 * cosLambda);
finalBearing *= 180.0 / Math.PI;
results[2] = finalBearing;
}
}
}
}
package cn.com.glsx.dj.device.util;
import javax.servlet.http.HttpServletRequest;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.framework.rop.response.RopResponse;
public class CommonUtil {
public static<T> RopResponse<T> convertRopResponse(RpcResponse<T> rpcRes){
return RopResponse.result(rpcRes);
}
public static<T,V> RopResponse<V> convertRopResponse(RpcResponse<T> rpcRes,ConvertHandler<T,V> handler){
if(rpcRes.isSuccess()) {
return RopResponse.success(handler.convert(rpcRes.getResult()));
}
return RopResponse.error(rpcRes);
}
public static String getIpAddr(HttpServletRequest request){
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Forwarded-For");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if(ip!=null){
String[] ss=ip.split(",");
if(ss.length>0){
return ss[0];
}
}
return ip;
}
}
package cn.com.glsx.dj.device.util;
public interface ConvertHandler<T,V> {
V convert(T source);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.com.glsx.dj.device.mapper.OutDeviceEventMessageMapper" >
<resultMap id="BaseResultMap" type="cn.com.glsx.dj.device.model.OutDeviceEventMessage" >
<!--
WARNING - @mbg.generated
-->
<id column="id" property="id" jdbcType="INTEGER" />
<result column="sn" property="sn" jdbcType="VARCHAR" />
<result column="title" property="title" jdbcType="VARCHAR" />
<result column="content" property="content" jdbcType="VARCHAR" />
<result column="type" property="type" jdbcType="INTEGER" />
<result column="address" property="address" jdbcType="VARCHAR" />
<result column="lng" property="lng" jdbcType="VARCHAR" />
<result column="lat" property="lat" jdbcType="VARCHAR" />
<result column="event_date" property="eventDate" jdbcType="TIMESTAMP" />
<result column="task_id" property="taskId" jdbcType="VARCHAR" />
<result column="push_success_flag" property="pushSuccessFlag" jdbcType="VARCHAR" />
<result column="created_date" property="createdDate" jdbcType="TIMESTAMP" />
<result column="updated_date" property="updatedDate" jdbcType="TIMESTAMP" />
<result column="deleted_flag" property="deletedFlag" jdbcType="CHAR" />
</resultMap>
<resultMap id="DTOResultMap" type="cn.com.glsx.dj.device.dto.OutDeviceEventMessageDTO" extends="BaseResultMap">
</resultMap>
<sql id="Base_Column_List" >
<!--
WARNING - @mbg.generated
-->
id, sn, title, content, type, address, lng, lat, event_date,task_id,push_success_flag,
created_date, updated_date, deleted_flag
</sql>
<select id="list" parameterType="cn.com.glsx.dj.device.dto.OutDeviceEventMessageDTO" resultMap="DTOResultMap">
select
dem.id, dem.sn, dem.title, dem.content, dem.type, dem.address, dem.lng, dem.lat, dem.event_date,dem.task_id,
dem.push_success_flag,dem.created_date, dem.updated_date
from dj_out_device_event_message dem
left join dj_out_device_info di on di.sn=dem.sn and di.deleted_flag='N'
<where>
dem.deleted_flag='N'
<if test="sourceType != null and sourceType !=''">
and di.source_type = #{sourceType}
</if>
<if test="pushSuccessFlag != null and pushSuccessFlag !=''">
and dem.push_success_flag = #{pushSuccessFlag}
</if>
</where>
</select>
</mapper>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.com.glsx.dj.device.mapper.OutDeviceInfoMapper" >
<resultMap id="BaseResultMap" type="cn.com.glsx.dj.device.model.OutDeviceInfo" >
<!--
WARNING - @mbg.generated
-->
<id column="id" property="id" jdbcType="INTEGER" />
<result column="sn" property="sn" jdbcType="VARCHAR" />
<result column="source_type" property="sourceType" jdbcType="VARCHAR" />
<result column="created_date" property="createdDate" jdbcType="TIMESTAMP" />
<result column="updated_date" property="updatedDate" jdbcType="TIMESTAMP" />
<result column="deleted_flag" property="deletedFlag" jdbcType="CHAR" />
</resultMap>
<sql id="Base_Column_List" >
<!--
WARNING - @mbg.generated
-->
id, sn, source_type, created_date, updated_date, deleted_flag
</sql>
</mapper>
\ No newline at end of file \ No newline at end of file
server.port=8119
server.display-name=rpc-dj-device
server.servlet.context-path=/rpc-dj-device
server.servlet.application-display-name=rpc-dj-device
logging.config=classpath:logback.xml
logging.path=/data/java_log/jetty/rpc-dj-device/rpc-dj-device.log
logging.level.root=INFO
ore.starter.class-name=Main
# diamond config
ore.diamond.group=dijia
ore.diamond.dataId=rpc-dj-device
ore.diamond.env=release
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<property resource="config/application.properties" />
<property name="APP_NAME" value="${server.display-name}" />
<property name="LOG_PATH" value="${logging.path}" />
<property name="LOG_LEVEL" value="${logging.level}" />
<contextName>${APP_NAME}</contextName>
<turboFilter class="org.oreframework.boot.logging.logback.OreBootTurboFilter">
<Marker>oreframework</Marker>
</turboFilter>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<layout class="org.oreframework.commons.log.OrePatternLayout">
<pattern>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [${APP_NAME}] [%traceid] [%thread] %-5level [%logger{36}.%method %line] - %msg%n</pattern>
</pattern>
</layout>
</appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- <Encoding> Label Old version of this label can not be used -->
<!-- <Encoding>UTF-8</Encoding> -->
<File>${LOG_PATH}</File>
<!-- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> -->
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<FileNamePattern>${LOG_PATH}.%d{yyyy-MM-dd}.%i</FileNamePattern>
<MaxHistory>15</MaxHistory>
<maxFileSize>200MB</maxFileSize>
</rollingPolicy>
<layout class="org.oreframework.commons.log.OrePatternLayout">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [${APP_NAME}] [%traceid] [%thread] %-5level [%logger{36}.%method %line] - %msg%n</pattern>
</layout>
<!-- 根据文件大小滚动,不支持 SizeBasedTriggeringPolicy 这种配置-->
<!-- <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>200MB</MaxFileSize>
</triggeringPolicy> -->
</appender>
<!-- druid连接池慢查询日志记录 -->
<appender name="DruidFILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${LOG_PATH}.druid_slow_sql</file>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 归档的日志文件的路径,例如今天是2020-01-01日志,当前写的日志文件路径为file节点指定,可以将此文件与file指定文件路径设置为不同路径,从而将当前日志文件或归档日志文件置不同的目录。
而2020-01-01的日志文件在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引 -->
<fileNamePattern>${LOG_PATH}.druid_slow_sql-%d{yyyy-MM-dd}.%i</fileNamePattern>
<!-- 除按日志记录之外,还配置了日志文件不能超过2M,若超过2M,日志文件会以索引0开始,命名日志文件,例如log-error-2020-01-01.0.log -->
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>200MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<!-- 追加方式记录日志 -->
<append>true</append>
<!-- 日志文件的格式 -->
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n</pattern>
<charset>utf-8</charset>
</encoder>
<!-- 此日志文件只记录级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<root level="${LOG_LEVEL}">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
<appender-ref ref="DruidFILE" />
</root>
</configuration>
\ No newline at end of file \ No newline at end of file
#!/bin/bash
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
DEPLOY_DIR=`pwd`
CONF_DIR=$DEPLOY_DIR/classes
SERVER_NAME=`sed '/application.name/!d;s/.*=//' classes/config/application.properties | tr -d '\r'`
#LOGS_FILE=`sed '/log4j.appender.logToFile.File/!d;s/.*=//' classes/log4j.properties | tr -d '\r'`
LOGS_FILE=`sed '/name="LOG_PATH"/!d;s/.*value="\(.*\)".*/\1/g' classes/logback.xml`
if [ -z "$SERVER_NAME" ]; then
SERVER_NAME=`hostname`
fi
PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
if [ -z "$PIDS" ]; then
echo "ERROR: The $SERVER_NAME does not started!"
exit 1
fi
LOGS_DIR=""
if [ -n "$LOGS_FILE" ]; then
LOGS_DIR=`dirname $LOGS_FILE`
else
LOGS_DIR=$DEPLOY_DIR/logs
fi
if [ ! -d $LOGS_DIR ]; then
mkdir $LOGS_DIR
fi
DUMP_DIR=$LOGS_DIR/dump
if [ ! -d $DUMP_DIR ]; then
mkdir $DUMP_DIR
fi
DUMP_DATE=`date +%Y%m%d%H%M%S`
DATE_DIR=$DUMP_DIR/$DUMP_DATE
if [ ! -d $DATE_DIR ]; then
mkdir $DATE_DIR
fi
echo -e "Dumping the $SERVER_NAME ...\c"
for PID in $PIDS ; do
jstack $PID > $DATE_DIR/jstack-$PID.dump 2>&1
echo -e ".\c"
jinfo $PID > $DATE_DIR/jinfo-$PID.dump 2>&1
echo -e ".\c"
jstat -gcutil $PID > $DATE_DIR/jstat-gcutil-$PID.dump 2>&1
echo -e ".\c"
jstat -gccapacity $PID > $DATE_DIR/jstat-gccapacity-$PID.dump 2>&1
echo -e ".\c"
jmap $PID > $DATE_DIR/jmap-$PID.dump 2>&1
echo -e ".\c"
jmap -heap $PID > $DATE_DIR/jmap-heap-$PID.dump 2>&1
echo -e ".\c"
jmap -histo $PID > $DATE_DIR/jmap-histo-$PID.dump 2>&1
echo -e ".\c"
if [ -r /usr/sbin/lsof ]; then
/usr/sbin/lsof -p $PID > $DATE_DIR/lsof-$PID.dump
echo -e ".\c"
fi
done
if [ -r /bin/netstat ]; then
/bin/netstat -an > $DATE_DIR/netstat.dump 2>&1
echo -e ".\c"
fi
if [ -r /usr/bin/iostat ]; then
/usr/bin/iostat > $DATE_DIR/iostat.dump 2>&1
echo -e ".\c"
fi
if [ -r /usr/bin/mpstat ]; then
/usr/bin/mpstat > $DATE_DIR/mpstat.dump 2>&1
echo -e ".\c"
fi
if [ -r /usr/bin/vmstat ]; then
/usr/bin/vmstat > $DATE_DIR/vmstat.dump 2>&1
echo -e ".\c"
fi
if [ -r /usr/bin/free ]; then
/usr/bin/free -t > $DATE_DIR/free.dump 2>&1
echo -e ".\c"
fi
if [ -r /usr/bin/sar ]; then
/usr/bin/sar > $DATE_DIR/sar.dump 2>&1
echo -e ".\c"
fi
if [ -r /usr/bin/uptime ]; then
/usr/bin/uptime > $DATE_DIR/uptime.dump 2>&1
echo -e ".\c"
fi
echo "OK!"
echo "DUMP: $DATE_DIR"
#!/bin/bash
ENV=$1
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
cd `dirname $0`
./stop.sh
./start.sh $ENV
\ No newline at end of file \ No newline at end of file
#!/bin/bash
cd `dirname $0`
if [ "$1" = "start" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./start.sh $ENV
else
if [ "$1" = "stop" ]; then
./stop.sh
else
if [ "$1" = "debug" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./start.sh $ENV debug
else
if [ "$1" = "restart" ]; then
ENV=$2
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
./restart.sh $ENV
else
if [ "$1" = "dump" ]; then
./dump.sh
else
echo "ERROR: Please input argument: start or stop or debug or restart or dump"
exit 1
fi
fi
fi
fi
fi
#!/bin/bash
JAVA_HOME="/app/soft/jdk1.8.0_20"
ENV=$1
if [ -z "$ENV" ]; then
echo "ERROR:PLEASE SPEC ENV ARGS,SUCH AS dev,test,beta,release.. "
echo "app exit"
exit 1
fi
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
DEPLOY_DIR=`pwd`
CONF_DIR=$DEPLOY_DIR/classes
SERVER_NAME=`sed '/server.display-name/!d;s/.*=//' classes/config/application.properties | tr -d '\r'`
SERVER_PORT=`sed '/server.port/!d;s/.*=//' classes/config/application.properties | tr -d '\r'`
#LOGS_FILE=`sed '/log4j.appender.logToFile.File/!d;s/.*=//' classes/log4j.properties | tr -d '\r'`
LOGS_FILE=`sed '/logging.path/!d;s/.*=//' classes/config/application.properties | tr -d '\r'`
if [ -z "$SERVER_NAME" ]; then
SERVER_NAME=`hostname`
fi
echo "server name is $SERVER_NAME"
echo "server port is $SERVER_PORT"
PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
if [ -n "$PIDS" ]; then
echo "ERROR: The $SERVER_NAME already started!"
echo "PID: $PIDS"
exit 1
fi
if [ -n "$SERVER_PORT" ]; then
SERVER_PORT_COUNT=`netstat -tln | grep $SERVER_PORT | wc -l`
if [ $SERVER_PORT_COUNT -gt 0 ]; then
echo "ERROR: The $SERVER_NAME port $SERVER_PORT already used!"
exit 1
fi
fi
LOGS_DIR=""
if [ -n "$LOGS_FILE" ]; then
LOGS_DIR=`dirname $LOGS_FILE`
else
LOGS_DIR=$DEPLOY_DIR/logs
fi
if [ ! -d $LOGS_DIR ]; then
mkdir $LOGS_DIR
fi
STDOUT_FILE=$LOGS_DIR/stdout.log
LIB_DIR=$DEPLOY_DIR/lib
LIB_JARS=`ls $LIB_DIR|grep .jar|awk '{print "'$LIB_DIR'/"$0}'|tr "\n" ":"`
JAVA_OPTS=" -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true "
JAVA_DEBUG_OPTS=""
if [ "$2" = "debug" ]; then
JAVA_DEBUG_OPTS=" -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n "
fi
JAVA_JMX_OPTS=""
if [ "$2" = "jmx" ]; then
JAVA_JMX_OPTS=" -Dcom.sun.management.jmxremote.port=1099 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false "
fi
JAVA_MEM_OPTS=""
BITS=`file $JAVA_HOME/bin/java | grep 64-bit`
if [ -n "$BITS" ]; then
JAVA_MEM_OPTS=" -server -Xmx1g -Xms1g -Xmn256m -XX:PermSize=128m -Xss256k -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:LargePageSizeInBytes=128m -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 "
else
JAVA_MEM_OPTS=" -server -Xms1024m -Xmx1024m -XX:PermSize=128m -XX:SurvivorRatio=2 -XX:+UseParallelGC "
fi
echo -e "Starting the $SERVER_NAME ...\c"
nohup $JAVA_HOME/bin/java $JAVA_OPTS $JAVA_MEM_OPTS $JAVA_DEBUG_OPTS $JAVA_JMX_OPTS -classpath $CONF_DIR:$LIB_JARS org.oreframework.boot.bootstrap.OreBootApplication env=$ENV > $STDOUT_FILE 2>&1 &
COUNT=0
while [ $COUNT -lt 1 ]; do
echo -e ".\c"
sleep 1
if [ -n "$SERVER_PORT" ]; then
COUNT=`netstat -an | grep $SERVER_PORT | wc -l`
else
COUNT=`ps --no-heading -C java -f --width 1000 | grep "$DEPLOY_DIR" | awk '{print $2}' | wc -l`
fi
if [ $COUNT -gt 0 ]; then
break
fi
done
echo "OK!"
PIDS=`ps --no-heading -C java -f --width 1000 | grep "$DEPLOY_DIR" | awk '{print $2}'`
echo "PID: $PIDS"
echo "STDOUT: $STDOUT_FILE"
#!/bin/bash
cd `dirname $0`
BIN_DIR=`pwd`
cd ..
DEPLOY_DIR=`pwd`
CONF_DIR=$DEPLOY_DIR/classes
SERVER_NAME=`sed '/application.name/!d;s/.*=//' classes/config/application.properties | tr -d '\r'`
if [ -z "$SERVER_NAME" ]; then
SERVER_NAME=`hostname`
fi
PIDS=`ps --no-heading -C java -f --width 1000 | grep "$CONF_DIR" |awk '{print $2}'`
if [ -z "$PIDS" ]; then
echo "ERROR: The $SERVER_NAME does not started!"
exit 1
fi
#if [ "$1" != "skip" ]; then
#$BIN_DIR/dump.sh
#fi
echo -e "Stopping the $SERVER_NAME ...\c"
for PID in $PIDS ; do
kill $PID > /dev/null 2>&1
done
COUNT=0
while [ $COUNT -lt 1 ]; do
echo -e ".\c"
sleep 1
COUNT=1
for PID in $PIDS ; do
PID_EXIST=`ps --no-heading -p $PID`
if [ -n "$PID_EXIST" ]; then
COUNT=0
break
fi
done
done
echo "OK!"
echo "PID: $PIDS"
package cn.com.glsx.dj.oss.remote;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import cn.com.glsx.dj.device.Main;
/**
* @Title: BaseRemoteTest.java
* @Description:
* @author alvin
* @date 2018年1月6日 下午3:58:33
* @version V1.0
* @Company: Didihu.com.cn
* @Copyright Copyright (c) 2015
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Main.class)
public class BaseRemoteTest {
}
package cn.com.glsx.dj.oss.service;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import cn.com.glsx.dj.device.Main;
/**
* @Title: BaseServiceTest.java
* @Description:
* @author alvin
* @date 2018年1月6日 下午1:23:03
* @version V1.0
* @Company: Didihu.com.cn
* @Copyright Copyright (c) 2015
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Main.class)
public class BaseServiceTest {
}
package cn.com.glsx.dj.oss.service;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import cn.com.glsx.dj.device.enums.DeviceEnum.SourceType;
import cn.com.glsx.dj.device.model.OutDeviceInfo;
import cn.com.glsx.dj.device.service.OutDeviceInfoService;
public class OutDeviceInfoServiceTest extends BaseServiceTest {
@Autowired
private OutDeviceInfoService outDeviceInfoService;
@Test
public void testInsert() {
OutDeviceInfo info = OutDeviceInfo.builder().sn("123456").sourceType(SourceType.WG.getValue()).build();
System.out.println(outDeviceInfoService.insert(info));
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<!-- 确保已安装mybatis generator eclipse插件 -->
<generatorConfiguration>
<context id="DB2Tables" targetRuntime="MyBatis3">
<property name="javaFileEncoding" value="UTF-8"/>
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<property name="mappers" value="org.oreframework.datasource.mybatis.mapper.OreMapper"/>
<property name="caseSensitive" value="true"/>
<property name="useActualColumnNames" value="true" />
<!--<property name="beginningDelimiter" value="`"/>-->
<!--<property name="endingDelimiter" value="`"/>-->
</plugin>
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://192.168.3.227:3306/glsx_dj?characterEncoding=utf8" userId="dev_admin" password="1f7e1ed2" />
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<javaModelGenerator targetPackage="cn.com.glsx.dj.device.model" targetProject="../rpc-dj-device-api/src/main/java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<sqlMapGenerator targetPackage="META-INF/orm" targetProject="src/main/resources">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<javaClientGenerator targetPackage="cn.com.glsx.dj.device.mapper" targetProject="MAVEN" type="XMLMAPPER">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 可配置多个 mybatis-generator:generate-->
<table tableName="dj_out_device_event_message" domainObjectName="OutDeviceEventMessage" enableSelectByExample="false" enableCountByExample="false" enableDeleteByExample="false" enableUpdateByExample="false">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
</context>
</generatorConfiguration>
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!