ToolUtils.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. package com.welampiot.utils;
  2. import com.alibaba.fastjson.JSON;
  3. import com.welampiot.common.BaseResult;
  4. import com.welampiot.common.InterfaceResultEnum;
  5. import com.welampiot.common.LampControlTypeEnum;
  6. import com.welampiot.configuration.MqttConfig;
  7. import com.welampiot.dto.GlobalLocationDTO;
  8. import com.welampiot.dto.SectionDTO;
  9. import com.welampiot.dto.UserDTO;
  10. import com.welampiot.handle.MqttHandler;
  11. import com.welampiot.service.GlobalLocationService;
  12. import com.welampiot.service.SectionService;
  13. import com.welampiot.service.UserService;
  14. import org.apache.commons.httpclient.HttpClient;
  15. import org.apache.commons.httpclient.methods.PostMethod;
  16. import org.eclipse.paho.client.mqttv3.MqttClient;
  17. import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
  18. import org.eclipse.paho.client.mqttv3.MqttMessage;
  19. import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
  20. import org.gavaghan.geodesy.Ellipsoid;
  21. import org.gavaghan.geodesy.GeodeticCalculator;
  22. import org.gavaghan.geodesy.GeodeticCurve;
  23. import org.gavaghan.geodesy.GlobalCoordinates;
  24. import org.slf4j.Logger;
  25. import org.slf4j.LoggerFactory;
  26. import org.springframework.beans.factory.annotation.Autowired;
  27. import org.springframework.stereotype.Component;
  28. import javax.servlet.http.HttpServletRequest;
  29. import java.io.IOException;
  30. import java.net.URL;
  31. import java.net.URLConnection;
  32. import java.text.DecimalFormat;
  33. import java.util.*;
  34. import java.util.regex.Pattern;
  35. import java.util.zip.CRC32;
  36. @Component
  37. public class ToolUtils {
  38. private UserDTO user;
  39. @Autowired
  40. private UserService userService;
  41. @Autowired
  42. private SectionService sectionService;
  43. @Autowired
  44. private GlobalLocationService globalLocationService;
  45. @Autowired
  46. private MqttConfig mqttConfig;
  47. @Autowired
  48. private MqttHandler mqttHandler;
  49. private static final String PATTERN = "^(?=.*[0-9])(?=.*[a-zA-Z]).{8,20}$";
  50. /**
  51. * 获取用户所有路段 id
  52. * @param request
  53. * @return 如果返回列表为空,表示超管获取到全部路段信息,此时不需要做路段筛选
  54. */
  55. public List getSectionList(HttpServletRequest request){
  56. String username = request.getParameter("username");
  57. ArrayList<Object> sectionList = new ArrayList<>();
  58. if (username == null || username.toString().length() == 0) {
  59. sectionList.add(0);
  60. return sectionList;
  61. }
  62. user = userService.findUserByUserName(username);
  63. if (user == null) {
  64. sectionList.add(0);
  65. return sectionList;
  66. }
  67. String provinceid = request.getParameter("provinceid");
  68. provinceid = provinceid == null || provinceid.equals("0") ? request.getParameter("provinceId") : provinceid;
  69. String cityid = request.getParameter("cityid");
  70. cityid = cityid == null || cityid.equals("0") ? request.getParameter("cityId") : cityid;
  71. String areaid = request.getParameter("areaid");
  72. areaid = areaid == null || areaid.equals("0") ? request.getParameter("areaId") : areaid;
  73. String sectionid = request.getParameter("sectionid");
  74. sectionid = sectionid == null || sectionid.equals("0") ? request.getParameter("sectionId") : sectionid;
  75. if (sectionid != null && sectionid.length() != 0 && !sectionid.equals("0")){
  76. sectionList.add(sectionid);
  77. return sectionList;
  78. }
  79. String zone = user.getZoneList();
  80. int role = user.getRole();
  81. List<SectionDTO> maps;
  82. List<GlobalLocationDTO> globalLocationList;
  83. ArrayList areaList = new ArrayList<>();
  84. if ((cityid != null && !cityid.equals("0")) || (provinceid != null && !provinceid.equals("0")) || (areaid != null && !areaid.equals("0"))){
  85. if (areaid == null || areaid.equals("0")){
  86. ArrayList cityList = new ArrayList<>();
  87. if (cityid == null || cityid.equals("0")){
  88. globalLocationList = globalLocationService.getListByPid(Integer.valueOf(provinceid));
  89. if (globalLocationList.isEmpty()){
  90. cityid = provinceid;
  91. }else {
  92. for (GlobalLocationDTO m :globalLocationList) {
  93. cityList.add(m.getId());
  94. }
  95. }
  96. }
  97. if (cityList.isEmpty()){
  98. globalLocationList = globalLocationService.getListByPid(Integer.valueOf(cityid));
  99. }else {
  100. globalLocationList = globalLocationService.getListByPidList(cityList);
  101. }
  102. if (globalLocationList.isEmpty()){
  103. areaid = cityid;
  104. }else {
  105. for (GlobalLocationDTO m :globalLocationList) {
  106. areaList.add(m.getId());
  107. }
  108. }
  109. }
  110. }
  111. if ((areaid == null || areaid.length() == 0 || areaid.equals("0")) && areaList.isEmpty()){
  112. if (role != 1) {
  113. return Arrays.asList(zone.split(","));
  114. }else {
  115. return new ArrayList<>();
  116. }
  117. }else {
  118. if (areaid == null || areaid.equals("0")){
  119. maps = sectionService.getListByPidList(areaList);
  120. if (role != 1){
  121. return Arrays.asList(zone.split(","));
  122. }
  123. }else {
  124. System.out.println(areaid);
  125. int areaid2 = Integer.valueOf(areaid);
  126. maps = sectionService.getListByPid(areaid2);
  127. }
  128. }
  129. for (SectionDTO map:maps) {
  130. sectionList.add(map.getId());
  131. }
  132. if (sectionList.isEmpty()) sectionList.add("0");
  133. return sectionList;
  134. }
  135. public UserDTO getUser() {
  136. return user;
  137. }
  138. /**
  139. * 返回接口信息,不带数据
  140. * @param code 状态码
  141. * @param version 语言类型 0 中文,1 英文,2 俄语
  142. * @return
  143. */
  144. public BaseResult response(InterfaceResultEnum resultEnum,Integer version){
  145. String msg;
  146. String code = resultEnum.getCode();
  147. if (version == 0){
  148. msg = resultEnum.getMsgCn();} else if (version == 1) {
  149. msg = resultEnum.getMsgEn();
  150. }else {
  151. msg = resultEnum.getMsgRu();
  152. }
  153. BaseResult<Object> objectBaseResult = new BaseResult<>(code, msg, new Object());
  154. Logger paramLog = LoggerFactory.getLogger("param_log");
  155. paramLog.info("reponse param== "+ JSON.toJSONString(objectBaseResult));
  156. return objectBaseResult;
  157. }
  158. /**
  159. * 返回接口信息,带数据
  160. * @param code 状态码
  161. * @param version 语言类型 0 中文,1 英文,2 俄语
  162. * @param obj 返回数据内容
  163. * @return
  164. */
  165. public BaseResult response(InterfaceResultEnum resultEnum,Integer version,Object obj){
  166. String msg;
  167. String code = resultEnum.getCode();
  168. if (version == 0){
  169. msg = resultEnum.getMsgCn();
  170. } else if (version == 1) {
  171. msg = resultEnum.getMsgEn();
  172. }else {
  173. msg = resultEnum.getMsgRu();
  174. }
  175. BaseResult<Object> objectBaseResult = new BaseResult<>(code, msg, obj);
  176. Logger paramLog = LoggerFactory.getLogger("param_log");
  177. paramLog.info("reponse param== "+ JSON.toJSONString(objectBaseResult));
  178. return objectBaseResult;
  179. }
  180. /**
  181. * 发送mqtt指令
  182. * @param sendTopic 发送的topic
  183. * @param cmdInfo 发送的指令内容
  184. * @param resTopic 接收指令返回的topic
  185. * @return
  186. */
  187. public String sendMqttCmd(String sendTopic,Object cmdInfo,String resTopic){
  188. MqttClient client;
  189. String res = "";
  190. try {
  191. try {
  192. client=new MqttClient(mqttConfig.getUrl(),mqttConfig.getClientId()+"_"+(new Date()).getTime(),new MemoryPersistence());
  193. MqttConnectOptions options=new MqttConnectOptions();
  194. options.setCleanSession(true);
  195. options.setUserName(mqttConfig.getUsername());
  196. options.setPassword(mqttConfig.getPassword().toCharArray());
  197. options.setConnectionTimeout(mqttConfig.getTimeout());
  198. options.setKeepAliveInterval(mqttConfig.getKeepalive());
  199. mqttHandler.setTopic(resTopic);
  200. // 设置回调
  201. client.setCallback(mqttHandler);
  202. // 建立连接
  203. client.connect(options);
  204. // MqttCustomerClient.setClient(client);
  205. client.subscribe(resTopic);
  206. // 消息发布所需参数
  207. MqttMessage message;
  208. if (cmdInfo instanceof String){
  209. message = new MqttMessage(((String) cmdInfo).getBytes());
  210. }else {
  211. message = new MqttMessage((byte[]) cmdInfo);
  212. }
  213. message.setQos(0);
  214. client.publish(sendTopic, message);
  215. int in = 0;
  216. while (true){
  217. Thread.sleep(1000);
  218. if (mqttHandler.getRes() != null && mqttHandler.getRes().length() != 0){
  219. res = mqttHandler.getRes();
  220. break;
  221. }
  222. in ++;
  223. if (in > 30) break;
  224. }
  225. client.disconnect();
  226. }catch (Exception e){
  227. e.printStackTrace();
  228. }
  229. }catch (Exception e){
  230. e.printStackTrace();
  231. }
  232. return res;
  233. }
  234. /**
  235. * 发送mqtt指令
  236. * @param sendTopic 发送的topic
  237. * @param cmdInfo 发送的指令内容
  238. * @param resTopic 接收指令返回的topic
  239. * @param timeout 指令超时时间
  240. * @return
  241. */
  242. public String sendMqttCmd(String sendTopic,Object cmdInfo,String resTopic,Integer timeout){
  243. MqttClient client;
  244. String res = "";
  245. try {
  246. try {
  247. client=new MqttClient(mqttConfig.getUrl(),mqttConfig.getClientId()+"_"+(new Date()).getTime(),new MemoryPersistence());
  248. MqttConnectOptions options=new MqttConnectOptions();
  249. options.setCleanSession(true);
  250. options.setUserName(mqttConfig.getUsername());
  251. options.setPassword(mqttConfig.getPassword().toCharArray());
  252. options.setConnectionTimeout(mqttConfig.getTimeout());
  253. options.setKeepAliveInterval(mqttConfig.getKeepalive());
  254. mqttHandler.setTopic(resTopic);
  255. // 设置回调
  256. client.setCallback(mqttHandler);
  257. // 建立连接
  258. client.connect(options);
  259. // MqttCustomerClient.setClient(client);
  260. client.subscribe(resTopic);
  261. // 消息发布所需参数
  262. MqttMessage message;
  263. if (cmdInfo instanceof String){
  264. message = new MqttMessage(((String) cmdInfo).getBytes());
  265. }else {
  266. message = new MqttMessage((byte[]) cmdInfo);
  267. }
  268. message.setQos(0);
  269. client.publish(sendTopic, message);
  270. int in = 0;
  271. if (timeout > 0){
  272. while (true){
  273. Thread.sleep(1000);
  274. if (mqttHandler.getRes() != null && mqttHandler.getRes().length() != 0){
  275. res = mqttHandler.getRes();
  276. break;
  277. }
  278. in ++;
  279. if (in > timeout) break;
  280. }
  281. }
  282. client.disconnect();
  283. }catch (Exception e){
  284. e.printStackTrace();
  285. }
  286. }catch (Exception e){
  287. e.printStackTrace();
  288. }
  289. return res;
  290. }
  291. /**
  292. * 字节数组转16进制字符串
  293. * @param b 字节数组
  294. * @return 16进制字符串
  295. * @throws
  296. */
  297. public static String bytes2HexString(byte[] b) {
  298. StringBuffer result = new StringBuffer();
  299. String hex;
  300. for (int i = 0; i < b.length; i++) {
  301. hex = Integer.toHexString(b[i] & 0xFF);
  302. if (hex.length() == 1) {
  303. hex = '0' + hex;
  304. }
  305. result.append(hex.toUpperCase());
  306. }
  307. return result.toString();
  308. }
  309. /**
  310. * 16进制字符串转字节数组
  311. * @param src 16进制字符串
  312. * @return 字节数组
  313. * @throws
  314. */
  315. public byte[] hexString2Bytes(String src) {
  316. int l = src.length() / 2;
  317. byte[] ret = new byte[l];
  318. for (int i = 0; i < l; i++) {
  319. ret[i] = (byte) Integer
  320. .valueOf(src.substring(i * 2, i * 2 + 2), 16).byteValue();
  321. }
  322. return ret;
  323. }
  324. /**
  325. * 获取CRC32校验码
  326. * @param src 16进制字符串
  327. * @return CRC32校验码
  328. */
  329. public String getCRC32ByHexString2Bytes(String src) {
  330. CRC32 crc32 = new CRC32();
  331. crc32.update(this.hexString2Bytes(src));
  332. return Integer.toHexString((int) crc32.getValue());
  333. }
  334. /**
  335. * 计算modbus CRC16校验码
  336. * @param bytes 需要计算的数据
  337. * @return
  338. */
  339. public String getCRC(byte[] bytes) {
  340. // CRC寄存器全为1
  341. int CRC = 0x0000ffff;
  342. // 多项式校验值
  343. int POLYNOMIAL = 0x0000a001;
  344. int i, j;
  345. for (i = 0; i < bytes.length; i++) {
  346. CRC ^= ((int) bytes[i] & 0x000000ff);
  347. for (j = 0; j < 8; j++) {
  348. if ((CRC & 0x00000001) != 0) {
  349. CRC >>= 1;
  350. CRC ^= POLYNOMIAL;
  351. } else {
  352. CRC >>= 1;
  353. }
  354. }
  355. }
  356. // 结果转换为16进制
  357. String result = Integer.toHexString(CRC).toUpperCase();
  358. if (result.length() != 4) {
  359. StringBuffer sb = new StringBuffer("0000");
  360. result = sb.replace(4 - result.length(), 4, result).toString();
  361. }
  362. //高位在前地位在后
  363. //return result.substring(2, 4) + " " + result.substring(0, 2);
  364. // 交换高低位,低位在前高位在后
  365. return result.substring(2, 4)+result.substring(0, 2);
  366. }
  367. public Object getRequestContent(HttpServletRequest request,String key){
  368. return request.getParameter(key);
  369. }
  370. /**
  371. * 获取请求参数
  372. * @param request 请求对象
  373. * @param key 参数值
  374. * @param type 参数类型 1 int 2 string
  375. * @return
  376. */
  377. public Object getRequestContent(HttpServletRequest request,String key,Integer type){
  378. if (type == 1){ // 获取 int 数据
  379. Integer keyId = request.getParameter(key) == null || request.getParameter(key).length() == 0? 0 : Integer.parseInt(request.getParameter(key));
  380. return keyId;
  381. }else if (type == 2){
  382. String keyStr = request.getParameter(key) == null ? "" : request.getParameter(key).toString();
  383. return keyStr;
  384. }
  385. return request.getParameter(key);
  386. }
  387. /**
  388. * 发送post请求
  389. * @param url 请求地址
  390. * @param paraMap 请求参数
  391. * @return
  392. */
  393. public String httpPost(String url,Map paraMap){
  394. HttpClient httpClient = new HttpClient();
  395. httpClient.getHttpConnectionManager().getParams().setSoTimeout(30000);
  396. PostMethod postMethod = new PostMethod(url);
  397. postMethod.addRequestHeader("accept", "*/*");
  398. //设置Content-Type
  399. postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  400. //添加请求参数
  401. Set set = paraMap.keySet();
  402. for (Object s : set) {
  403. postMethod.addParameter((String) s, (String) paraMap.get(s));
  404. }
  405. String result = "";
  406. try {
  407. int code = httpClient.executeMethod(postMethod);
  408. if (code == 200){
  409. result = postMethod.getResponseBodyAsString();
  410. }
  411. } catch (IOException e) {
  412. // e.printStackTrace();
  413. }
  414. return result;
  415. }
  416. /**
  417. * 发送post请求
  418. * @param url 请求地址
  419. * @param paraMap 请求参数
  420. * @param timeout 超时时间
  421. * @return
  422. */
  423. public String httpPost(String url,Map paraMap,int timeout){
  424. HttpClient httpClient = new HttpClient();
  425. httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);
  426. PostMethod postMethod = new PostMethod(url);
  427. postMethod.addRequestHeader("accept", "*/*");
  428. //设置Content-Type
  429. postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  430. //添加请求参数
  431. Set set = paraMap.keySet();
  432. for (Object s : set) {
  433. postMethod.addParameter((String) s, (String) paraMap.get(s));
  434. }
  435. String result = "";
  436. try {
  437. int code = httpClient.executeMethod(postMethod);
  438. if (code == 200){
  439. result = postMethod.getResponseBodyAsString();
  440. }
  441. } catch (IOException e) {
  442. // e.printStackTrace();
  443. }
  444. return result;
  445. }
  446. /**
  447. * 通过id获取控制器型号名称
  448. * @param id
  449. * @return
  450. */
  451. public String getLampControlNameById(Integer id){
  452. for (LampControlTypeEnum value : LampControlTypeEnum.values()) {
  453. if (value.getId().intValue() == id.intValue()){
  454. return value.getName();
  455. }
  456. }
  457. return "";
  458. }
  459. /**
  460. * 通过控制器型号名称获取型号id
  461. * @param id
  462. * @return
  463. */
  464. public Integer getLampControlIdByName(String name){
  465. for (LampControlTypeEnum value : LampControlTypeEnum.values()) {
  466. if (value.getName().equals(name)){
  467. return value.getId();
  468. }
  469. }
  470. return 0;
  471. }
  472. /**
  473. * 获取文件的大小
  474. * @param path 文件的路径
  475. * @return 返回文件的大小(四舍五入)
  476. */
  477. public String getFileSize(String path) throws IOException {
  478. String urlStr = path;
  479. if (!urlStr.contains("https://") && !urlStr.contains("http://")) {
  480. urlStr = "http://" + urlStr;
  481. }
  482. URL url = new URL(urlStr);
  483. URLConnection connection = url.openConnection();
  484. long fileSize = connection.getContentLengthLong();
  485. DecimalFormat decimalFormat = new DecimalFormat("0.00");
  486. if (fileSize != -1) {
  487. double fileSizeMB = (double) fileSize / (1024 * 1024);
  488. return decimalFormat.format(fileSizeMB);
  489. } else {
  490. return null;
  491. }
  492. }
  493. /**
  494. * 计算两个经纬度之间的距离
  495. * @param gpsFrom 第一个经纬度坐标点
  496. * @param gpsTo 第二个经纬度坐标点
  497. * @param ellipsoid 坐标系
  498. * @return 返回两者之间的距离
  499. */
  500. public static double getDistanceMeter(GlobalCoordinates gpsFrom, GlobalCoordinates gpsTo, Ellipsoid ellipsoid) {
  501. //创建GeodeticCalculator,调用计算方法,传入坐标系,经纬度用于计算距离
  502. GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo);
  503. return geoCurve.getEllipsoidalDistance();
  504. }
  505. /**
  506. * 检查密码组合是否包含字母和数字
  507. * @param pwd 密码
  508. * @return true、false
  509. */
  510. public static Boolean checkPassword(String pwd) {
  511. boolean isFlag;
  512. isFlag = Pattern.matches(PATTERN, pwd);
  513. return isFlag;
  514. }
  515. }