DriverJob.java
20.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
package com.ruoyi.job;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.common.cache.SchedulingCache;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.driver.domain.Driver;
import com.ruoyi.driver.service.IDriverService;
import com.ruoyi.equipment.domain.Equipment;
import com.ruoyi.equipment.mapper.EquipmentMapper;
import com.ruoyi.pojo.request.PersonnelRequestVo;
import com.ruoyi.pojo.request.TokenRequestVo;
import com.ruoyi.pojo.response.ResponseSchedulingDto;
import com.ruoyi.pojo.response.personnel.*;
import com.ruoyi.service.ThreadJobService;
import com.ruoyi.utils.ConstDateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static com.ruoyi.common.ConstDriverProperties.PERSONNEL_POSTS_DRIVER;
import static com.ruoyi.common.ConstDriverProperties.PERSONNEL_POSTS_SALES;
import static com.ruoyi.common.ConstEquipmentProperties.*;
import static com.ruoyi.common.redispre.GlobalRedisPreName.*;
/**
* 该定时任务用户获取驾驶员信息
*
* @author 20412
*/
@Component("driverJob")
@Slf4j
public class DriverJob implements InitializingBean {
@Autowired
private RedisCache redisCache;
@Resource
private SchedulingCache schedulingCache;
@Resource
EquipmentMapper equipmentMapper;
@Resource
private RestTemplate restTemplate;
@Resource
private ThreadJobService threadJobService;
@Autowired
private IDriverService driverService;
@Value("${api.url.getDriverInfo}")
private String getDriverInfoUrl;
@Value("${api.personnel.token.tokenUrl}")
private String tokenUrl;
@Value("${api.personnel.token.appKey}")
private String appKey;
@Value("${api.personnel.token.appSecret}")
private String appSecret;
@Value("${api.url.getSchedulingInfoNew}")
private String getSchedulingInfoUrl;
@Value("${api.config.password}")
private String password;
@Value("${api.config.nonce}")
private String nonce;
private static ThreadJobService THREAD_JOB_SERVICE;
private static SchedulingCache SCHEDULING_CACHE;
private static EquipmentMapper EQUIPMENT_MAPPER;
private static String APP_KEY;
private static String TOKEN_URL;
private static String APP_SECRET;
private static IDriverService DRIVER_SERVICE;
private static RedisCache REDIS_CACHE;
private static RestTemplate RESTTEMPLATE;
private static String GET_SCHEDULING_INFO_URL;
private static String GET_DRIVER_INFO_URL;
private static String PASSWORD;
private static String NONCE;
/**
* 通过该定时任务获取驾驶员信息 并保存到数据库
*/
public void getDriverInfo(String params) throws Exception {
try {
// String getDriverInfoUrl = String.format(GET_DRIVER_INFO_URL, params);
//获取token
log.info("开始获取人事接口token");
TokenResponseVo tokenVo = getToken(TOKEN_URL);
log.info("获取人事接口token完毕");
// 获取驾驶员信息
log.info("开始获取驾驶员信息");
getDrivers(tokenVo.getAccessToken());
log.info("获取驾驶员信息结束");
} catch (Exception e) {
log.info("执行失败:" + e.getMessage());
}
log.info("执行结束");
}
private static void saveDrivers(List<Driver> drivers, String accessToken) {
// 多线程插入数据
log.info("开始插入");
THREAD_JOB_SERVICE.asyncUploadDriverWithUpdateImageUrl(drivers, accessToken);
// String downloadImage = getDownloadImage(url, accessToken, "");
}
// public static void main(String[] args) {
// String str = "[{\"previewUrl\":\"/ossFileHandle?appType=APP_HV8J7X8PFRXLJJW8JTZK&fileName=APP_HV8J7X8PFRXLJJW8JTZK_bWFuYWdlcjgxNF9QRTg2Nk1EMThYTUNaNkxVN002QTQ3N0hQV0E2MlNYMTMwQ0tMQTQ$.png&instId=&type=open&process=image/resize,m_fill,w_200,h_200,limit_0/quality,q_80\",\"size\":621992,\"name\":\"0332d25e3b9e80bca3d90daf0d5857d.png\",\"downloadUrl\":\"/ossFileHandle?appType=APP_HV8J7X8PFRXLJJW8JTZK&fileName=APP_HV8J7X8PFRXLJJW8JTZK_bWFuYWdlcjgxNF9QRTg2Nk1EMThYTUNaNkxVN002QTQ3N0hQV0E2MlNYMTMwQ0tMQTQ$.png&instId=&type=download\",\"fileUuid\":\"APP_HV8J7X8PFRXLJJW8JTZK_bWFuYWdlcjgxNF9QRTg2Nk1EMThYTUNaNkxVN002QTQ3N0hQV0E2MlNYMTMwQ0tMQTQ$.png\",\"url\":\"/ossFileHandle?appType=APP_HV8J7X8PFRXLJJW8JTZK&fileName=APP_HV8J7X8PFRXLJJW8JTZK_bWFuYWdlcjgxNF9QRTg2Nk1EMThYTUNaNkxVN002QTQ3N0hQV0E2MlNYMTMwQ0tMQTQ$.png&instId=&type=download\"}]";
//// List<List> lists = JSONArray.parseArray(str, List.class);
// List<ImageField_lk9mk228> lists = JSONArray.parseArray(str, ImageField_lk9mk228.class);
// System.out.println(lists);
// }
public static String getDownloadImageUrl(String accessToken, String preViewUrl) {
accessToken = REDIS_CACHE.getCacheObject(REDIS_PERSONNEL_TOKEN);
String url = "https://api.dingtalk.com/v1.0/yida/apps/temporaryUrls/APP_HV8J7X8PFRXLJJW8JTZK";
String fileUrl = "https://scroix.aliwork.com";
try {
fileUrl = URLEncoder.encode(fileUrl + preViewUrl, String.valueOf(StandardCharsets.UTF_8));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
url = url + "?userId=InterfaceManagement&timeout=7200000&fileUrl=" + fileUrl + "&systemToken=16A66291CHE9K5DPE1IDO9E63FOE2VWA09QFLV";
Map<String, Object> param = new HashMap<>();
param.put("userId", "InterfaceManagement");
param.put("timeout", 7200000L);
param.put("fileUrl", fileUrl);
param.put("systemToken", "16A66291CHE9K5DPE1IDO9E63FOE2VWA09QFLV");
Map<String, String> header = new HashMap<>();
header.put("x-acs-dingtalk-access-token", accessToken);
header.put("Content-Type", "application/json");
String result = "";
try {
String body = HttpUtil.createGet(url).addHeaders(header).form(new HashMap<>()).execute().body();
result = JSON.parseObject(body, ImageUrlResultResponseVo.class).getResult();
// 可能需要重新获取token
} catch (Exception e) {
String token = DriverJob.getToken(TOKEN_URL).getAccessToken();
header.put("x-acs-dingtalk-access-token", token);
String body = HttpUtil.createGet(url).addHeaders(header).form(new HashMap<>()).execute().body();
ImageUrlResultResponseVo vo = JSON.parseObject(body, ImageUrlResultResponseVo.class);
result = vo.getResult();
}
return result;
}
public void clearExceptionYesterdayRecord() {
// 获取当前日期时间
Calendar calendar = Calendar.getInstance();
// 将日期减去一天
calendar.add(Calendar.DAY_OF_MONTH, -1);
// 获取昨天的日期时间
Date yesterday = calendar.getTime();
String dateKey = REDIS_SIGN_IN_DRIVER_ALCOHOL_OVERFLOW + ConstDateUtil.formatDate(yesterday);
log.info("开始清除昨天的异常数据:{}", dateKey);
REDIS_CACHE.deleteObject(dateKey);
log.info("清除昨天的异常数据完成:{}", dateKey);
}
/**
* 获取排班任务请求
* 24小时执行一次
*/
public void getSchedulingInfo() {
// TODO 获取当天的签到表
long timestamp = System.currentTimeMillis();
String formatDate = ConstDateUtil.formatDate(timestamp);
// String formatDate = ConstDateUtil.formatDate(ConstDateUtil.getTheSpecifiedNumberOfDaysOfTime(-1));
log.info("获取排班任务触发时间:{}", formatDate);
// 获取排班请求
String getSchedulingInfoUrl = null;
log.info("开始获取{}的排班数据", formatDate);
try {
getSchedulingInfoUrl = String.format(GET_SCHEDULING_INFO_URL, "99", formatDate, timestamp, NONCE, PASSWORD, getSHA1(getStringStringMap(String.valueOf(timestamp))));
} catch (Exception e) {
throw new RuntimeException(e);
}
// 获取排班信息并存入redis
saveSchedulingToRedis(getSchedulingInfoUrl, formatDate);
// 删除两天前排班信息
deleteScheduling();
log.info("获取{}的排班数据完毕", formatDate);
}
private void deleteScheduling() {
String nowKey = DRIVER_SCHEDULING_PRE + ConstDateUtil.formatDate(new Date());
String yesterdayKey = DRIVER_SCHEDULING_PRE + ConstDateUtil.formatDate(ConstDateUtil.getTheSpecifiedNumberOfDaysOfTime(-1));
List<String> keys = SCHEDULING_CACHE.getKeys();
for (int i = 0; i < keys.size(); i++) {
if (nowKey.equals(keys.get(i)) || yesterdayKey.equals(keys.get(i))){
continue;
}
SCHEDULING_CACHE.removeCacheSchedulingByKey(keys.get(i));
}
}
/**
* 计算是否全部设备完成了对应的用户人脸注册
*/
public void computedFaceSignIn() {
DRIVER_SERVICE.updateDriverByComputed();
}
/**
* 计算设备在线状态 5 分钟一次
*/
public void computedDeviceOnlineStatus(String date) {
List<Equipment> list = EQUIPMENT_MAPPER.selectEquipmentList(null);
Long checkTime = StringUtils.isEmpty(date) ? DEVICE_OFFLINE_TIME : Long.parseLong(date);
for (Equipment equipment : list) {
if (Objects.isNull(equipment.getLastHeartRes())) {
equipment.setOnlineClient(DEVICE_OFFLINE);
} else {
LocalDateTime time = ConstDateUtil.getLocalDateTimeByLongTime(equipment.getLastHeartRes().getTime());
LocalDateTime nowTime = LocalDateTime.now();
long timeout = ChronoUnit.MINUTES.between(time, nowTime);
if (checkTime.compareTo(timeout) < 0) {
equipment.setOnlineClient(DEVICE_OFFLINE);
} else {
equipment.setOnlineClient(DEVICE_ONLINE);
}
}
}
EQUIPMENT_MAPPER.updateEquipments(list);
}
public Map<String, List<ResponseSchedulingDto>> saveSchedulingToRedis(String getSchedulingInfoUrl, String dateKey) {
log.info("开始拉取排班:{}", dateKey);
List<ResponseSchedulingDto> originSchedulingList = RESTTEMPLATE.exchange(
getSchedulingInfoUrl,
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<ResponseSchedulingDto>>() {
}).getBody();
Map<String, List<ResponseSchedulingDto>> driverSchedulingMap = new HashMap<>(200);
// 以员工号为key存入排班集合
originSchedulingList.stream().forEach(item -> {
// 员工号为key
String[] infos = item.getJsy().split("/");
String driverJobCode = infos[0];
String driverName = infos[1];
String salePersonJobCode = item.getSpy().split("/").length > 0 ? item.getSpy().split("/")[0] : null;
String salePersonName = item.getSpy().split("/").length > 0 ? item.getSpy().split("/")[1] : null;
splitSaveScheduling(driverSchedulingMap, driverJobCode, driverName, item, PERSONNEL_POSTS_DRIVER);
splitSaveScheduling(driverSchedulingMap, salePersonJobCode, salePersonName, item, PERSONNEL_POSTS_SALES);
});
// 排序
List<String> keys = new ArrayList<>(driverSchedulingMap.keySet());
for (String key : keys) {
List<ResponseSchedulingDto> schedulingList = driverSchedulingMap.get(key);
schedulingList.sort(Comparator.comparing(ResponseSchedulingDto::getFcsjT));
}
// 存入数据库
THREAD_JOB_SERVICE.asyncComputedScheduling(driverSchedulingMap);
// 存入缓存
SCHEDULING_CACHE.setCacheScheduling(DRIVER_SCHEDULING_PRE + dateKey, driverSchedulingMap);
// REDIS_CACHE.setCacheMap(DRIVER_SCHEDULING_PRE + dateKey, driverSchedulingMap, 2, TimeUnit.DAYS);
log.info("拉取排班完毕:{}", dateKey);
return driverSchedulingMap;
}
private void splitSaveScheduling(Map<String, List<ResponseSchedulingDto>> driverSchedulingMap, String jobCode, String name, ResponseSchedulingDto item, String posts) {
if (!Objects.isNull(jobCode)) {
ResponseSchedulingDto scheduling = new ResponseSchedulingDto();
BeanUtils.copyProperties(item,scheduling);
scheduling.setPosts(posts);
scheduling.setJobCode(jobCode);
scheduling.setName(name);
if (Objects.isNull(driverSchedulingMap.get(jobCode))) {
List<ResponseSchedulingDto> oneDriverScheduling = new ArrayList<>();
oneDriverScheduling.add(scheduling);
driverSchedulingMap.put(jobCode, oneDriverScheduling);
} else {
driverSchedulingMap.get(jobCode).add(scheduling);
}
}
}
public static void getDrivers(String accessToken) throws Exception {
// Map<String, String> configMap = getStringStringMap(timestamp);
// String sign = getSHA1(configMap);
Date date = new Date();
int pageSize = 100;
PersonnelResultResponseVo vo = getPersonInfo(accessToken, pageSize, 1);
int countPage = vo.getTotalCount() / pageSize;
countPage = vo.getTotalCount() % pageSize == 0 ? countPage : countPage + 1;
List<Driver> drivers = getDrivers(date, vo);
// updateDrivers(drivers);
saveDrivers(drivers, accessToken);
for (int i = 1; i <= countPage; ) {
if (++i <= countPage) {
vo = getPersonInfo(accessToken, 100, i);
drivers = getDrivers(date, vo);
// updateDrivers(drivers);
saveDrivers(drivers, accessToken);
}
}
}
private static void updateDrivers(List<Driver> drivers) {
log.info("开始更新人脸注册状态");
DRIVER_SERVICE.updateDrivers(drivers);
log.info("更新人脸注册状态完毕");
}
private static List<Driver> getDrivers(Date date, PersonnelResultResponseVo vo) {
List<Driver> drivers = vo.getData().stream().map(item -> {
Driver driver = new Driver();
FormData formData = item.getFormData();
driver.setUpdateTime(date);
driver.setJobCode(formData.getTextField_lk9mk222());
driver.setPersonnelName(formData.getTextField_lk9mk224());
driver.setPosts(formData.getTextField_lk9mk226());
// 解析JSON字符串
List<ImageField_lk9mk228> lists = JSONArray.parseArray(formData.getImageField_lk9mk228(), ImageField_lk9mk228.class);
driver.setImage(lists.get(0).getPreviewUrl());
driver.setLineName(formData.getTextField_lkmgdvnu());
driver.setFleetName(formData.getTextField_lkmgdvnv());
return driver;
}).collect(Collectors.toList());
return drivers;
}
private static PersonnelResultResponseVo getPersonInfo(String accessToken, Integer pageSize, Integer currentPage) {
RestTemplate restTemplate = new RestTemplate();
String url = "https://api.dingtalk.com/v1.0/yida/forms/instances/search";
PersonnelRequestVo vo = new PersonnelRequestVo();
vo.setAppType("APP_HV8J7X8PFRXLJJW8JTZK");
vo.setFormUuid("FORM-D2B665D1LQMCRRGS9WE6F54QTVYF25BXHM9KL4");
vo.setUserId("InterfaceManagement");
vo.setSystemToken("16A66291CHE9K5DPE1IDO9E63FOE2VWA09QFLV");
vo.setCurrentPage(currentPage);
vo.setPageSize(pageSize);
// 工号组件
// vo.setSearchFieldJson(" size = 4");
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("x-acs-dingtalk-access-token", accessToken);
// 创建HttpEntity对象
HttpEntity<String> requestEntity = new HttpEntity<>(JSON.toJSONString(vo), headers);
// 发送POST请求
ResponseEntity<PersonnelResultResponseVo> result = restTemplate.postForEntity(url, requestEntity, PersonnelResultResponseVo.class);
PersonnelResultResponseVo body = result.getBody();
return body;
}
public static TokenResponseVo getToken(String url) {
TokenRequestVo request = new TokenRequestVo();
request.setAppKey(APP_KEY);
request.setAppSecret(APP_SECRET);
String requestBody = JSON.toJSONString(request);
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// 创建HttpEntity对象
HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
// 发送POST请求
ResponseEntity<TokenResponseVo> responseEntity = RESTTEMPLATE.postForEntity(url, requestEntity, TokenResponseVo.class);
TokenResponseVo vo = responseEntity.getBody();
REDIS_CACHE.setCacheObject(REDIS_PERSONNEL_TOKEN, vo.getAccessToken(), vo.getExpireIn(), TimeUnit.SECONDS);
return vo;
}
public Map<String, String> getStringStringMap(String timestamp) {
Map<String, String> configMap = new HashMap<>(5);
configMap.put("timestamp", String.valueOf(timestamp));
configMap.put("nonce", NONCE);
configMap.put("password", PASSWORD);
return configMap;
}
/**
* 获取签名
*
* @param map
* @return
* @throws Exception
*/
public String getSHA1(Map<String, String> map) throws Exception {
try {
String[] array = new String[map.size()];
map.values().toArray(array);
StringBuffer sb = new StringBuffer();
// 字符串排序
Arrays.sort(array);
for (int i = 0; i < array.length; i++) {
sb.append(array[i]);
}
String str = sb.toString();
// SHA1签名生成
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(str.getBytes());
byte[] digest = md.digest();
StringBuffer hexstr = new StringBuffer();
String shaHex = "";
for (int i = 0; i < digest.length; i++) {
shaHex = Integer.toHexString(digest[i] & 0xFF);
if (shaHex.length() < 2) {
hexstr.append(0);
}
hexstr.append(shaHex);
}
return hexstr.toString();
} catch (Exception e) {
throw e;
}
}
// public static void main(String[] args) throws Exception {
// RestTemplate restTemplate1 = new RestTemplate();
//// String url = "http://101.95.136.206:9089/webservice/rest/person/company/%s";
// String url = "http://101.95.136.206:9089/webservice/rest/schedule_real/sch_jk/%s/%s?timestamp=%d&nonce=%s&password=%s&sign=%s";
//
// long timestamp = System.currentTimeMillis();
// Map<String, String> configMap = new HashMap<>(5);
// configMap.put("timestamp", String.valueOf(timestamp));
// configMap.put("nonce", "NONCE");
// configMap.put("password", "c4dd3d8cb9a82f6d6a625818618b28ca7bebb464");
// String format = String.format(url, "99", DateUtils.getDate("yyyyMMdd"), timestamp, "NONCE", "c4dd3d8cb9a82f6d6a625818618b28ca7bebb464", getSHA1(configMap));
//// String sign = getSHA1(configMap);
//// String httpUrl = format
//// + "?timestamp=" + timestamp
//// + "&nonce=" + "NONCE"
//// + "&password=" + "c4dd3d8cb9a82f6d6a625818618b28ca7bebb464"
//// + "&sign=" + sign;
// Object forObject = restTemplate1.getForObject(format, Object.class);
// }
@Override
public void afterPropertiesSet() throws Exception {
GET_DRIVER_INFO_URL = getDriverInfoUrl;
NONCE = nonce;
PASSWORD = password;
RESTTEMPLATE = restTemplate;
DRIVER_SERVICE = driverService;
REDIS_CACHE = redisCache;
GET_SCHEDULING_INFO_URL = getSchedulingInfoUrl;
THREAD_JOB_SERVICE = threadJobService;
TOKEN_URL = tokenUrl;
APP_KEY = appKey;
APP_SECRET = appSecret;
SCHEDULING_CACHE = schedulingCache;
EQUIPMENT_MAPPER = equipmentMapper;
}
}