Commit b405fce7 by fz

1.添加异常处理

2.拦截器开放接口鉴权
3.添加接口model
4.引入平台相关的dubbo服务接口
1 parent d75b47d5
Showing 35 changed files with 821 additions and 332 deletions
......@@ -62,5 +62,11 @@
<artifactId>lombok</artifactId>
<version>${org.projectlombok.version}</version>
</dependency>
<dependency>
<groupId>cn.com.glsx.openplatform</groupId>
<artifactId>rpc-openplatform-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
......@@ -4,6 +4,12 @@ import com.glsx.config.SystemProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @Description: service基类
* @author fengzhi
* @version V1.0
*/
@Slf4j
public class BaseService {
@Autowired
......
package com.glsx.config;
import cn.com.glsx.openplatform.service.IceOpenApiService;
import org.oreframework.boot.autoconfigure.dubbo.reference.ReferenceBuilderFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Title: DubboConfig.java
* @Description: Dubbo服务注册配置
* @author deployer name
* @version V1.0
* @Company: Didihu.com.cn
* @Copyright Copyright (c) 2018
*/
@Configuration
public class DubboConfig {
@Autowired
private ReferenceBuilderFactory factory;
/**
* 注册远程服务IceOpenApiService
* @return
*/
@Bean
public IceOpenApiService rpcApiMethodRemote(){
return factory.builder(IceOpenApiService.class).check(false).timeout(30000).build();
}
}
......@@ -7,12 +7,10 @@ import org.springframework.context.annotation.Configuration;
import javax.servlet.Filter;
/**
* @author 01
* @program wrapper-demo
* @description 过滤器配置类
* @create 2018-12-24 21:06
* @since 1.0
**/
* @Description: 过滤器配置类
* @author fengzhi
* @version V1.0
*/
@Configuration
public class FilterConfig {
/**
......
......@@ -6,6 +6,12 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @Description: 拦截器配置类
* @author fengzhi
* @version V1.0
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
......@@ -15,6 +21,6 @@ public class WebConfig implements WebMvcConfigurer {
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authIntercepter)
.addPathPatterns("/**")
.excludePathPatterns("/openApi/v1.0/token/**");
.excludePathPatterns("/openApi/v1.0/token");
}
}
package com.glsx.constant;
/**
* @Description: 全局变量
* @author fengzhi
* @version V1.0
*/
public class OpenAPIConstant {
public static final String TEST_PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJLYAe7vz8bZX0/Ro1c7SxwoAmzbH85MfPTWIPl4QQ6QRoZTThlzsRqDggGsRXPc1PVXv02o6v+oC7xV8ewG4GKJJ6RScuVVcGPbgDMIrc6J3LLKl5ullUDA3+KiWrAOQ8mHD9KcO9tN8y8uii3aDQapKl4DtyThaKyx37oYJ1BJAgMBAAECgYBhpzLJ8kML6zzeOPzWIwFVLSpHuAVTzTwAGnJ9VMJ26+1qoPW8KVrq1e/cKvNZFM+uhPccryvwbpG3YrRqkTwgZoodnBe06WlQH2iqdXfeW5bXcVfcbFNMlztDO2JgXuhPHajvgb28+4bd2wHr0aQk6cDSxWo3jOUpY9eezGoY7QJBAOCLz7/wtVEH5CfbD7K6707l8NNgZbxGqs41WtVWCLoUAx3WOPj0GR6p8ns7Ng5zykn8nnO72qqfVP/s5Q6alGcCQQCnac1Jmbfa7P38Or7qZYfTIvVNUxPXiMpK5GieYFEF0FAnKtmVGvLUk70ghDKi4Bm+/RYTs+e7fX3qjgb7gYfPAkA1FFezw67YzMi+MyZu1YmkWO6oyOzDqODPhgVG0OOXOQvTjcRB9VHK0dmkD8cje3OiMbkzGoECPE/Xf6RV42yZAkBCl8ZuEXRd5El/jIqmyG5H4S78bCCHasU1Fzg6T4vLKTrI6bWVJxwSzRW9Gnjd6xCytQ+UFMsH/Hoa1BYY80RnAkEArY7J7I37JsL1L+tNaSsD7vdb/+9eSv81n5dzh2yhyMCKgMhvPbqFn3V5p6gaL5YnCjN4ulxqvay79cohnyn9+A==";
public static final String TEST_TOKEN = "yRaUk3pOtRxYLH2nNoNBXSEC4zvPicu2d6gAOh+NLXl7TIiR8kDL/aMJQcjN4LDqLAnBosahygnRro6ZCoR7KXoE0bmJ+5Ozhv3Hz+vvzUyGEjGmorIVXIlS/KkZWAwIguFYhXXSDLHwxfZZHMQxTtARAv3hpf7nM++YeGCnNUQ=";
public static final String TEST_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCS2AHu78/G2V9P0aNXO0scKAJs2x/OTHz01iD5eEEOkEaGU04Zc7Eag4IBrEVz3NT1V79NqOr/qAu8VfHsBuBiiSekUnLlVXBj24AzCK3OidyyypebpZVAwN/iolqwDkPJhw/SnDvbTfMvLoot2g0GqSpeA7ck4Wissd+6GCdQSQIDAQAB";
public static final String TIME_FROMAT_NORMAL = "yyyy-MM-dd HH:mm:ss";
public static final String PARAM_SIGN = "sign";
}
......@@ -8,47 +8,53 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* @Title: OpenApiController.java
* @Description: 公共平台对外提供的api
* @author fengzhi
* @version V1.0
* @Company: Didihu.com.cn
* @version V1.0
*/
@RestController
@RequestMapping("/openApi/v1.0")
@Slf4j
public class OpenApiController {
/*
* 开放平台service接口
*/
@Autowired
OpenApiService openApiService;
//授权管理
/*
* 授权管理
*/
@PostMapping("token")
public Result getToken(@RequestBody TokenBo tokenBo){
//todo jwt令牌
String jwtToken = openApiService.getToken(tokenBo);
return Result.ok().data(jwtToken);
}
//获取设备列表
/*
* 获取设备列表
*/
@PostMapping("deviceList")
public Result getDeviceList(@RequestBody DeviceListBo deviceListBo){
//todo 接口自己实现
log.info("OpenApiService===getDeviceList==="+deviceListBo);
DeviceListDTO deviceListVo = openApiService.getDeviceList(deviceListBo);
return Result.ok().data(deviceListVo);
}
//下发指令
/*
* 下发指令
*/
@PostMapping("postCommands")
public Result postCommands(@RequestBody CommandsBo commandsBo){
openApiService.postCommands(commandsBo);
return Result.ok();
}
//查询设备状态
/*
* 查询设备状态
*/
@PostMapping("deviceStatus")
public Result getDeviceStatus(@RequestBody DeviceStatusBo deviceStatusBo){
Integer status = openApiService.getDeviceStatus(deviceStatusBo);
......@@ -57,53 +63,94 @@ public class OpenApiController {
return Result.ok().data(map);
}
//获取商户下的数据概况信息
/*
* 获取商户下的数据概况信息
*/
@PostMapping("dataView")
public Result getDataView(@RequestBody DeviceStatusBo deviceStatusBo){
//todo 与杨林龙对接
DataViewDTO dataView = openApiService.getDataView(deviceStatusBo);
Map<String, Integer> dataView = openApiService.getDataView(deviceStatusBo);
log.info("fz===="+dataView.toString());
return Result.ok().data(dataView);
}
//消息订阅
/*
* 消息订阅
*/
@PostMapping("subscribeMessage")
public Result subscribeMessage(@RequestBody subscribeMessageBo subscribeMessageBo){
openApiService.subscribeMessage(subscribeMessageBo);
return Result.ok();
}
//查询最新位置点
/*
* 查询最新位置点
*/
@PostMapping("latestGpsRecord")
public Result getLatestGpsRecord(@RequestBody DeviceStatusBo deviceStatusBo){
LatestGpsRecordDto latestGpsRecordDto = openApiService.getLatestRGPSRecord(deviceStatusBo);
LatestGpsRecordDto latestGpsRecordDto = openApiService.getLatestGPSRecord(deviceStatusBo);
return Result.ok().data(latestGpsRecordDto);
}
//查询最新基站信息
/*
* 查询最新基站信息
*/
@PostMapping("latestBsRecord")
public Result getLatestBsRecord(@RequestBody DeviceStatusBo deviceStatusBo){
LatestBsRecordDto latestGpsRecordDto = openApiService.getLatestBsRecord(deviceStatusBo);
return Result.ok().data(latestGpsRecordDto);
}
//查询最新GPS和基站信息
/*
* 查询最新GPS和基站信息
*/
@PostMapping("latestGpsBsRecord")
public Result getLatestGpsBsRecord(@RequestBody DeviceStatusBo deviceStatusBo){
LatestGpsBsRecordDto latestGpsBsRecordDto = openApiService.getLatestGpsBsRecord(deviceStatusBo);
return Result.ok().data(latestGpsBsRecordDto);
}
//查询某时间段轨迹信息
/*
* 查询某时间段轨迹信息
*/
@PostMapping("gpsRecords")
public Result getGpsRecords(@RequestBody GpsBsRecordsBo gpsRecordsBo){
GpsRecordsDto gpsRecordsDto = openApiService.getGpsRecords(gpsRecordsBo);
return Result.ok().data(gpsRecordsDto);
}
//查询某时间段基站信息
/*
* 查询某时间段基站信息
*/
@PostMapping("bsRecords")
public Result getBsRecords(@RequestBody GpsBsRecordsBo gpsRecordsBo){
BsRecordsDto bsRecordsDto = openApiService.getBsRecords(gpsRecordsBo);
return Result.ok().data(bsRecordsDto);
}
/*
* 查询首次GPS点
*/
@PostMapping("firstGpsRecord")
public Result getFirstGpsRecord(@RequestBody DeviceStatusBo deviceStatusBo){
FirstGpsRecordDto firstGpsRecordDto = openApiService.getFirstGpsRecord(deviceStatusBo);
return Result.ok().data(firstGpsRecordDto);
}
/*
* 查询最近指定条数轨迹信息
*/
@PostMapping("recentGpsRecords")
public Result getRecentGpsRecords(@RequestBody DeviceStatusCountBo deviceStatusBo){
GpsRecordsDto recentGpsRecords = openApiService.getRecentGpsRecords(deviceStatusBo);
return Result.ok().data(recentGpsRecords);
}
/*
* 查询最近指定条数基站信息
*/
@PostMapping("recentBsRecords")
public Result getRecentBsRecords(@RequestBody DeviceStatusCountBo deviceStatusBo){
BsRecordsDto recentBsRecords = openApiService.getRecentBsRecords(deviceStatusBo);
return Result.ok().data(recentBsRecords);
}
}
package com.glsx.enums;
public enum MapTypeEnum {
NONE_TYPE(0, "NONE"),
DOUBLE_TYPE(1, "googlebaidu"),
GOOGLE_TYPE(2, "google"),
BAIDU_TYPE(3, "baidu");
private Integer id;
private String text;
private MapTypeEnum(Integer id, String text){
this.id = id;
this.text = text;
}
public static MapTypeEnum findById(Integer id) {
MapTypeEnum[] objs = MapTypeEnum.values();
for (MapTypeEnum obj : objs) {
if (id.equals(obj.getId())) {
return obj;
}
}
return null;
}
public String getText() {
return this.text;
}
public Integer getId() {
return this.id;
}
}
package com.glsx.exception;
/**
* @Description: 异常枚举类
* @author fengzhi
* @version V1.0
*/
public enum ApiErrorMessage {
TOKEN_ERROR(1001,"token有误: [%s]"),
ARGS_ERROR(1002,"参数错误: [%s]"),
ILLEGAL_DEVICE_SN(1003,"devicesn不存在"),
AUTH_ERROR(1004,"未授权(Ip与设定的IP不符)"),
ILLEGAL_DEVICE_TYPE(1005,"devicetype不存在"),
PARAM_ERROR(1006,"各项数据格式、长度不正确"),
TOKEN_TIME_OUT(1007,"超时"),
ARGS_NULL(1008,"参数错误,必传参数");
private int code;
private String message;
public ApiException exception(Object ...args){
return new ApiException(this,args);
}
private ApiErrorMessage(int code, String message){
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
}
package com.glsx.exception;
import com.glsx.model.Result;
/**
* @Description: api业务异常
* @author fengzhi
* @version V1.0
*/
public class ApiException extends BusinessException {
public ApiException(Result resultEntity) {
super(resultEntity);
}
public ApiException(ApiErrorMessage exception, Object... args) {
super(exception.getCode(), String.format(exception.getMessage(), args));
}
public ApiException(String message) {
super(message);
}
}
package com.glsx.exception;
import com.glsx.model.Result;
/**
* @Description: 业务异常
* @author fengzhi
* @version V1.0
*/
public class BusinessException extends RuntimeException{
private static final long serialVersionUID = 1L;
private Result resultEntity;
public BusinessException(String message) {
super(message);
this.resultEntity =Result.error(message);
}
public BusinessException(int errorCode, String message) {
super(message);
this.resultEntity =Result.error(errorCode,message);
}
public BusinessException(Result resultEntity) {
super(resultEntity.getMessage());
this.resultEntity = resultEntity;
}
public Result getResultEntity() {
return resultEntity;
}
}
package com.glsx.exception;
import com.glsx.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
/**
* @Description: 全局异常处理
* @author fengzhi
* @version V1.0
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 业务异常处理
*
* @param req
* @param e
* @return
*/
@ExceptionHandler(value = BusinessException.class)
public Result businessExceptionHandler(HttpServletRequest req, Exception e) {
log.error("业务异常:" + e.getMessage());
ApiException businessException = (ApiException) e;
return businessException.getResultEntity();
}
}
package com.glsx.ice.iceClient;
import com.glsx.config.SystemProperty;
import com.glsx.ice.DISTRICT.IDistrictFinderPrx;
import com.glsx.ice.DISTRICT.IDistrictFinderPrxHelper;
import com.glsx.model.DTO.BsRecordDto;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
@Slf4j
public class IceDistrictClient {
static String url = SystemProperty.getProperty("ice.districUrl");
static Ice.Communicator ic = Ice.Util.initialize();
static Ice.ObjectPrx base = ic.stringToProxy(url).ice_timeout(Integer.parseInt(SystemProperty.getProperty("ice.connectTimeout")));
static IDistrictFinderPrx prx = IDistrictFinderPrxHelper.checkedCast(base);
/**
* 通过经纬度查询所属行政区域
* @return
*/
public static List<BsRecordDto> getDistInfoByPos(float lng, float lat) {
try {
if (prx == null) {
throw new Exception("Invalid proxy");
}
Ice.IntHolder distCode = new Ice.IntHolder();
Ice.StringHolder strDistName = new Ice.StringHolder();
boolean res = prx.get_distinfo_by_pos(lng,lat,distCode,strDistName);
if (res) {
log.info("success===getDistInfoByPos:" + distCode+"=="+strDistName);
}
} catch (Ice.LocalException e) {
log.error("===getDistInfoByPos_ICE_EXCEP:" + e.getMessage(), e);
} catch (Exception e) {
log.error("===getDistInfoByPos_EXCEP:" + e.getMessage(), e);
}
return null;
}
}
......@@ -12,109 +12,14 @@ import java.util.stream.Collectors;
@Slf4j
public class IceHDaoGpsClient {
static String url = SystemProperty.getProperty("ice.trace.interface.url");
static String url = SystemProperty.getProperty("ice.traceUrl");
// static String url = "HDaoGpsSvc:default -h 192.168.3.153 -p 23479";
static Ice.Communicator ic = Ice.Util.initialize();
static Ice.ObjectPrx base = ic.stringToProxy(url).ice_timeout(Integer.parseInt(SystemProperty.getProperty("ice.connect.timeout")));
static Ice.ObjectPrx base = ic.stringToProxy(url).ice_timeout(Integer.parseInt(SystemProperty.getProperty("ice.connectTimeout")));
static DaoGpsServicePrx prx = DaoGpsServicePrxHelper.checkedCast(base);
/**
* HDaoGpsSvc:default -h 192.168.3.153 -p 23479
* 获取一段时间的轨迹
*
* @param apType 2: OBD; 4: DDbox(DVD) 5: Tracker 6: rearMirror 7: car recorder
* @param beginTime 开始时间
* @param endTime 结束时间
* @param userId 嘀嘀号
* @return
*/
public static List<GpsRecord> getTrack(int apType, Date beginTime, Date endTime, long userId) {
try {
if (prx == null) {
throw new Exception("Invalid proxy");
}
if (beginTime.after(endTime)) {
return null;
}
GpsGetResponseHolder res = new GpsGetResponseHolder(new GpsGetResponse());
GpsGetRequest req = new GpsGetRequest();
req.apType = apType;
req.startTime = new Long(beginTime.getTime() / 1000).intValue();
req.endTime = new Long(endTime.getTime() / 1000).intValue();
req.extraMapReq = 1;
req.reqCount = 0;
req.userID = userId;
prx.getGpsRecords(req, res);
List<GpsRecord> list = new ArrayList<GpsRecord>();
if (res != null && res.value != null && res.value.oprResult == 0) {
GpsRecord[] r = res.value.records;
int len = r.length;
for (int i = 0; i < len; i++) {
GpsRecord rec = r[i];
log.debug("====GpsRecord:" + rec);
}
return list;
}
} catch (Ice.LocalException e) {
log.error("===getTrack_ICE_EXCEP:" + e.getMessage(), e);
} catch (Exception e) {
log.error("===getTrack_EXCEP:" + e.getMessage(), e);
}
return null;
}
public static List<GpsRecord> getTrackByImei(int type, Date beginTime, Date endTime, long sn) {
try {
if (prx == null) {
throw new Exception("Invalid proxy");
}
if (beginTime.after(endTime)) {
return null;
}
GpsGetExResponseHolder res = new GpsGetExResponseHolder(new GpsGetExResponse());
GpsGetRequest req = new GpsGetRequest();
req.apType = type;
req.startTime = new Long(beginTime.getTime() / 1000).intValue();
;
req.endTime = new Long(endTime.getTime() / 1000).intValue();
req.extraMapReq = 1;
req.reqCount = 0;
req.userID = sn;
prx.getGpsRecordsByImei(req, res);
List<GpsRecord> list = new ArrayList<GpsRecord>();
if (res != null && res.value != null && res.value.oprResult == 0) {
GpsRecord[] r = res.value.records;
int len = r.length;
for (int i = 0; i < len; i++) {
GpsRecord rec = r[i];
log.debug("====TrackByImei:" + rec);
//GpsRecord g = new GpsRecord();
////BeanUtils.copyProperties(g, rec);
//g.setbLat((int) (rec.getbLat()/1000000D));
//g.setbLng((int) (rec.getbLng()/1000000D));
//g.setSpeed(rec.getSpeed());
//g.setgLat((int) (rec.getgLat()/1000000D));
//g.setgLng((int) (rec.getgLng()/1000000D));
//
//g.setLat((int) (rec.getLat()/1000000D));
//g.setLng((int) (rec.getLng()/1000000D));
//g.setGpsTime(rec.getGpsTime());
//g.setStoreTime(rec.getStoreTime());
//
//list.add(g);
}
return list;
}
} catch (Ice.LocalException e) {
log.error("===getTrackByImei_ICE_EXCEP:" + e.getMessage(), e);
} catch (Exception e) {
log.error("===getTrackByImei_EXCEP:" + e.getMessage(), e);
}
return null;
}
public static GpsRecord getLatestRGPSRecord(Long userId, Integer deviceType, Integer mapType) {
GpsRecord gpsRecord = null;
public static LatestGpsRecordDto getLatestGpsRecord(Long userId, Integer deviceType, Integer mapType) {
LatestGpsRecordDto gpsRecord = null;
try {
if (prx == null) {
throw new Exception("Invalid proxy");
......@@ -125,17 +30,15 @@ public class IceHDaoGpsClient {
LatestRgpsGetResponseHolder res = new LatestRgpsGetResponseHolder();
boolean ret = false;
ret = prx.getLatestRgpsRecord(req, res);
log.info("===getLatestRGPSRecord:" + ret);
if (ret) {
log.info("===getLatestRGPSRecord:" + res.value.record);
//gpsRecord = new GpsRecord();
//gpsRecord.setgLng(res.value.record.gLng);
//gpsRecord.setgLat(res.value.record.gLat);
//gpsRecord.setLng(res.value.record.lng);
//gpsRecord.setLat(res.value.record.lat);
//gpsRecord.setSpeed(res.value.record.speed);
//gpsRecord.setAlt(res.value.record.alt);
//gpsRecord.setGpsTime(res.value.record.gpsTime);
gpsRecord = new LatestGpsRecordDto();
gpsRecord.setGlng(res.value.record.gLng/ 1000000D);
gpsRecord.setGlat(res.value.record.gLat/ 1000000D);
gpsRecord.setLng(res.value.record.lng/ 1000000D);
gpsRecord.setLat(res.value.record.lat/ 1000000D);
gpsRecord.setSpeed(res.value.record.speed);
gpsRecord.setGpstime(res.value.record.gpsTime);
}
} catch (Ice.LocalException e) {
log.error("===getLatestRGPSRecord_ICE_EXCEP:" + e.getMessage(), e);
......@@ -145,8 +48,8 @@ public class IceHDaoGpsClient {
return gpsRecord;
}
public static BsRecord getLatestBsRecord(long userId, Integer deviceType) {
BsRecord bsRecord = null;
public static LatestBsRecordDto getLatestBsRecord(long userId, Integer deviceType) {
LatestBsRecordDto bsRecord = null;
try {
if (prx == null) {
throw new Exception("Invalid proxy");
......@@ -157,15 +60,21 @@ public class IceHDaoGpsClient {
boolean ret = false;
LatestBsGetRequest req = new LatestBsGetRequest(userId, deviceType);
ret = prx.getLatestBsRecord(req, res);
log.info("===getLatestBsRecord:" + ret);
if (ret) {
log.info("===LatestBsRecord:" + res.value.record);
int gpsTime = res.value.record.gpsTime;
int storeTime = res.value.record.storeTime;
int mcc = res.value.record.mcc;
int mnc = res.value.record.mnc;
BsInfo[] bsInfos = res.value.record.bsInfos;
bsRecord = new BsRecord(gpsTime, storeTime, mcc, mnc, bsInfos);
bsRecord = new LatestBsRecordDto();
bsRecord.setGpstime(res.value.record.gpsTime);
bsRecord.setMcc(res.value.record.mcc);
bsRecord.setMnc(res.value.record.mnc);
List<BsInfoDto> bsInfos = Arrays.stream(res.value.record.bsInfos).map(bsInfo -> {
BsInfoDto bsRecordDto = new BsInfoDto();
bsRecordDto.setCi(bsInfo.cellId);
bsRecordDto.setLac(bsInfo.lac);
bsRecordDto.setSignal(bsInfo.signal);
return bsRecordDto;
}).collect(Collectors.toList());
bsRecord.setBsrecord(bsInfos);
}
} catch (Ice.LocalException e) {
log.error("===getLatestBsRecord_ICE_EXCEP:" + e.getMessage(), e);
......@@ -175,13 +84,54 @@ public class IceHDaoGpsClient {
return bsRecord;
}
public static LatestGpsBsRecordDto getDevicesGpsInfo(long[] userIds, int extraMapReq, int seqNo) {
LatestGpsBsRecordDto bsRecord = null;
try {
if (prx == null) {
throw new Exception("Invalid proxy");
}
// 第2个参数:2: OBD; 4: DDbox(DVD) 5: Tracker 6: rearMirror 7: car recorder
BatchGpsDevInfoResponseHolder res = new BatchGpsDevInfoResponseHolder();
boolean ret = false;
BatchGpsDevInfoRequest req = new BatchGpsDevInfoRequest(userIds, extraMapReq,seqNo);
ret = prx.getDevicesGpsInfo(req, res);
if (ret) {
log.info("===getDevicesGpsInfo:" + res.value.gpsDevInfos);
GpsDevInfo[] gpsDevInfos = res.value.gpsDevInfos;
if(null != gpsDevInfos && gpsDevInfos.length>0){
GpsDevInfo gpsDevInfo = gpsDevInfos[0];
bsRecord = new LatestGpsBsRecordDto();
bsRecord.setGpstime(gpsDevInfo.record.gpsTime);
//bsRecord.setMcc(gpsDevInfo.record.);
//bsRecord.setMnc(gpsDevInfo.record.mnc);
//List<BsRecordDto> bsInfos = Arrays.stream(res.value.record.bsInfos).map(bsInfo -> {
// BsRecordDto bsRecordDto = new BsRecordDto();
// bsRecordDto.setCi(bsInfo.cellId);
// bsRecordDto.setLac(bsInfo.lac);
// bsRecordDto.setSignal(bsInfo.signal);
// return bsRecordDto;
//}).collect(Collectors.toList());
//bsRecord.setBsrecord(bsInfos);
}
}
} catch (Ice.LocalException e) {
log.error("===getDevicesGpsInfo_ICE_EXCEP:" + e.getMessage(), e);
} catch (Exception e) {
log.error("===getDevicesGpsInfo_EXCEP:" + e.getMessage(), e);
}
return bsRecord;
}
/**
* @param apType 2: OBD; 4: DDbox(DVD) 5: Tracker 6: rearMirror 7: car recorder
* @param startTime 开始时间
* @param endTime 结束时间
* @return
*/
public static List<GpsRecordDto> getGpsRecords(int apType, Date startTime, Date endTime, long userId) {
public static GpsRecordsDto getGpsRecords(int apType, Date startTime, Date endTime, long userId) {
try {
if (prx == null) {
throw new Exception("Invalid proxy");
......@@ -189,6 +139,7 @@ public class IceHDaoGpsClient {
if (startTime.after(endTime)) {
return null;
}
GpsRecordsDto gpsRecordsDto = new GpsRecordsDto();
GpsGetResponseHolder res = new GpsGetResponseHolder(new GpsGetResponse());
GpsGetRequest req = new GpsGetRequest();
req.apType = apType;
......@@ -199,32 +150,16 @@ public class IceHDaoGpsClient {
req.userID = userId;
prx.getGpsRecords(req, res);
List<GpsRecordDto> list = new ArrayList();
if (res != null && res.value != null && res.value.oprResult == 0) {
GpsRecord[] r = res.value.records;
int len = r.length;
for (int i = 0; i < len; i++) {
GpsRecord rec = r[i];
GpsRecordDto g = new GpsRecordDto();
g.setGpstime(rec.gpsTime);
g.setAlt(rec.alt);
g.setDir(rec.dir);
g.setSpeed(rec.speed);
g.setLat(rec.lat / 1000000D);
g.setLng(rec.lng / 1000000D);
g.setGlat(rec.gLat / 1000000D);
g.setGlng(rec.gLng / 1000000D);
g.setBlat(rec.bLat / 1000000D);
g.setBlng(rec.bLat / 1000000D);
list.add(g);
}
return list;
gpsRecordsDto.setGpsrecord(convertGpsRecord(r));
}
return gpsRecordsDto;
} catch (Ice.LocalException e) {
log.error("===getTrack_ICE_EXCEP:" + e.getMessage(), e);
log.error("===getGpsRecords_ICE_EXCEP:" + e.getMessage(), e);
} catch (Exception e) {
log.error("===getTrack_EXCEP:" + e.getMessage(), e);
log.error("===getGpsRecords_EXCEP:" + e.getMessage(), e);
}
return null;
}
......@@ -235,7 +170,7 @@ public class IceHDaoGpsClient {
* @param endTime 结束时间
* @return
*/
public static List<BsRecordDto> getBsRecords(int apType, Date startTime, Date endTime, long userId) {
public static BsRecordsDto getBsRecords(int apType, Date startTime, Date endTime, long userId) {
try {
if (prx == null) {
throw new Exception("Invalid proxy");
......@@ -243,6 +178,7 @@ public class IceHDaoGpsClient {
if (startTime.after(endTime)) {
return null;
}
BsRecordsDto bsRecordsDto = new BsRecordsDto();
BsGetResponseHolder res = new BsGetResponseHolder(new BsGetResponse());
BsGetRequest req = new BsGetRequest();
req.apType = apType;
......@@ -252,33 +188,141 @@ public class IceHDaoGpsClient {
req.userID = userId;
prx.getBsRecords(req, res);
List<GpsRecordDto> list = new ArrayList();
if (res != null && res.value != null && res.value.oprResult == 0) {
BsRecord[] r = res.value.records;
bsRecordsDto.setBsrecord(convertBsRecord(r));
}
return bsRecordsDto;
} catch (Ice.LocalException e) {
log.error("===getBsRecords_ICE_EXCEP:" + e.getMessage(), e);
} catch (Exception e) {
log.error("===getBsRecords_EXCEP:" + e.getMessage(), e);
}
return null;
}
//查询首次GPS点
public static FirstGpsRecordDto getFirstGpsRecord(int apType, long userId) {
try {
if (prx == null) {
throw new Exception("Invalid proxy");
}
FirstGpsRecordDto firstGpsRecordDto = null;
GpsGetResponseHolder res = new GpsGetResponseHolder(new GpsGetResponse());
GpsGetRequest req = new GpsGetRequest();
req.apType = apType;
req.reqCount = 0;
req.userID = userId;
prx.getFirstGpsRecord(req, res);
if (res != null && res.value != null && res.value.oprResult == 0) {
GpsRecord[] r = res.value.records;
int len = r.length;
if(len>0){
GpsRecord gpsRecord = r[0];
firstGpsRecordDto = new FirstGpsRecordDto();
firstGpsRecordDto.setLat(gpsRecord.lat / 1000000D);
firstGpsRecordDto.setLng(gpsRecord.lng/ 1000000D);
firstGpsRecordDto.setGlat(gpsRecord.gLat/ 1000000D);
firstGpsRecordDto.setGlng(gpsRecord.gLng/ 1000000D);
firstGpsRecordDto.setSpeed(gpsRecord.speed);
firstGpsRecordDto.setGpstime(gpsRecord.gpsTime);
}
}
return firstGpsRecordDto;
} catch (Ice.LocalException e) {
log.error("===getFirstGpsRecord_ICE_EXCEP:" + e.getMessage(), e);
} catch (Exception e) {
log.error("===getFirstGpsRecord_EXCEP:" + e.getMessage(), e);
}
return null;
}
public static GpsRecordsDto getRecentGpsRecords(long userID, int apType, int apSubType, int extraMapReq, int reqCount) {
try {
if (prx == null) {
throw new Exception("Invalid proxy");
}
GpsRecordsDto gpsRecordsDto = new GpsRecordsDto();
RecentGpsGetResponseHolder res = new RecentGpsGetResponseHolder(new RecentGpsGetResponse());
RecentGpsGetRequest req = new RecentGpsGetRequest(userID,apType,apSubType,extraMapReq,reqCount);
prx.getRecentGpsRecords(req, res);
if (res != null && res.value != null && res.value.oprResult == 0) {
GpsRecord[] r = res.value.records;
gpsRecordsDto.setGpsrecord(convertGpsRecord(r));
}
return gpsRecordsDto;
} catch (Ice.LocalException e) {
log.error("===getRecentGpsRecords_ICE_EXCEP:" + e.getMessage(), e);
} catch (Exception e) {
log.error("===getRecentGpsRecords_EXCEP:" + e.getMessage(), e);
}
return null;
}
public static BsRecordsDto getRecentBsRecords(int apType, long userId) {
try {
if (prx == null) {
throw new Exception("Invalid proxy");
}
BsRecordsDto bsRecordsDto = new BsRecordsDto();
RecentBsGetResponseHolder res = new RecentBsGetResponseHolder(new RecentBsGetResponse());
RecentBsGetRequest req = new RecentBsGetRequest();
req.apType = apType;
req.reqCount = 0;
req.userID = userId;
prx.getRecentBsRecords(req, res);
if (res != null && res.value != null && res.value.oprResult == 0) {
Arrays.stream(res.value.records).map(rec->{
BsRecordsDto g = new BsRecordsDto();
g.setGpstime(rec.gpsTime);
g.setMcc(rec.mcc);
g.setMnc(rec.mnc);
List<BsRecordDto> bsInfos = Arrays.stream(rec.bsInfos).map(info ->
{
BsRecordDto bsRecord = new BsRecordDto();
bsRecord.setCi(info.cellId);
bsRecord.setLac(info.lac);
bsRecord.setSignal(info.signal);
return bsRecord;
}).collect(Collectors.toList());
g.setBsrecord(bsInfos);
return g;
}).collect(Collectors.toList());
BsRecord[] r = res.value.records;
bsRecordsDto.setBsrecord(convertBsRecord(r));
}
return bsRecordsDto;
} catch (Ice.LocalException e) {
log.error("===getTrack_ICE_EXCEP:" + e.getMessage(), e);
log.error("===getRecentBsRecords_ICE_EXCEP:" + e.getMessage(), e);
} catch (Exception e) {
log.error("===getTrack_EXCEP:" + e.getMessage(), e);
log.error("===getRecentBsRecords_EXCEP:" + e.getMessage(), e);
}
return null;
}
private static List<GpsRecordDto> convertGpsRecord(GpsRecord[] records){
return Arrays.stream(records).map(rec->{
GpsRecordDto g = new GpsRecordDto();
g.setGpstime(rec.gpsTime);
g.setAlt(rec.alt);
g.setDir(rec.dir);
g.setSpeed(rec.speed);
g.setLat(rec.lat / 1000000D);
g.setLng(rec.lng / 1000000D);
g.setGlat(rec.gLat / 1000000D);
g.setGlng(rec.gLng / 1000000D);
g.setBlat(rec.bLat / 1000000D);
g.setBlng(rec.bLat / 1000000D);
return g;
}).collect(Collectors.toList());
}
private static List<BsRecordDto> convertBsRecord(BsRecord[] records){
return Arrays.stream(records).map(rec->{
BsRecordDto g = new BsRecordDto();
g.setGpstime(rec.gpsTime);
g.setMcc(rec.mcc);
g.setMnc(rec.mnc);
List<BsInfoDto> bsInfos = Arrays.stream(rec.bsInfos).map(info ->
{
BsInfoDto bsRecord = new BsInfoDto();
bsRecord.setCi(info.cellId);
bsRecord.setLac(info.lac);
bsRecord.setSignal(info.signal);
return bsRecord;
}).collect(Collectors.toList());
g.setBsinfo(bsInfos);
return g;
}).collect(Collectors.toList());
}
}
......@@ -2,6 +2,7 @@ package com.glsx.ice.iceClient;
import Ice.Communicator;
import com.glsx.config.SystemProperty;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -10,14 +11,12 @@ import org.slf4j.LoggerFactory;
* @author Administrator
*
*/
@Slf4j
public class IcePoiSearchClient {
private static Logger log = LoggerFactory.getLogger(IcePoiSearchClient.class);
// ice接口服务器地址 ice.poisearch.interface.url=PoiSearchNear:default -h 47.107.239.127 -p 10081
private static String ICE_URL = SystemProperty.getProperty("ice.poisearch.interface.url");
private static String ICE_URL = SystemProperty.getProperty("ice.poisearchUrl");
static Communicator ic = Ice.Util.initialize();
static Ice.ObjectPrx base = ic.stringToProxy(ICE_URL).ice_timeout(Integer.parseInt(SystemProperty.getProperty("ice.connect.timeout")));
static Ice.ObjectPrx base = ic.stringToProxy(ICE_URL).ice_timeout(Integer.parseInt(SystemProperty.getProperty("ice.connectTimeout")));
public static void main(String[] args) throws Exception {
......
......@@ -3,6 +3,7 @@ package com.glsx.ice.iceClient;
import Ice.Communicator;
import com.glsx.config.SystemProperty;
import com.glsx.ice.HDaoMile.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -13,14 +14,13 @@ import java.util.Date;
* @author Administrator
*
*/
@Slf4j
public class IceRtMileStatClient {
private static Logger log = LoggerFactory.getLogger(IceRtMileStatClient.class);
// ice接口服务器地址 ice.interface.url=FenceUpdate:default -h 192.168.3.153 -p
// 10000
private static String ICE_URL = SystemProperty.getProperty("ice.mile.interface.url");
private static String ICE_URL = SystemProperty.getProperty("ice.mileUrl");
static Communicator ic = Ice.Util.initialize();
static Ice.ObjectPrx base = ic.stringToProxy(ICE_URL).ice_timeout(Integer.parseInt(SystemProperty.getProperty("ice.connect.timeout")));
static Ice.ObjectPrx base = ic.stringToProxy(ICE_URL).ice_timeout(Integer.parseInt(SystemProperty.getProperty("ice.connectTimeout")));
static DaoMileServicePrx daoMileService = DaoMileServicePrxHelper.checkedCast(base);
......
package com.glsx.intercepter;
import com.glsx.utils.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import com.glsx.constant.OpenAPIConstant;
import com.glsx.exception.ApiErrorMessage;
import com.glsx.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -10,39 +11,66 @@ import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
/**
* @Description: 开放平台接口拦截器
* @author fengzhi
* @version V1.0
*/
@Component
@Slf4j
public class AuthIntercepter implements HandlerInterceptor {
/**
* JWT工具
*/
@Autowired
private JwtTokenUtil jwtTokenUtil;
private JwtUtil jwtUtil;
/**
* 请求拦截
*
* @param request request 请求对象, 包含请求地址, 头, 参数, body(流)等信息
* @param request response 响应对象, 包含输入流, 响应body类型等信息
* @param handler 指controller的@Controller注解下的"完整"方法名, 是包含exception等字段信息
* @return boolean 是否拦截
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("===拦截==");
if (isJson(request)) {
// 获取json字符串
String jsonStr = new RequestWrapper(request).getBodyString();
log.info("[preHandle] json数据 : {}", jsonStr);
JSONObject jsonParam = JSONObject.fromObject(jsonStr);
String jwtToken = jsonParam.getString("token");
Claims claims = jwtTokenUtil.getClaimsFromToken(jwtToken);
if (null != claims) {
String s1 = (String) claims.get("fzs");
Integer s2 = (Integer) claims.get("fzn");
Integer s3 = (Integer) claims.get("fzl");
log.info("jwt===s1:" + s1 + "==s2:" + s2 + "==s3:" + s3);
}
log.info("===AuthIntercepter拦截=="+request.getServletPath());
//非json返回提示
if (!isJson(request))
throw ApiErrorMessage.PARAM_ERROR.exception();
// 获取json字符串
String jsonStr = new RequestWrapper(request).getBodyString();
log.info("[preHandle] json数据 : {}", jsonStr);
JSONObject jsonParam = JSONObject.fromObject(jsonStr);
//获取token
String jwtToken = jsonParam.getString("token");
//判断token是否过期
boolean tokenExpired = false;
try {
//解析验证token
tokenExpired = jwtUtil.isTokenExpired(jwtToken);
}catch (Exception e){
throw ApiErrorMessage.TOKEN_ERROR.exception();
}
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
if(tokenExpired){
throw ApiErrorMessage.TOKEN_TIME_OUT.exception();
}
//提示过期时间
SimpleDateFormat sdf = new SimpleDateFormat(OpenAPIConstant.TIME_FROMAT_NORMAL);
String expirTime = sdf.format(jwtUtil.getExpiredDateFromToken(jwtToken));
log.info("token过期时间:"+expirTime);
//验证成功,放行
return true;
}
/**
* 判断本次请求的数据类型是否为json
*
......
package com.glsx.intercepter;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* 使用HttpServletRequestWrapper + Filter解决输入流不能重复读取问题
* @Description: HttpServletRequestWrapper + Filter解决输入流不能重复读取问题
* @author fengzhi
* @version V1.0
*/
@Slf4j
public class ReplaceStreamFilter implements Filter {
......
......@@ -10,7 +10,9 @@ import java.io.*;
import java.nio.charset.Charset;
/**
* 使用HttpServletRequestWrapper + Filter解决输入流不能重复读取问题
* @Description: HttpServletRequestWrapper + Filter解决输入流不能重复读取问题
* @author fengzhi
* @version V1.0
*/
@Slf4j
public class RequestWrapper extends HttpServletRequestWrapper {
......
package com.glsx.model.BO;
import lombok.Data;
import lombok.ToString;
@Data
@ToString(callSuper = true)
public class DeviceStatusCountBo extends DeviceStatusBo{
private Integer count;
}
package com.glsx.model.BO;
import com.glsx.model.Basemodel;
import lombok.Data;
import lombok.ToString;
@Data
@ToString(callSuper = true)
public class TokenBo extends Basemodel {
public class TokenBo {
/*
* appID,应用唯一标识(可能是用户id,服务商ID或是微信公众号,具体到时候定义)
*/
private Integer appId;
/*
* 当前时间戳,精确到秒。例如时间为2015-03-23 14:58:33 ,则time= 1427093913
*/
private String time;
/*
* 授权类型,1:简单模式
*/
private Integer grantType;
/*
* 参数用公钥加密后的密文
*/
private String sign;
}
......@@ -3,9 +3,11 @@ package com.glsx.model;
import lombok.Data;
import lombok.ToString;
import java.util.Date;
@Data
@ToString(callSuper = true)
public class BaseTimeRangeModel extends Basemodel{
private Long startTime;
private Long endTime;
private Date startTime;
private Date endTime;
}
......@@ -5,10 +5,6 @@ import java.io.Serializable;
@Data
public class Basemodel implements Serializable {
private Integer appId;
private String time;
//会话token
//会话token(jwt令牌)
private String token;
}
package com.glsx.model.DTO;
import lombok.Data;
@Data
public class BsInfoDto {
//基号
private Integer lac;
//塔号
private Integer ci;
//信号强度 0~100
private Integer signal;
}
......@@ -2,12 +2,16 @@ package com.glsx.model.DTO;
import lombok.Data;
import java.util.List;
@Data
public class BsRecordDto {
//基号
private Integer lac;
//塔号
private Integer ci;
//信号强度 0~100
private Integer signal;
//时间翟10位 1970之后的秒数
private Integer gpstime;
//国家码
private Integer mcc;
//所属运商
private Integer mnc;
private List<BsInfoDto> bsinfo;
}
......@@ -8,12 +8,10 @@ import java.util.List;
@Data
@ToString(callSuper = true)
public class BsRecordsDto {
//时间翟10位 1970之后的秒数
private Integer gpstime;
//国家码
private Integer mcc;
//所属运商
private Integer mnc;
//设备号
private String sn;
//是否还有记录
private Boolean has_more;
//bs记录
private List<BsRecordDto> bsrecord;
}
package com.glsx.model.DTO;
import lombok.Data;
@Data
public class DataViewDTO {
//总共激活设备数
private Integer totaldevice;
//总共用户数
private Integer totalusers;
//在线设备数
private Integer onlinedevices;
}
package com.glsx.model.DTO;
import com.glsx.model.GaodeMap;
import lombok.Data;
@Data
public class FirstGpsRecordDto extends GaodeMap {
//10位时间戳(1970之后的秒数)
private Integer gpstime;
//速度
private Integer speed;
//设备号
private String sn;
}
......@@ -15,6 +15,6 @@ public class LatestBsRecordDto {
//所属运商
private Integer mnc;
private List<BsRecordDto> bsrecord;
private List<BsInfoDto> bsrecord;
}
......@@ -13,23 +13,27 @@ import java.util.Map;
*/
public class Result extends HashMap<String,Object>{
private static final long serialVersionUID = 1L;
public static final String CODE_KEY = "code";
public static final String SUCCESS_KEY = "success";
public static final String MSG_KEY = "message";
private static final String RESULT_KEY = "result";
public static final Integer SUCCESS = 0;
public static final Integer ERROR = 9999;
public Result() {
this.put(CODE_KEY, 200);
this.put(CODE_KEY, SUCCESS);
this.put(SUCCESS_KEY, true);
this.put(MSG_KEY, "");
}
public static Result error() {
return error(9999, "未知异常,请联系管理员");
return error(ERROR, "未知错误");
}
public static Result error(String msg) {
return error(500, msg);
return error(ERROR, msg);
}
public static Result error(int code, String msg) {
......
......@@ -3,6 +3,8 @@ package com.glsx.service;
import com.glsx.model.BO.*;
import com.glsx.model.DTO.*;
import java.util.Map;
public interface OpenApiService {
String getToken(TokenBo grantType);
......@@ -13,11 +15,11 @@ public interface OpenApiService {
Integer getDeviceStatus(DeviceStatusBo deviceStatusBo);
DataViewDTO getDataView(DeviceStatusBo deviceStatusBo);
Map<String, Integer> getDataView(DeviceStatusBo deviceStatusBo);
void subscribeMessage(subscribeMessageBo subscribeMessageBo);
LatestGpsRecordDto getLatestRGPSRecord(DeviceStatusBo deviceStatusBo);
LatestGpsRecordDto getLatestGPSRecord(DeviceStatusBo deviceStatusBo);
LatestBsRecordDto getLatestBsRecord(DeviceStatusBo deviceStatusBo);
......@@ -26,4 +28,10 @@ public interface OpenApiService {
GpsRecordsDto getGpsRecords(GpsBsRecordsBo gpsRecordsBo);
BsRecordsDto getBsRecords(GpsBsRecordsBo gpsRecordsBo);
FirstGpsRecordDto getFirstGpsRecord(DeviceStatusBo deviceStatusBo);
GpsRecordsDto getRecentGpsRecords(DeviceStatusBo deviceStatusBo);
BsRecordsDto getRecentBsRecords(DeviceStatusBo deviceStatusBo);
}
package com.glsx.service.impl;
import cn.com.glsx.openplatform.service.IceOpenApiService;
import com.glsx.base.controller.BaseService;
import com.glsx.constant.OpenAPIConstant;
import com.glsx.enums.MapTypeEnum;
import com.glsx.exception.ApiErrorMessage;
import com.glsx.ice.iceClient.IceHDaoGpsClient;
import com.glsx.model.BO.*;
import com.glsx.model.DTO.*;
import com.glsx.service.OpenApiService;
import com.glsx.utils.JwtTokenUtil;
import com.glsx.utils.JwtUtil;
import com.glsx.utils.MapUtils;
import com.glsx.utils.RSAUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
/**
* @Description: 开放平台接口实现类
* @author fengzhi
* @version V1.0
*/
@Service
public class OpenApiServiceImpl extends BaseService implements OpenApiService {
@Autowired
JwtTokenUtil jwtTokenUtil;
JwtUtil jwtTokenUtil;
@Autowired
IceOpenApiService iceOpenApiService;
@Override
public String getToken(TokenBo tokenBo) {
logi("OpenApiService===调用getToken===" + tokenBo);
//appID,应用唯一标识(可能是用户id,服务商ID或是微信公众号,具体到时候定义)
Integer appId = tokenBo.getAppId();
//授权类型,1:简单模式
Integer grantType = tokenBo.getGrantType();
//当前时间戳,精确到秒。例如时间为2015-03-23 14:58:33 ,则time= 1427093913
String time = tokenBo.getTime();
//获取密文(参数顺序按照字母升序,共钥加密)
String token = tokenBo.getToken();
logi("OpenApiService===调用getToken开始===" + tokenBo);
//校验必传参数
TreeMap<String, String> params = MapUtils.transBean2Map(tokenBo);
logi("参数对象:" + params);
boolean miss = params.entrySet().stream().anyMatch(kv->StringUtils.isEmpty(kv.getValue()));
if(miss)
throw ApiErrorMessage.ARGS_NULL.exception();
//todo 根据appID查询客户信息
Integer appId = tokenBo.getAppId();
//获取公钥加密的密文
String sign = tokenBo.getSign();
//todo 获取私钥
String privateKey = OpenAPIConstant.TEST_PRIVATE_KEY;
String originalStr = "";
try {
//解密获取明文
originalStr = RSAUtils.decrypt(token, privateKey);
//私钥解密获取明文
originalStr = RSAUtils.decrypt(sign, privateKey);
} catch (Exception e) {
loge("OpenApiService===RSA解密错误===", e);
throw ApiErrorMessage.ARGS_ERROR.exception("RSA解密错误=="+sign);
}
//校验参数,防止篡改
TreeMap<String, String> params = MapUtils.transBean2Map(tokenBo);
params.remove("token");
logi("Map对象:" + params);
//按照参数字母升序(参数+参数值)拼接
//除了sign以外,按照参数字母升序(参数+参数值)拼接
StringBuffer paramsStrbuf = new StringBuffer();
for (Map.Entry<String, String> param : params.entrySet()) {
paramsStrbuf.append(param.getKey()).append(param.getValue());
}
params.remove(OpenAPIConstant.PARAM_SIGN);
params.entrySet().stream().forEach(kv->{
paramsStrbuf.append(kv.getKey()).append(kv.getValue());
});
String paramsStr = paramsStrbuf.toString();
//如果与明文不相同,则参数被篡改
//校验参数,防止篡改
if (!paramsStr.equals(originalStr)) {
logi("参数被篡改");
throw ApiErrorMessage.ARGS_ERROR.exception("请求参数被篡改");
}
//todo 将客户信息转化为jwt
......@@ -66,66 +77,113 @@ public class OpenApiServiceImpl extends BaseService implements OpenApiService {
infos.put("fzn", 123);
infos.put("fzl", 22);
String jwtToken = jwtTokenUtil.generateToken(infos);
logi("OpenApiService===返回jwt===" + jwtToken);
return jwtToken;
}
/*
* 参数用公钥加密后的密文
*/
@Override
public DeviceListDTO getDeviceList(DeviceListBo deviceListBo) {
logi("OpenApiService===getDeviceList===" + deviceListBo);
DeviceListDTO deviceListDTO = new DeviceListDTO();
deviceListDTO.setTotal(100);
return null;
return deviceListDTO;
}
//todo 接口还没给
@Override
public void postCommands(CommandsBo commandsBo) {
logi("OpenApiService===ImplpostCommands");
logi("OpenApiService===postCommands");
}
//todo 接口还没给
@Override
public Integer getDeviceStatus(DeviceStatusBo deviceStatusBo) {
logi("OpenApiService===getToken");
logi("OpenApiService===getDeviceStatus");
return null;
}
@Override
public DataViewDTO getDataView(DeviceStatusBo deviceStatusBo) {
logi("OpenApiService===getToken");
return null;
public Map<String, Integer> getDataView(DeviceStatusBo deviceStatusBo) {
logi("OpenApiService===getDataView");
int userID = 1;
return iceOpenApiService.getDataView(userID);
}
//todo 接口还没给
@Override
public void subscribeMessage(subscribeMessageBo subscribeMessageBo) {
logi("OpenApiService===getToken");
logi("OpenApiService===subscribeMessage");
}
@Override
public LatestGpsRecordDto getLatestRGPSRecord(DeviceStatusBo deviceStatusBo) {
logi("OpenApiService===getToken");
return null;
public LatestGpsRecordDto getLatestGPSRecord(DeviceStatusBo deviceStatusBo) {
logi("OpenApiService===getLatestRGPSRecord");
long dId = 61000593;
Integer dType = 6;
//todo 调用参数
LatestGpsRecordDto gpsRecord = IceHDaoGpsClient.getLatestGpsRecord(dId, dType, MapTypeEnum.NONE_TYPE.getId());
//todo 设置sn
return gpsRecord;
}
@Override
public LatestBsRecordDto getLatestBsRecord(DeviceStatusBo deviceStatusBo) {
logi("OpenApiService===getLatestBsRecord" + deviceStatusBo);
return null;
long dId = 61000593;
Integer dType = 6;
//todo 调用参数
LatestBsRecordDto bsRecord = IceHDaoGpsClient.getLatestBsRecord(dId, dType);
//todo 设置sn
return bsRecord;
}
@Override
public LatestGpsBsRecordDto getLatestGpsBsRecord(DeviceStatusBo deviceStatusBo) {
logi("OpenApiService===getLatestGpsBsRecord===" + deviceStatusBo);
return null;
long[] dId = {61000593};
//todo 调用参数
LatestGpsBsRecordDto latestGpsBsRecordDto = IceHDaoGpsClient.getDevicesGpsInfo(dId, 0,0);
return latestGpsBsRecordDto;
}
@Override
public GpsRecordsDto getGpsRecords(GpsBsRecordsBo gpsRecordsBo) {
logi("OpenApiService===getGpsRecords===" + gpsRecordsBo);
return null;
GpsRecordsDto gpsRecordsDto = IceHDaoGpsClient.getGpsRecords(1,gpsRecordsBo.getStartTime(),gpsRecordsBo.getEndTime(),1);
return gpsRecordsDto;
}
@Override
public BsRecordsDto getBsRecords(GpsBsRecordsBo gpsRecordsBo) {
return null;
logi("OpenApiService===getGpsRecords===" + gpsRecordsBo);
BsRecordsDto bsRecordsDto = IceHDaoGpsClient.getBsRecords(1,gpsRecordsBo.getStartTime(),gpsRecordsBo.getEndTime(),1);
return bsRecordsDto;
}
@Override
public FirstGpsRecordDto getFirstGpsRecord(DeviceStatusBo deviceStatusBo) {
logi("OpenApiService===getFirstGpsRecord===" + deviceStatusBo);
FirstGpsRecordDto firstGpsRecordDto = IceHDaoGpsClient.getFirstGpsRecord(1,1);
return firstGpsRecordDto;
}
@Override
public GpsRecordsDto getRecentGpsRecords(DeviceStatusBo deviceStatusBo) {
logi("OpenApiService===getRecentGpsRecords===" + deviceStatusBo);
GpsRecordsDto bsRecordsDto = IceHDaoGpsClient.getRecentGpsRecords(1,1,1,1,1);
return bsRecordsDto;
}
@Override
public BsRecordsDto getRecentBsRecords(DeviceStatusBo deviceStatusBo) {
logi("OpenApiService===getRecentBsRecords===" + deviceStatusBo);
BsRecordsDto bsRecordsDto = IceHDaoGpsClient.getRecentBsRecords(1,1);
return bsRecordsDto;
}
}
package com.glsx.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.glsx.config.SystemProperty;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
......@@ -12,25 +7,19 @@ import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* JwtToken生成的工具类
* JWT token的格式:header.payload.signature
* header的格式(算法、token的类型):
* {"alg": "HS512","type": "JWT"}
* payload的格式(用户名、创建时间、生成时间):
* {"sub":"wang","created":1489079981393,"exp":1489684781}
* signature的生成算法:
* HMACSHA512(base64UrlEncode(header) + "." +base64UrlEncode(payload),secret)
* @Description: Jwt工具类
* @author fengzhi
* @version V1.0
*/
@Slf4j
@Component
public class JwtTokenUtil {
public class JwtUtil {
private static final String CLAIM_KEY_CREATED = "created";
private static final String JWT_SECRET = "jwt.openapi.secret";
private static final String JWT_EXPIRATION = "jwt.openapi.expiration";
private static final String JWT_SECRET = "jwt.secret";
private static final String JWT_EXPIRATION = "jwt.expiration";
/**
* 根据负责生成JWT的token
......@@ -48,14 +37,10 @@ public class JwtTokenUtil {
*/
public Claims getClaimsFromToken(String token) {
Claims claims = null;
try {
claims = Jwts.parser()
.setSigningKey(SystemProperty.getProperty(JWT_SECRET))
.parseClaimsJws(token)
.getBody();
} catch (Exception e) {
log.info("JWT格式验证失败:{}",token);
}
claims = Jwts.parser()
.setSigningKey(SystemProperty.getProperty(JWT_SECRET))
.parseClaimsJws(token)
.getBody();
return claims;
}
......
......@@ -6,6 +6,12 @@ import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.TreeMap;
/**
* @Description: 将实体类属性转为map
* @author fengzhi
* @version V1.0
*/
public class MapUtils {
public static TreeMap<String, String> transBean2Map(Object obj) {
......
......@@ -11,9 +11,16 @@ import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
/**
* @Description: RSA工具类
* @author fengzhi
* @version V1.0
*/
@Component
public class RSAUtils {
/*private static Map<Integer, String> keyMap = new HashMap<Integer, String>(); //用于封装随机产生的公钥与私钥
private static Map<Integer, String> keyMap = new HashMap<Integer, String>(); //用于封装随机产生的公钥与私钥
public static void main(String[] args) throws Exception {
//生成公钥和私钥
genKeyPair();
......@@ -28,10 +35,10 @@ public class RSAUtils {
System.out.println("还原后的字符串为:" + messageDe);
}
*//**
/**
* 随机生成密钥对
* @throws NoSuchAlgorithmException
*//*
*/
public static void genKeyPair() throws NoSuchAlgorithmException {
// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
......@@ -47,7 +54,8 @@ public class RSAUtils {
// 将公钥和私钥保存到Map
keyMap.put(0,publicKeyString); //0表示公钥
keyMap.put(1,privateKeyString); //1表示私钥
}*/
}
/**
* RSA公钥加密
*
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!