Blame view

src/main/java/com/objecteye/utils/GlobalUtil.java 16.4 KB
c83b5b39   Liu Haoyu   项目创建, 集成spring-se...
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
  package com.objecteye.utils;
  
  import com.objecteye.exception.CustomXException;
  import org.apache.http.Consts;
  import org.apache.http.HttpEntity;
  import org.apache.http.client.methods.CloseableHttpResponse;
  import org.apache.http.client.methods.HttpPost;
  import org.apache.http.entity.mime.MultipartEntityBuilder;
  import org.apache.http.entity.mime.content.FileBody;
  import org.apache.http.entity.mime.content.StringBody;
  import org.apache.http.impl.client.CloseableHttpClient;
  import org.apache.http.impl.client.HttpClients;
  import org.apache.http.util.EntityUtils;
  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;
  import org.springframework.boot.system.ApplicationHome;
  import sun.misc.BASE64Decoder;
  
  import javax.imageio.ImageIO;
  import java.awt.image.BufferedImage;
  import java.awt.image.ComponentSampleModel;
  import java.io.*;
  import java.net.HttpURLConnection;
  import java.net.URL;
  import java.net.URLConnection;
  import java.text.SimpleDateFormat;
  import java.util.*;
  import java.util.regex.Pattern;
  
  public class GlobalUtil {
      private static Logger logger = LoggerFactory.getLogger(GlobalUtil.class);
  
      public final static String IPWITHDEPLOYLIST = "IpWithDeployList";
      public final static String EQUIPMENTIPANDID = "equipmentIpAndId";
      public final static String PREVIEWIPLISTLIST = "previewIpList";
      public final static String ALARMMSG = "alarmMsg";
      public final static String DEPLOYIDANDENDTIME = "deployIdAndTime";
  
      public final static String COMMON_HEADER_CONTENT_TYPE = "application/json;charset=UTF-8";
  
      /**
       * redis中保存车辆特征值归一化距离信息的key
       */
      public final static String VEHICLE_FEATURE_DISTANCE = "vehicleFeatureDistance";
      /**
       * redis中保存车辆特征值信息的key
       */
      public final static String VEHICLE_FEATURE = "vehicleFeature";
  
      /**
c83b5b39   Liu Haoyu   项目创建, 集成spring-se...
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
       * 布控报警模块 -redis key-任务开始时间
       */
      public final static String DEPLOYID_STATRTIME = "deployIdAndStartTime";
  
      /**
       * 布控报警模块 -redis key-布控库id
       */
      public final static String DEPLOY_LIB = "deployLib";
      /**
       * 布控报警模块 -redis key-布控类型
       */
      public final static String DEPLOY_TYPE = "deployType";
      /**
       * 布控报警模块 -redis key-车牌信息
       */
      public final static String DEPLOY_PLATE_NUM = "deployPlateNum";
      /**
       * 布控报警模块 -redis 布控任务id-阈值
       */
      public final static String DEPLOYTHRESLD = "deployThresld";
  
  
      public final static int FACE_FEATURE_SIZE = 512;
  
      public final static int MAX_FACE_COUNT = 20;
  
      public final static int PARAM_SIZE = 62;
  
      public final static int FACIALFEAPOINTSIZE = 25;
  
      // public final static String FACE_DB_DIR = System.getProperty("user.home") + File.separator + "dbFiles" + File.separator;
  
      public final static String FACE_DB_DIR = dbPath() + File.separator;
  
      public final static String FACE_DB_SUFFIX = ".db";
  
      public final static String IMAGE_DATA_TYPE = "just using imageBase64";
  
      public final static String IMAGE_URL_TYPE = "just using imageUrl";
  
      public final static String[] METRICS_NAMES_COUNT = {"system.cpu.count", "jvm.threads.daemon", "tomcat.threads.current"};
  
      public final static String METRICS_PROCESS_START_TIME = "process.start.time";
  
      public final static String METRICS_PROCESS_UP_TIME = "process.uptime";
  
  
      public final static String[] METRICS_NAMES_MEMORY = {"jvm.memory.max", "jvm.memory.used"};
  
      public final static String[] METRICS_NAMES_PERCENT = {"process.cpu.usage", "system.cpu.usage"};
  
      public final static String LIBRARY_PREFIX = "LIBRARY_DB_";
  
      public final static String LIBRARY_PREFIX1 = "LIBRARY_HANDLE_";
  
      public final static String LIBRARY_INFO_PREFIX = "LIBRARY_INFO_";
  
      public static BufferedImage decodeBASE64ToBufferedImge(String imagebase64) {
  
          BufferedImage bufferedImage = null;
          try {
              byte[] bytes = Base64.getDecoder().decode(imagebase64);
              ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
              bufferedImage = ImageIO.read(stream);
          } catch (IOException e) {
              logger.error("method:decodeBASE64ToBufferedImge,info:decodeBASE64ToBufferedImge failed,IOException");
          }
          return bufferedImage;
      }
  
      public static byte[] getMatrixBGR(BufferedImage image) {
          if (null == image)
              throw new NullPointerException();
          byte[] matrixBGR;
          if (isBGR3Byte(image)) {
              matrixBGR = (byte[]) image.getData().getDataElements(0, 0, image.getWidth(), image.getHeight(), null);
          } else {
              int intrgb[] = image.getRGB(0, 0, image.getWidth(), image.getHeight(), null, 0, image.getWidth());
              matrixBGR = new byte[image.getWidth() * image.getHeight() * 3];
              for (int i = 0, j = 0; i < intrgb.length; ++i, j += 3) {
                  matrixBGR[j] = (byte) (intrgb[i] & 0xff);
                  matrixBGR[j + 1] = (byte) ((intrgb[i] >> 8) & 0xff);
                  matrixBGR[j + 2] = (byte) ((intrgb[i] >> 16) & 0xff);
              }
          }
          return matrixBGR;
      }
  
      public static boolean isBGR3Byte(BufferedImage image) {
          return equalBandOffsetWith3Byte(image, new int[]{0, 1, 2});
      }
  
      private static boolean equalBandOffsetWith3Byte(BufferedImage image, int[] bandOffset) {
          if (image.getType() == BufferedImage.TYPE_3BYTE_BGR) {
              if (image.getData().getSampleModel() instanceof ComponentSampleModel) {
                  ComponentSampleModel sampleModel = (ComponentSampleModel) image.getData().getSampleModel();
                  if (Arrays.equals(sampleModel.getBandOffsets(), bandOffset)) {
                      return true;
                  }
              }
  
          }
          return false;
      }
  
      public static BufferedImage imageUrlToBufferedImge(String imageUrl) throws IOException {
          BufferedImage bufferedImage = null;
          HttpURLConnection httpUrl = null;
          URL url = null;
          InputStream in = null;
          try {
              url = new URL(imageUrl);
              httpUrl = (HttpURLConnection) url.openConnection();
              httpUrl.connect();
              in = httpUrl.getInputStream();
              bufferedImage = ImageIO.read(in);
          } finally {
              if (in != null) {
                  try {
                      in.close();
                      httpUrl.disconnect();
                  } catch (IOException e) {
                      logger.error("method:imageUrlToBufferedImge,info:imageUrlToBufferedImge failed,IOException");
                      e.printStackTrace();
                  }
              }
          }
          return bufferedImage;
      }
  
      public static boolean checkBase64(String imageBase64) {
          String base64Pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
          if (!Pattern.matches(base64Pattern, imageBase64)) {
              return false;
          }
          return true;
      }
  
      public static String featureToString(float[] feature) {
          StringBuffer sb = new StringBuffer();
          sb.append("[");
          for (int l = 0; l < feature.length; l++) {
              sb.append(feature[l]);
              if (l < feature.length - 1) {
                  sb.append(",");
              }
          }
          sb.append("]");
          return sb.toString();
      }
  
      public static float[] featureToFloat(String featureStr) {
          float[] feature = new float[GlobalUtil.FACE_FEATURE_SIZE];
          String[] feaArray = featureStr.trim().replace("[", "").replace("]", "").split(",");
          if (feaArray.length != GlobalUtil.FACE_FEATURE_SIZE) {
              Map<String, Object> re = new HashMap<>(16);
              re.put("result", new ArrayList<>());
              throw new CustomXException(CustomInfoCollections.REQUEST_FEATURE_LENGTH_ERROR.getMsg(), CustomInfoCollections.REQUEST_FEATURE_LENGTH_ERROR.getCode(), re);
          }
          for (int i = 0; i < feaArray.length; i++) {
              feature[i] = Float.parseFloat(feaArray[i]);
          }
          return feature;
      }
  
      public static Integer getTimeStamp() {
          long timeStampSec = System.currentTimeMillis() / 1000;
          String timestamp = String.format("%010d", timeStampSec);
          return Integer.valueOf(timestamp);
      }
  
      public static String timeStampToTime(String timeStamp) {
          String time;
          SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
          time = simpleDateFormat.format(new Date(Long.valueOf(timeStamp)));
          return time;
      }
  
      public static float[] chooseMaxFaceRect(float[] rect, int faceCount) {
          int index = chooseMaxFaceIndex(rect, faceCount);
          for (int k = 0; k < GlobalUtil.PARAM_SIZE; k++) {
              rect[k] = rect[index * GlobalUtil.PARAM_SIZE + k];
          }
          return rect;
      }
  
      public static int chooseMaxFaceIndex(float[] rect, int faceCount) {
          int index = 0;
          float max = rect[0 * GlobalUtil.PARAM_SIZE + 2] * rect[0 * GlobalUtil.PARAM_SIZE + 3];
          for (int i = 1; i < faceCount; i++) {
              if (max < rect[i * GlobalUtil.PARAM_SIZE + 2] * rect[i * GlobalUtil.PARAM_SIZE + 3]) {
                  index = i;
                  max = rect[i * GlobalUtil.PARAM_SIZE + 2] * rect[i * GlobalUtil.PARAM_SIZE + 3];
              }
          }
          return index;
      }
  
      public static String dbPath2() {
          ApplicationHome home = new ApplicationHome(GlobalUtil.class);
          File jarFile = home.getSource();
          //File parentFile = jarFile.getParentFile().getParentFile();
          File parentFile = jarFile.getParentFile();
          return parentFile.toString();
      }
  
      public static String dbPath() {
          ApplicationHome home = new ApplicationHome(GlobalUtil.class);
          File jarFile = home.getSource();
          File parentFile = jarFile.getParentFile().getParentFile();
          //File parentFile = jarFile.getParentFile();
          return parentFile.toString();
      }
  
      public static String dbPath1() {
          ApplicationHome home = new ApplicationHome(GlobalUtil.class);
          File jarFile = home.getSource();
          File parentFile = jarFile.getParentFile().getParentFile();
          //File parentFile = jarFile.getParentFile();
          return parentFile.toString();
      }
  
      public static BufferedImage downUrl(String url) {
          BufferedImage bufferedImage = null;
          try {
              bufferedImage = GlobalUtil.imageUrlToBufferedImge(url);
          } catch (IOException e) {
              throw new CustomXException(CustomInfoCollections.IMAGE_DOWNLOAD_FAILED.getMsg(), CustomInfoCollections.IMAGE_DOWNLOAD_FAILED.getCode());
          }
          if (bufferedImage == null) {
              throw new CustomXException(CustomInfoCollections.IMAGE_DOWNLOAD_FAILED.getMsg(), CustomInfoCollections.IMAGE_DOWNLOAD_FAILED.getCode());
          }
          return bufferedImage;
      }
  
      public static BufferedImage base642BufferedImage(String base64) {
          if (!GlobalUtil.checkBase64(base64)) {
              Map<String, Object> ret = new HashMap<>();
              ret.put("result", new ArrayList<>());
              throw new CustomXException(CustomInfoCollections.IMAGE_PARSE_EXCEPTION.getMsg(), CustomInfoCollections.IMAGE_PARSE_EXCEPTION.getCode(), ret);
          }
          return GlobalUtil.decodeBASE64ToBufferedImge(base64);
      }
  
      public static Map<String, float[]> txt2String(File file) {
          StringBuilder result = new StringBuilder();
          Map<String, float[]> map = new HashMap<String, float[]>();
          float[] floats = null;
          try {
              BufferedReader br = new BufferedReader(new FileReader(file));
              String s = null;
              while ((s = br.readLine()) != null) {
                  String[] split = s.split(" ");
                  if (split.length == 513) {
                      floats = new float[512];
                      for (int i = 1; i < 513; i++) {
                          floats[i - 1] = Float.parseFloat(split[i]);
                      }
                      String id = split[0];
                      map.put(id, floats);
                  } else {
                      logger.error("格式错误");
                  }
              }
              br.close();
          } catch (Exception e) {
              e.printStackTrace();
          }
          return map;
      }
  
      public static boolean base64StrToImage(String imgStr, String path) {
          if (imgStr == null)
              return false;
          BASE64Decoder decoder = new BASE64Decoder();
          try {
              // 解密
              byte[] b = decoder.decodeBuffer(imgStr);
              // 处理数据
              for (int i = 0; i < b.length; ++i) {
                  if (b[i] < 0) {
                      b[i] += 256;
                  }
              }
              //文件夹不存在则自动创建
              File tempFile = new File(path);
              if (!tempFile.getParentFile().exists()) {
                  tempFile.getParentFile().mkdirs();
              }
              OutputStream out = new FileOutputStream(tempFile);
              out.write(b);
              out.flush();
              out.close();
              return true;
          } catch (Exception e) {
              return false;
          }
      }
  
      public static void url2Pic(String _url, String path) throws Exception {
          try {
              URL url = new URL(_url);
              URLConnection con = url.openConnection();
              con.setConnectTimeout(5000);
              InputStream is = con.getInputStream();
              byte[] bs = new byte[1024];
              int len;
              File sf = new File(path);
              OutputStream os = new FileOutputStream(sf);
              while ((len = is.read(bs)) != -1) {
                  os.write(bs, 0, len);
              }
              os.close();
              is.close();
          } catch (IOException e) {
          }
      }
  
      public static String httpExecute(String url, File file) {
  
          CloseableHttpResponse response = null;
          String resultString = "";
          try {
              CloseableHttpClient httpClient = HttpClients.createDefault();
  
              HttpPost httpPost = new HttpPost(url);
  
              FileBody fileBody = new FileBody(file, org.apache.http.entity.ContentType.create("image/png", Consts.UTF_8));
  
              HttpEntity build = MultipartEntityBuilder.create()
                      .addPart("TPXX", fileBody)
                      .build();
              httpPost.setEntity(build);
              response = httpClient.execute(httpPost);
              resultString = EntityUtils.toString(response.getEntity(), "utf-8");
  
          } catch (Exception e) {
              e.printStackTrace();
          } finally {
              try {
                  response.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
          return resultString;
      }
  
      public static String httpExecute(String url, File file, String face_id) {
  
          CloseableHttpResponse response = null;
          String resultString = "";
          try {
              CloseableHttpClient httpClient = HttpClients.createDefault();
  
              HttpPost httpPost = new HttpPost(url);
  
              FileBody fileBody = new FileBody(file, org.apache.http.entity.ContentType.create("image/png", Consts.UTF_8));
  
              HttpEntity build = MultipartEntityBuilder.create()
                      .addPart("image", fileBody)
                      .addPart("face_id", new StringBody(face_id))
                      .build();
              httpPost.setEntity(build);
              response = httpClient.execute(httpPost);
              resultString = EntityUtils.toString(response.getEntity(), "utf-8");
  
          } catch (Exception e) {
              e.printStackTrace();
          } finally {
              try {
                  response.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
          return resultString;
      }
  
      /**
       * 对字节数组字符串进行Base64解码并生成图片
       *
       * @param imgStr
       * @param imgFilePath
       * @return
       */
      public static boolean generateImage(String imgStr, String imgFilePath) {
          if (imgStr == null) {
              return false;
          }
          BASE64Decoder decoder = new BASE64Decoder();
          try {
              byte[] bytes = decoder.decodeBuffer(imgStr);
              for (int i = 0; i < bytes.length; ++i) {
                  if (bytes[i] < 0) {
                      bytes[i] += 256;
                  }
              }
              OutputStream out = new FileOutputStream(imgFilePath);
              out.write(bytes);
              out.flush();
              out.close();
              return true;
          } catch (Exception e) {
              return false;
          }
      }
  
  }