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 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 PREVIEWIPLISTLIST = "previewIpList"; public final static String ALARMMSG = "alarmMsg"; public final static String DEPLOYIDANDENDTIME = "deployIdAndTime"; /** * 已经登录的用户token相关信息, hashKey = loginUserToken, key: username, value: login time(long type) */ public final static String LOGIN_USER_TOKEN = "loginUserToken"; 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"; /** * 布控报警模块 -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 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 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 txt2String(File file) { StringBuilder result = new StringBuilder(); Map map = new HashMap(); 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; } try { // 解密 byte[] b = org.apache.commons.codec.binary.Base64.decodeBase64(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 { if (response != null) { 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; } try { byte[] bytes = org.apache.commons.codec.binary.Base64.decodeBase64(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; } } }