123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552 |
- package com.welampiot.utils;
- import com.alibaba.fastjson.JSON;
- import com.welampiot.common.BaseResult;
- import com.welampiot.common.InterfaceResultEnum;
- import com.welampiot.common.LampControlTypeEnum;
- import com.welampiot.configuration.MqttConfig;
- import com.welampiot.dto.GlobalLocationDTO;
- import com.welampiot.dto.SectionDTO;
- import com.welampiot.dto.UserDTO;
- import com.welampiot.handle.MqttHandler;
- import com.welampiot.service.GlobalLocationService;
- import com.welampiot.service.SectionService;
- import com.welampiot.service.UserService;
- import org.apache.commons.httpclient.HttpClient;
- import org.apache.commons.httpclient.methods.PostMethod;
- import org.eclipse.paho.client.mqttv3.MqttClient;
- import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
- import org.eclipse.paho.client.mqttv3.MqttMessage;
- import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
- import org.gavaghan.geodesy.Ellipsoid;
- import org.gavaghan.geodesy.GeodeticCalculator;
- import org.gavaghan.geodesy.GeodeticCurve;
- import org.gavaghan.geodesy.GlobalCoordinates;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Component;
- import javax.servlet.http.HttpServletRequest;
- import java.io.IOException;
- import java.net.URL;
- import java.net.URLConnection;
- import java.text.DecimalFormat;
- import java.util.*;
- import java.util.regex.Pattern;
- import java.util.zip.CRC32;
- @Component
- public class ToolUtils {
- private UserDTO user;
- @Autowired
- private UserService userService;
- @Autowired
- private SectionService sectionService;
- @Autowired
- private GlobalLocationService globalLocationService;
- @Autowired
- private MqttConfig mqttConfig;
- @Autowired
- private MqttHandler mqttHandler;
- private static final String PATTERN = "^(?=.*[0-9])(?=.*[a-zA-Z]).{8,20}$";
- /**
- * 获取用户所有路段 id
- * @param request
- * @return 如果返回列表为空,表示超管获取到全部路段信息,此时不需要做路段筛选
- */
- public List getSectionList(HttpServletRequest request){
- String username = request.getParameter("username");
- ArrayList<Object> sectionList = new ArrayList<>();
- if (username == null || username.toString().length() == 0) {
- sectionList.add(0);
- return sectionList;
- }
- user = userService.findUserByUserName(username);
- if (user == null) {
- sectionList.add(0);
- return sectionList;
- }
- String provinceid = request.getParameter("provinceid");
- provinceid = provinceid == null || provinceid.equals("0") ? request.getParameter("provinceId") : provinceid;
- String cityid = request.getParameter("cityid");
- cityid = cityid == null || cityid.equals("0") ? request.getParameter("cityId") : cityid;
- String areaid = request.getParameter("areaid");
- areaid = areaid == null || areaid.equals("0") ? request.getParameter("areaId") : areaid;
- String sectionid = request.getParameter("sectionid");
- sectionid = sectionid == null || sectionid.equals("0") ? request.getParameter("sectionId") : sectionid;
- if (sectionid != null && sectionid.length() != 0 && !sectionid.equals("0")){
- sectionList.add(sectionid);
- return sectionList;
- }
- String zone = user.getZoneList();
- int role = user.getRole();
- List<SectionDTO> maps;
- List<GlobalLocationDTO> globalLocationList;
- ArrayList areaList = new ArrayList<>();
- if ((cityid != null && !cityid.equals("0")) || (provinceid != null && !provinceid.equals("0")) || (areaid != null && !areaid.equals("0"))){
- if (areaid == null || areaid.equals("0")){
- ArrayList cityList = new ArrayList<>();
- if (cityid == null || cityid.equals("0")){
- globalLocationList = globalLocationService.getListByPid(Integer.valueOf(provinceid));
- if (globalLocationList.isEmpty()){
- cityid = provinceid;
- }else {
- for (GlobalLocationDTO m :globalLocationList) {
- cityList.add(m.getId());
- }
- }
- }
- if (cityList.isEmpty()){
- globalLocationList = globalLocationService.getListByPid(Integer.valueOf(cityid));
- }else {
- globalLocationList = globalLocationService.getListByPidList(cityList);
- }
- if (globalLocationList.isEmpty()){
- areaid = cityid;
- }else {
- for (GlobalLocationDTO m :globalLocationList) {
- areaList.add(m.getId());
- }
- }
- }
- }
- if ((areaid == null || areaid.length() == 0 || areaid.equals("0")) && areaList.isEmpty()){
- if (role != 1) {
- return Arrays.asList(zone.split(","));
- }else {
- return new ArrayList<>();
- }
- }else {
- if (areaid == null || areaid.equals("0")){
- maps = sectionService.getListByPidList(areaList);
- if (role != 1){
- return Arrays.asList(zone.split(","));
- }
- }else {
- System.out.println(areaid);
- int areaid2 = Integer.valueOf(areaid);
- maps = sectionService.getListByPid(areaid2);
- }
- }
- for (SectionDTO map:maps) {
- sectionList.add(map.getId());
- }
- if (sectionList.isEmpty()) sectionList.add("0");
- return sectionList;
- }
- public UserDTO getUser() {
- return user;
- }
- /**
- * 返回接口信息,不带数据
- * @param code 状态码
- * @param version 语言类型 0 中文,1 英文,2 俄语
- * @return
- */
- public BaseResult response(InterfaceResultEnum resultEnum,Integer version){
- String msg;
- String code = resultEnum.getCode();
- if (version == 0){
- msg = resultEnum.getMsgCn();} else if (version == 1) {
- msg = resultEnum.getMsgEn();
- }else {
- msg = resultEnum.getMsgRu();
- }
- BaseResult<Object> objectBaseResult = new BaseResult<>(code, msg, new Object());
- Logger paramLog = LoggerFactory.getLogger("param_log");
- paramLog.info("reponse param== "+ JSON.toJSONString(objectBaseResult));
- return objectBaseResult;
- }
- /**
- * 返回接口信息,带数据
- * @param code 状态码
- * @param version 语言类型 0 中文,1 英文,2 俄语
- * @param obj 返回数据内容
- * @return
- */
- public BaseResult response(InterfaceResultEnum resultEnum,Integer version,Object obj){
- String msg;
- String code = resultEnum.getCode();
- if (version == 0){
- msg = resultEnum.getMsgCn();
- } else if (version == 1) {
- msg = resultEnum.getMsgEn();
- }else {
- msg = resultEnum.getMsgRu();
- }
- BaseResult<Object> objectBaseResult = new BaseResult<>(code, msg, obj);
- Logger paramLog = LoggerFactory.getLogger("param_log");
- paramLog.info("reponse param== "+ JSON.toJSONString(objectBaseResult));
- return objectBaseResult;
- }
- /**
- * 发送mqtt指令
- * @param sendTopic 发送的topic
- * @param cmdInfo 发送的指令内容
- * @param resTopic 接收指令返回的topic
- * @return
- */
- public String sendMqttCmd(String sendTopic,Object cmdInfo,String resTopic){
- MqttClient client;
- String res = "";
- try {
- try {
- client=new MqttClient(mqttConfig.getUrl(),mqttConfig.getClientId()+"_"+(new Date()).getTime(),new MemoryPersistence());
- MqttConnectOptions options=new MqttConnectOptions();
- options.setCleanSession(true);
- options.setUserName(mqttConfig.getUsername());
- options.setPassword(mqttConfig.getPassword().toCharArray());
- options.setConnectionTimeout(mqttConfig.getTimeout());
- options.setKeepAliveInterval(mqttConfig.getKeepalive());
- mqttHandler.setTopic(resTopic);
- // 设置回调
- client.setCallback(mqttHandler);
- // 建立连接
- client.connect(options);
- // MqttCustomerClient.setClient(client);
- client.subscribe(resTopic);
- // 消息发布所需参数
- MqttMessage message;
- if (cmdInfo instanceof String){
- message = new MqttMessage(((String) cmdInfo).getBytes());
- }else {
- message = new MqttMessage((byte[]) cmdInfo);
- }
- message.setQos(0);
- client.publish(sendTopic, message);
- int in = 0;
- while (true){
- Thread.sleep(1000);
- if (mqttHandler.getRes() != null && mqttHandler.getRes().length() != 0){
- res = mqttHandler.getRes();
- break;
- }
- in ++;
- if (in > 30) break;
- }
- client.disconnect();
- }catch (Exception e){
- e.printStackTrace();
- }
- }catch (Exception e){
- e.printStackTrace();
- }
- return res;
- }
- /**
- * 发送mqtt指令
- * @param sendTopic 发送的topic
- * @param cmdInfo 发送的指令内容
- * @param resTopic 接收指令返回的topic
- * @param timeout 指令超时时间
- * @return
- */
- public String sendMqttCmd(String sendTopic,Object cmdInfo,String resTopic,Integer timeout){
- MqttClient client;
- String res = "";
- try {
- try {
- client=new MqttClient(mqttConfig.getUrl(),mqttConfig.getClientId()+"_"+(new Date()).getTime(),new MemoryPersistence());
- MqttConnectOptions options=new MqttConnectOptions();
- options.setCleanSession(true);
- options.setUserName(mqttConfig.getUsername());
- options.setPassword(mqttConfig.getPassword().toCharArray());
- options.setConnectionTimeout(mqttConfig.getTimeout());
- options.setKeepAliveInterval(mqttConfig.getKeepalive());
- mqttHandler.setTopic(resTopic);
- // 设置回调
- client.setCallback(mqttHandler);
- // 建立连接
- client.connect(options);
- // MqttCustomerClient.setClient(client);
- client.subscribe(resTopic);
- // 消息发布所需参数
- MqttMessage message;
- if (cmdInfo instanceof String){
- message = new MqttMessage(((String) cmdInfo).getBytes());
- }else {
- message = new MqttMessage((byte[]) cmdInfo);
- }
- message.setQos(0);
- client.publish(sendTopic, message);
- int in = 0;
- if (timeout > 0){
- while (true){
- Thread.sleep(1000);
- if (mqttHandler.getRes() != null && mqttHandler.getRes().length() != 0){
- res = mqttHandler.getRes();
- break;
- }
- in ++;
- if (in > timeout) break;
- }
- }
- client.disconnect();
- }catch (Exception e){
- e.printStackTrace();
- }
- }catch (Exception e){
- e.printStackTrace();
- }
- return res;
- }
- /**
- * 字节数组转16进制字符串
- * @param b 字节数组
- * @return 16进制字符串
- * @throws
- */
- public static String bytes2HexString(byte[] b) {
- StringBuffer result = new StringBuffer();
- String hex;
- for (int i = 0; i < b.length; i++) {
- hex = Integer.toHexString(b[i] & 0xFF);
- if (hex.length() == 1) {
- hex = '0' + hex;
- }
- result.append(hex.toUpperCase());
- }
- return result.toString();
- }
- /**
- * 16进制字符串转字节数组
- * @param src 16进制字符串
- * @return 字节数组
- * @throws
- */
- public byte[] hexString2Bytes(String src) {
- int l = src.length() / 2;
- byte[] ret = new byte[l];
- for (int i = 0; i < l; i++) {
- ret[i] = (byte) Integer
- .valueOf(src.substring(i * 2, i * 2 + 2), 16).byteValue();
- }
- return ret;
- }
- /**
- * 获取CRC32校验码
- * @param src 16进制字符串
- * @return CRC32校验码
- */
- public String getCRC32ByHexString2Bytes(String src) {
- CRC32 crc32 = new CRC32();
- crc32.update(this.hexString2Bytes(src));
- return Integer.toHexString((int) crc32.getValue());
- }
- /**
- * 计算modbus CRC16校验码
- * @param bytes 需要计算的数据
- * @return
- */
- public String getCRC(byte[] bytes) {
- // CRC寄存器全为1
- int CRC = 0x0000ffff;
- // 多项式校验值
- int POLYNOMIAL = 0x0000a001;
- int i, j;
- for (i = 0; i < bytes.length; i++) {
- CRC ^= ((int) bytes[i] & 0x000000ff);
- for (j = 0; j < 8; j++) {
- if ((CRC & 0x00000001) != 0) {
- CRC >>= 1;
- CRC ^= POLYNOMIAL;
- } else {
- CRC >>= 1;
- }
- }
- }
- // 结果转换为16进制
- String result = Integer.toHexString(CRC).toUpperCase();
- if (result.length() != 4) {
- StringBuffer sb = new StringBuffer("0000");
- result = sb.replace(4 - result.length(), 4, result).toString();
- }
- //高位在前地位在后
- //return result.substring(2, 4) + " " + result.substring(0, 2);
- // 交换高低位,低位在前高位在后
- return result.substring(2, 4)+result.substring(0, 2);
- }
- public Object getRequestContent(HttpServletRequest request,String key){
- return request.getParameter(key);
- }
- /**
- * 获取请求参数
- * @param request 请求对象
- * @param key 参数值
- * @param type 参数类型 1 int 2 string
- * @return
- */
- public Object getRequestContent(HttpServletRequest request,String key,Integer type){
- if (type == 1){ // 获取 int 数据
- Integer keyId = request.getParameter(key) == null || request.getParameter(key).length() == 0? 0 : Integer.parseInt(request.getParameter(key));
- return keyId;
- }else if (type == 2){
- String keyStr = request.getParameter(key) == null ? "" : request.getParameter(key).toString();
- return keyStr;
- }
- return request.getParameter(key);
- }
- /**
- * 发送post请求
- * @param url 请求地址
- * @param paraMap 请求参数
- * @return
- */
- public String httpPost(String url,Map paraMap){
- HttpClient httpClient = new HttpClient();
- httpClient.getHttpConnectionManager().getParams().setSoTimeout(30000);
- PostMethod postMethod = new PostMethod(url);
- postMethod.addRequestHeader("accept", "*/*");
- //设置Content-Type
- postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
- //添加请求参数
- Set set = paraMap.keySet();
- for (Object s : set) {
- postMethod.addParameter((String) s, (String) paraMap.get(s));
- }
- String result = "";
- try {
- int code = httpClient.executeMethod(postMethod);
- if (code == 200){
- result = postMethod.getResponseBodyAsString();
- }
- } catch (IOException e) {
- // e.printStackTrace();
- }
- return result;
- }
- /**
- * 发送post请求
- * @param url 请求地址
- * @param paraMap 请求参数
- * @param timeout 超时时间
- * @return
- */
- public String httpPost(String url,Map paraMap,int timeout){
- HttpClient httpClient = new HttpClient();
- httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);
- PostMethod postMethod = new PostMethod(url);
- postMethod.addRequestHeader("accept", "*/*");
- //设置Content-Type
- postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
- //添加请求参数
- Set set = paraMap.keySet();
- for (Object s : set) {
- postMethod.addParameter((String) s, (String) paraMap.get(s));
- }
- String result = "";
- try {
- int code = httpClient.executeMethod(postMethod);
- if (code == 200){
- result = postMethod.getResponseBodyAsString();
- }
- } catch (IOException e) {
- // e.printStackTrace();
- }
- return result;
- }
- /**
- * 通过id获取控制器型号名称
- * @param id
- * @return
- */
- public String getLampControlNameById(Integer id){
- for (LampControlTypeEnum value : LampControlTypeEnum.values()) {
- if (value.getId().intValue() == id.intValue()){
- return value.getName();
- }
- }
- return "";
- }
- /**
- * 通过控制器型号名称获取型号id
- * @param id
- * @return
- */
- public Integer getLampControlIdByName(String name){
- for (LampControlTypeEnum value : LampControlTypeEnum.values()) {
- if (value.getName().equals(name)){
- return value.getId();
- }
- }
- return 0;
- }
- /**
- * 获取文件的大小
- * @param path 文件的路径
- * @return 返回文件的大小(四舍五入)
- */
- public String getFileSize(String path) throws IOException {
- String urlStr = path;
- if (!urlStr.contains("https://") && !urlStr.contains("http://")) {
- urlStr = "http://" + urlStr;
- }
- URL url = new URL(urlStr);
- URLConnection connection = url.openConnection();
- long fileSize = connection.getContentLengthLong();
- DecimalFormat decimalFormat = new DecimalFormat("0.00");
- if (fileSize != -1) {
- double fileSizeMB = (double) fileSize / (1024 * 1024);
- return decimalFormat.format(fileSizeMB);
- } else {
- return null;
- }
- }
- /**
- * 计算两个经纬度之间的距离
- * @param gpsFrom 第一个经纬度坐标点
- * @param gpsTo 第二个经纬度坐标点
- * @param ellipsoid 坐标系
- * @return 返回两者之间的距离
- */
- public static double getDistanceMeter(GlobalCoordinates gpsFrom, GlobalCoordinates gpsTo, Ellipsoid ellipsoid) {
- //创建GeodeticCalculator,调用计算方法,传入坐标系,经纬度用于计算距离
- GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo);
- return geoCurve.getEllipsoidalDistance();
- }
- /**
- * 检查密码组合是否包含字母和数字
- * @param pwd 密码
- * @return true、false
- */
- public static Boolean checkPassword(String pwd) {
- boolean isFlag;
- isFlag = Pattern.matches(PATTERN, pwd);
- return isFlag;
- }
- }
|