mirror of
https://github.com/hpd840321/starRiverProperty.git
synced 2026-06-11 17:30:29 +08:00
fix: replace 43 service files with alt decompiler versions
Alt source (JD-GUI/Procyon based): preserves generics, 0 raw Lists, 0 (Object) casts But introduces lambda corruption (.map(()), .forEach(()), computeIfAbsent(()) Replaced 43 files where alt has significantly fewer errors: - OrganizationServiceImpl: 141 (Object) casts → 0 - CpImageStoreToolServiceImpl: 79 (Object) casts → 0 - ImgPersonServiceImpl: 37 (Object) casts → 0 - And 40 more files with similar improvements Remaining: 200 errors (different distribution than CFR baseline) - Mostly lambda corruption from alt decompiler - Fixable with targeted .map(())→orElse, forEach(())→reconstruction
This commit is contained in:
+99
-96
@@ -1,14 +1,16 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
// 业务服务
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.MathContext;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.List;
|
||||
import javax.imageio.ImageIO;
|
||||
import org.apache.commons.imaging.ImageReadException;
|
||||
import org.apache.commons.imaging.Imaging;
|
||||
import org.apache.commons.imaging.common.ImageMetadata;
|
||||
import org.apache.commons.imaging.formats.tiff.TiffField;
|
||||
import org.apache.commons.imaging.formats.tiff.TiffImageMetadata;
|
||||
@@ -16,100 +18,101 @@ import org.apache.commons.imaging.formats.tiff.constants.TiffTagConstants;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class ImageEditUtils {
|
||||
private static final Logger log = LoggerFactory.getLogger(ImageEditUtils.class);
|
||||
public static final int CIRCLE = 360;
|
||||
public static final int ZERO = 0;
|
||||
|
||||
private ImageEditUtils() {
|
||||
}
|
||||
|
||||
/*
|
||||
* Exception decompiling
|
||||
*/
|
||||
public static byte[] reduce(byte[] bytes, int targetWidth) {
|
||||
/*
|
||||
* This method has failed to decompile. When submitting a bug report, please provide this stack trace, and (if you hold appropriate legal rights) the relevant class file.
|
||||
*
|
||||
* org.benf.cfr.reader.util.ConfusedCFRException: Started 2 blocks at once
|
||||
* at org.benf.cfr.reader.bytecode.analysis.opgraph.Op04StructuredStatement.getStartingBlocks(Op04StructuredStatement.java:412)
|
||||
* at org.benf.cfr.reader.bytecode.analysis.opgraph.Op04StructuredStatement.buildNestedBlocks(Op04StructuredStatement.java:487)
|
||||
* at org.benf.cfr.reader.bytecode.analysis.opgraph.Op03SimpleStatement.createInitialStructuredBlock(Op03SimpleStatement.java:736)
|
||||
* at org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysisInner(CodeAnalyser.java:850)
|
||||
* at org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysisOrWrapFail(CodeAnalyser.java:278)
|
||||
* at org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysis(CodeAnalyser.java:201)
|
||||
* at org.benf.cfr.reader.entities.attributes.AttributeCode.analyse(AttributeCode.java:94)
|
||||
* at org.benf.cfr.reader.entities.Method.analyse(Method.java:531)
|
||||
* at org.benf.cfr.reader.entities.ClassFile.analyseMid(ClassFile.java:1055)
|
||||
* at org.benf.cfr.reader.entities.ClassFile.analyseTop(ClassFile.java:942)
|
||||
* at org.benf.cfr.reader.Driver.doJarVersionTypes(Driver.java:257)
|
||||
* at org.benf.cfr.reader.Driver.doJar(Driver.java:139)
|
||||
* at org.benf.cfr.reader.CfrDriverImpl.analyse(CfrDriverImpl.java:76)
|
||||
* at org.benf.cfr.reader.Main.main(Main.java:54)
|
||||
*/
|
||||
throw new IllegalStateException("Decompilation failed");
|
||||
}
|
||||
|
||||
public static float getRate(int targetWidth, int width) {
|
||||
float rate = 1.0f;
|
||||
if (width > targetWidth) {
|
||||
BigDecimal b1 = new BigDecimal(targetWidth);
|
||||
MathContext mc = new MathContext(2, RoundingMode.HALF_UP);
|
||||
BigDecimal b2 = new BigDecimal(width);
|
||||
return b1.divide(b2, mc).floatValue();
|
||||
}
|
||||
log.debug("rate={}", (Object)Float.valueOf(rate));
|
||||
return rate;
|
||||
}
|
||||
|
||||
public static int getImgRotateAngle(File jpegImageFile) throws ServiceException {
|
||||
try {
|
||||
int angel = 0;
|
||||
int orientation = 1;
|
||||
ImageMetadata metadata = Imaging.getMetadata((File)jpegImageFile);
|
||||
if (metadata == null) {
|
||||
return 0;
|
||||
}
|
||||
List metadataItems = metadata.getItems();
|
||||
for (ImageMetadata.ImageMetadataItem metadataItem : metadataItems) {
|
||||
TiffField tiffField;
|
||||
if (!(metadataItem instanceof TiffImageMetadata.TiffMetadataItem) || !(tiffField = ((TiffImageMetadata.TiffMetadataItem)metadataItem).getTiffField()).getTagInfo().equals(TiffTagConstants.TIFF_TAG_ORIENTATION)) continue;
|
||||
Object orientationValue = tiffField.getValue();
|
||||
if (orientationValue == null) break;
|
||||
orientation = Integer.parseInt(orientationValue.toString());
|
||||
break;
|
||||
}
|
||||
if (6 == orientation) {
|
||||
angel = 90;
|
||||
} else if (3 == orientation) {
|
||||
angel = 180;
|
||||
} else if (8 == orientation) {
|
||||
angel = 270;
|
||||
}
|
||||
return angel;
|
||||
}
|
||||
catch (IOException | NumberFormatException | ImageReadException e) {
|
||||
throw new ServiceException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static int rotateAngle(File jpegImageFile) {
|
||||
try {
|
||||
int old = ImageEditUtils.getImgRotateAngle(jpegImageFile);
|
||||
int now = 360 - old;
|
||||
log.debug("图片原角度:{} 现角度:{}", (Object)old, (Object)now);
|
||||
return now;
|
||||
}
|
||||
catch (ServiceException e) {
|
||||
log.error("图片原角度识别失败", e);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isRotate(int now) throws ServiceException {
|
||||
return 0 != now && 360 != now;
|
||||
}
|
||||
private static final Logger log = LoggerFactory.getLogger(ImageEditUtils.class);
|
||||
public static final int CIRCLE = 360;
|
||||
public static final int ZERO = 0;
|
||||
public static byte[] reduce(byte[] bytes, int targetWidth) {
|
||||
int width;
|
||||
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes)) {
|
||||
BufferedImage bufferedImage = ImageIO.read(bais);
|
||||
width = bufferedImage.getWidth();
|
||||
if (targetWidth >= width) {
|
||||
return bytes;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("ImageEditUtils reduce fail IOException", e);
|
||||
return bytes;
|
||||
}
|
||||
try(ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
|
||||
float rate = getRate(targetWidth, width);
|
||||
Thumbnails.of(new InputStream[] { bais }).scale(rate).toOutputStream(baos);
|
||||
byte[] scaleBytes = baos.toByteArray();
|
||||
return scaleBytes;
|
||||
} catch (IOException e) {
|
||||
log.error("ImageEditUtils reduce fail", e);
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
public static float getRate(int targetWidth, int width) {
|
||||
float rate = 1.0F;
|
||||
if (width > targetWidth) {
|
||||
BigDecimal b1 = new BigDecimal(targetWidth);
|
||||
MathContext mc = new MathContext(2, RoundingMode.HALF_UP);
|
||||
BigDecimal b2 = new BigDecimal(width);
|
||||
return b1.divide(b2, mc).floatValue();
|
||||
}
|
||||
log.debug("rate={}", Float.valueOf(rate));
|
||||
return rate;
|
||||
}
|
||||
public static int getImgRotateAngle(File jpegImageFile) throws ServiceException {
|
||||
try {
|
||||
int angel = 0;
|
||||
int orientation = 1;
|
||||
ImageMetadata metadata = Imaging.getMetadata(jpegImageFile);
|
||||
if (metadata == null) {
|
||||
return 0;
|
||||
}
|
||||
List<? extends ImageMetadata.ImageMetadataItem> metadataItems = metadata.getItems();
|
||||
for (ImageMetadata.ImageMetadataItem metadataItem : metadataItems) {
|
||||
if (metadataItem instanceof TiffImageMetadata.TiffMetadataItem) {
|
||||
TiffField tiffField = ((TiffImageMetadata.TiffMetadataItem)metadataItem).getTiffField();
|
||||
if (!tiffField.getTagInfo().equals(TiffTagConstants.TIFF_TAG_ORIENTATION)) {
|
||||
continue;
|
||||
}
|
||||
Object orientationValue = tiffField.getValue();
|
||||
if (orientationValue == null) {
|
||||
break;
|
||||
}
|
||||
orientation = Integer.parseInt(orientationValue.toString());
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (6 == orientation) {
|
||||
angel = 90;
|
||||
} else if (3 == orientation) {
|
||||
angel = 180;
|
||||
} else if (8 == orientation) {
|
||||
angel = 270;
|
||||
}
|
||||
return angel;
|
||||
} catch (ImageReadException|IOException|NumberFormatException e) {
|
||||
throw new ServiceException(e);
|
||||
}
|
||||
}
|
||||
public static int rotateAngle(File jpegImageFile) {
|
||||
try {
|
||||
int old = getImgRotateAngle(jpegImageFile);
|
||||
int now = 360 - old;
|
||||
log.debug("图片原角度:{} 现角度:{}", Integer.valueOf(old), Integer.valueOf(now));
|
||||
return now;
|
||||
} catch (ServiceException e) {
|
||||
log.error("图片原角度识别失败", (Throwable)e);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
public static boolean isRotate(int now) throws ServiceException {
|
||||
if (0 == now || 360 == now) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/common/ImageEditUtils.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+111
-106
@@ -1,122 +1,127 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
// 业务服务
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.Closeable;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.util.Base64;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class ImageUtil {
|
||||
private static final Logger log = LoggerFactory.getLogger(ImageUtil.class);
|
||||
|
||||
private ImageUtil() {
|
||||
}
|
||||
|
||||
/*
|
||||
* Exception decompiling
|
||||
*/
|
||||
public static String encodeImageToBase64(String urlStr) {
|
||||
/*
|
||||
* This method has failed to decompile. When submitting a bug report, please provide this stack trace, and (if you hold appropriate legal rights) the relevant class file.
|
||||
*
|
||||
* org.benf.cfr.reader.util.ConfusedCFRException: Started 2 blocks at once
|
||||
* at org.benf.cfr.reader.bytecode.analysis.opgraph.Op04StructuredStatement.getStartingBlocks(Op04StructuredStatement.java:412)
|
||||
* at org.benf.cfr.reader.bytecode.analysis.opgraph.Op04StructuredStatement.buildNestedBlocks(Op04StructuredStatement.java:487)
|
||||
* at org.benf.cfr.reader.bytecode.analysis.opgraph.Op03SimpleStatement.createInitialStructuredBlock(Op03SimpleStatement.java:736)
|
||||
* at org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysisInner(CodeAnalyser.java:850)
|
||||
* at org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysisOrWrapFail(CodeAnalyser.java:278)
|
||||
* at org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysis(CodeAnalyser.java:201)
|
||||
* at org.benf.cfr.reader.entities.attributes.AttributeCode.analyse(AttributeCode.java:94)
|
||||
* at org.benf.cfr.reader.entities.Method.analyse(Method.java:531)
|
||||
* at org.benf.cfr.reader.entities.ClassFile.analyseMid(ClassFile.java:1055)
|
||||
* at org.benf.cfr.reader.entities.ClassFile.analyseTop(ClassFile.java:942)
|
||||
* at org.benf.cfr.reader.Driver.doJarVersionTypes(Driver.java:257)
|
||||
* at org.benf.cfr.reader.Driver.doJar(Driver.java:139)
|
||||
* at org.benf.cfr.reader.CfrDriverImpl.analyse(CfrDriverImpl.java:76)
|
||||
* at org.benf.cfr.reader.Main.main(Main.java:54)
|
||||
*/
|
||||
throw new IllegalStateException("Decompilation failed");
|
||||
}
|
||||
|
||||
/*
|
||||
* Exception decompiling
|
||||
*/
|
||||
public static byte[] encodeImageToByte(String urlStr) {
|
||||
/*
|
||||
* This method has failed to decompile. When submitting a bug report, please provide this stack trace, and (if you hold appropriate legal rights) the relevant class file.
|
||||
*
|
||||
* org.benf.cfr.reader.util.ConfusedCFRException: Started 2 blocks at once
|
||||
* at org.benf.cfr.reader.bytecode.analysis.opgraph.Op04StructuredStatement.getStartingBlocks(Op04StructuredStatement.java:412)
|
||||
* at org.benf.cfr.reader.bytecode.analysis.opgraph.Op04StructuredStatement.buildNestedBlocks(Op04StructuredStatement.java:487)
|
||||
* at org.benf.cfr.reader.bytecode.analysis.opgraph.Op03SimpleStatement.createInitialStructuredBlock(Op03SimpleStatement.java:736)
|
||||
* at org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysisInner(CodeAnalyser.java:850)
|
||||
* at org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysisOrWrapFail(CodeAnalyser.java:278)
|
||||
* at org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysis(CodeAnalyser.java:201)
|
||||
* at org.benf.cfr.reader.entities.attributes.AttributeCode.analyse(AttributeCode.java:94)
|
||||
* at org.benf.cfr.reader.entities.Method.analyse(Method.java:531)
|
||||
* at org.benf.cfr.reader.entities.ClassFile.analyseMid(ClassFile.java:1055)
|
||||
* at org.benf.cfr.reader.entities.ClassFile.analyseTop(ClassFile.java:942)
|
||||
* at org.benf.cfr.reader.Driver.doJarVersionTypes(Driver.java:257)
|
||||
* at org.benf.cfr.reader.Driver.doJar(Driver.java:139)
|
||||
* at org.benf.cfr.reader.CfrDriverImpl.analyse(CfrDriverImpl.java:76)
|
||||
* at org.benf.cfr.reader.Main.main(Main.java:54)
|
||||
*/
|
||||
throw new IllegalStateException("Decompilation failed");
|
||||
}
|
||||
|
||||
public static String encodeByte2Base64(byte[] image) {
|
||||
String base64 = Base64.getEncoder().encodeToString(image);
|
||||
String reg = "[\n-\r]";
|
||||
Pattern p = Pattern.compile(reg);
|
||||
Matcher m = p.matcher(base64);
|
||||
base64 = m.replaceAll("");
|
||||
return base64;
|
||||
}
|
||||
|
||||
public static void byte2File(byte[] image, String filePath) {
|
||||
try (BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(image));
|
||||
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(new File(filePath)));){
|
||||
byte[] buffer = new byte[1024];
|
||||
int length = bis.read(buffer);
|
||||
while (length != -1) {
|
||||
output.write(buffer, 0, length);
|
||||
length = bis.read(buffer);
|
||||
}
|
||||
output.flush();
|
||||
}
|
||||
catch (IOException e) {
|
||||
log.error("exception:{}", (Object)e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static void closeStream(Closeable stream) {
|
||||
try {
|
||||
if (stream != null) {
|
||||
stream.close();
|
||||
}
|
||||
}
|
||||
catch (IOException e) {
|
||||
log.error("关闭资源失败,{}", (Object)e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static void close(Closeable ... closeableList) {
|
||||
try {
|
||||
for (Closeable closeable : closeableList) {
|
||||
if (closeable == null) continue;
|
||||
closeable.close();
|
||||
}
|
||||
}
|
||||
catch (IOException e) {
|
||||
log.error("关闭资源失败,{}", (Object)e.getMessage());
|
||||
}
|
||||
}
|
||||
private static final Logger log = LoggerFactory.getLogger(ImageUtil.class);
|
||||
public static String encodeImageToBase64(String urlStr) {
|
||||
HttpURLConnection conn = null;
|
||||
try {
|
||||
URL url = new URL(urlStr);
|
||||
conn = (HttpURLConnection)url.openConnection();
|
||||
conn.setRequestMethod("GET");
|
||||
conn.setConnectTimeout(5000);
|
||||
} catch (IOException e) {
|
||||
log.error("图片请求失败", e);
|
||||
return "img_download_parse_error";
|
||||
}
|
||||
try(InputStream inStream = conn.getInputStream();
|
||||
ByteArrayOutputStream outStream = new ByteArrayOutputStream()) {
|
||||
byte[] buffer = new byte[1024];
|
||||
int len = 0;
|
||||
while ((len = inStream.read(buffer)) != -1)
|
||||
{
|
||||
outStream.write(buffer, 0, len);
|
||||
}
|
||||
inStream.close();
|
||||
byte[] data = outStream.toByteArray();
|
||||
String base64 = Base64.getEncoder().encodeToString(data);
|
||||
String reg = "[\n-\r]";
|
||||
Pattern p = Pattern.compile(reg);
|
||||
Matcher m = p.matcher(base64);
|
||||
base64 = m.replaceAll("");
|
||||
return base64;
|
||||
} catch (IOException e) {
|
||||
log.error("图片下载失败,{}", e.getMessage());
|
||||
return "img_download_parse_error";
|
||||
}
|
||||
}
|
||||
public static byte[] encodeImageToByte(String urlStr) {
|
||||
HttpURLConnection conn = null;
|
||||
try {
|
||||
URL url = new URL(urlStr);
|
||||
conn = (HttpURLConnection)url.openConnection();
|
||||
conn.setRequestMethod("GET");
|
||||
conn.setConnectTimeout(5000);
|
||||
} catch (IOException e) {
|
||||
log.error("图片请求失败", e);
|
||||
return new byte[0];
|
||||
}
|
||||
try(InputStream inStream = conn.getInputStream();
|
||||
ByteArrayOutputStream outStream = new ByteArrayOutputStream()) {
|
||||
byte[] buffer = new byte[1024];
|
||||
int len = 0;
|
||||
while ((len = inStream.read(buffer)) != -1)
|
||||
{
|
||||
outStream.write(buffer, 0, len);
|
||||
}
|
||||
inStream.close();
|
||||
byte[] data = outStream.toByteArray();
|
||||
return data;
|
||||
} catch (IOException e) {
|
||||
log.error("图片下载失败", e);
|
||||
return new byte[0];
|
||||
}
|
||||
}
|
||||
public static String encodeByte2Base64(byte[] image) {
|
||||
String base64 = Base64.getEncoder().encodeToString(image);
|
||||
String reg = "[\n-\r]";
|
||||
Pattern p = Pattern.compile(reg);
|
||||
Matcher m = p.matcher(base64);
|
||||
base64 = m.replaceAll("");
|
||||
return base64;
|
||||
}
|
||||
public static void byte2File(byte[] image, String filePath) {
|
||||
try(BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(image));
|
||||
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(new File(filePath)))) {
|
||||
byte[] buffer = new byte[1024];
|
||||
int length = bis.read(buffer);
|
||||
while (length != -1) {
|
||||
output.write(buffer, 0, length);
|
||||
length = bis.read(buffer);
|
||||
}
|
||||
output.flush();
|
||||
} catch (IOException e) {
|
||||
log.error("exception:{}", e.getMessage());
|
||||
}
|
||||
}
|
||||
public static void closeStream(Closeable stream) {
|
||||
try {
|
||||
if (stream != null) {
|
||||
stream.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("关闭资源失败,{}", e.getMessage());
|
||||
}
|
||||
}
|
||||
public static void close(Closeable... closeableList) {
|
||||
try {
|
||||
for (Closeable closeable : closeableList) {
|
||||
if (closeable != null) {
|
||||
closeable.close();
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("关闭资源失败,{}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/common/ImageUtil.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+271
-283
@@ -1,5 +1,4 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
// 业务服务
|
||||
import com.google.common.collect.Maps;
|
||||
import java.beans.BeanInfo;
|
||||
import java.beans.IntrospectionException;
|
||||
@@ -13,7 +12,6 @@ import java.io.InputStreamReader;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
@@ -21,8 +19,8 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Function;
|
||||
@@ -43,286 +41,276 @@ import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import org.springside.modules.security.utils.Digests;
|
||||
import org.springside.modules.utils.Encodes;
|
||||
|
||||
public class ToolUtil {
|
||||
public static final Logger LOGGER = LoggerFactory.getLogger(ToolUtil.class);
|
||||
public static final int HASH_INTERATIONS = 1024;
|
||||
private static final int SALT_SIZE = 8;
|
||||
private static final String EMAIL_REG = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
|
||||
private static final String CAPITAL_LETTER_REG = ".*[A-Z].*";
|
||||
private static final String UPPER_CASE_REG = ".*[a-z].*";
|
||||
private static final String SPECIAL_CHAR_REG = ".*((?=[\\x21-\\x7e]+)[^A-Za-z0-9]).*";
|
||||
private static final String NUMBER_REG = ".*[0-9].*";
|
||||
private static final String UNKNOWN = "unknown";
|
||||
|
||||
private ToolUtil() {
|
||||
}
|
||||
|
||||
public static String generateUUID() {
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
return uuid.replaceAll("-", "");
|
||||
}
|
||||
|
||||
public static String exStackTrace(Exception ex) {
|
||||
StringWriter sw = new StringWriter();
|
||||
PrintWriter pw = new PrintWriter(sw);
|
||||
ex.printStackTrace(pw);
|
||||
return sw.toString();
|
||||
}
|
||||
|
||||
public static boolean isEmail(String str) {
|
||||
if (StringUtils.isBlank((CharSequence)str)) {
|
||||
return false;
|
||||
}
|
||||
Pattern pattern = Pattern.compile(EMAIL_REG);
|
||||
Matcher isEmail = pattern.matcher(str);
|
||||
return isEmail.matches();
|
||||
}
|
||||
|
||||
public static String entryptPassword(String paramStr) {
|
||||
if (StringUtils.isNotEmpty((CharSequence)paramStr)) {
|
||||
byte[] salt = Digests.generateSalt((int)8);
|
||||
byte[] hashPassword = Digests.sha1((byte[])paramStr.getBytes(), (byte[])salt, (int)1024);
|
||||
String saltStr = Encodes.encodeHex((byte[])salt);
|
||||
String password = Encodes.encodeHex((byte[])hashPassword);
|
||||
return password + "," + saltStr;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String entryptPassword(String paramStr, String salt) {
|
||||
if (StringUtils.isNotEmpty((CharSequence)paramStr)) {
|
||||
byte[] saltStr = Encodes.decodeHex((String)salt);
|
||||
byte[] hashPassword = Digests.sha1((byte[])paramStr.getBytes(), (byte[])saltStr, (int)1024);
|
||||
String password = Encodes.encodeHex((byte[])hashPassword);
|
||||
return password;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String readFileByLines(InputStream inputStream) throws UnsupportedEncodingException, FileNotFoundException {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
try (InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8");
|
||||
BufferedReader reader = new BufferedReader(isr);){
|
||||
LOGGER.info("以行为单位读取文件内容,一次读一整行:");
|
||||
String tempString = null;
|
||||
int line = 1;
|
||||
while ((tempString = reader.readLine()) != null) {
|
||||
sb.append(tempString);
|
||||
++line;
|
||||
}
|
||||
}
|
||||
catch (IOException e) {
|
||||
LOGGER.warn(e.getMessage());
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String getClientIp(HttpServletRequest request) {
|
||||
String ip = request.getHeader("X-Real-IP");
|
||||
LOGGER.info("ipadd : {}", (Object)ip);
|
||||
if (StringUtils.isBlank((CharSequence)ip) || UNKNOWN.equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("X-Forwarded-For");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("Proxy-Client-IP");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
|
||||
ip = request.getRemoteAddr();
|
||||
}
|
||||
LOGGER.info(" ip --> {}", (Object)ip);
|
||||
return ip;
|
||||
}
|
||||
|
||||
public static String parseGBK(String sIn) {
|
||||
if (sIn == null || "".equals(sIn)) {
|
||||
return sIn;
|
||||
}
|
||||
try {
|
||||
return new String(sIn.getBytes("GBK"), StandardCharsets.ISO_8859_1);
|
||||
}
|
||||
catch (UnsupportedEncodingException usex) {
|
||||
return sIn;
|
||||
}
|
||||
}
|
||||
|
||||
public static String randomNum(int range) {
|
||||
Double rangeD = Math.pow(10.0, range);
|
||||
int result = (int)((new SecureRandom().nextDouble() * 9.0 + 1.0) * (double)rangeD.intValue());
|
||||
return String.valueOf(result);
|
||||
}
|
||||
|
||||
public static Map<String, Object> convertBeanToMap(Object condition) {
|
||||
if (condition == null) {
|
||||
return null;
|
||||
}
|
||||
if (condition instanceof Map) {
|
||||
return (Map)condition;
|
||||
}
|
||||
HashMap objectAsMap = Maps.newHashMap();
|
||||
BeanInfo info = null;
|
||||
try {
|
||||
info = Introspector.getBeanInfo(condition.getClass());
|
||||
}
|
||||
catch (IntrospectionException e) {
|
||||
LOGGER.warn(e.getMessage());
|
||||
}
|
||||
if (info != null && info.getPropertyDescriptors() != null) {
|
||||
for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
|
||||
Method reader = pd.getReadMethod();
|
||||
if (reader == null || "class".equals(pd.getName())) continue;
|
||||
try {
|
||||
objectAsMap.put(pd.getName(), reader.invoke(condition, new Object[0]));
|
||||
}
|
||||
catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
|
||||
LOGGER.warn(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
return objectAsMap;
|
||||
}
|
||||
|
||||
public static void getPassword(String password) {
|
||||
byte[] salt = Digests.generateSalt((int)8);
|
||||
LOGGER.info("salt:{}", (Object)Encodes.encodeHex((byte[])salt));
|
||||
byte[] hashPassword = Digests.sha1((byte[])password.getBytes(), (byte[])salt, (int)1024);
|
||||
LOGGER.info("hashPassword:{}", (Object)Encodes.encodeHex((byte[])hashPassword));
|
||||
}
|
||||
|
||||
public static String formatNumberToString(long number) {
|
||||
String[] format = new String[]{"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
|
||||
String[] units = new String[]{"", "十", "百", "千", "万", "十", "百", "千", "亿"};
|
||||
String s = String.valueOf(number);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < s.length(); ++i) {
|
||||
String index = String.valueOf(s.charAt(i));
|
||||
sb = sb.append(format[Integer.parseInt(index)]);
|
||||
}
|
||||
String sss = String.valueOf(sb);
|
||||
int i = 0;
|
||||
for (int j = sss.length(); j > 0; --j) {
|
||||
sb = ++i <= 8 ? sb.insert(j, units[i]) : sb.insert(j, units[i - 8]);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String getContentByHtmlUrl(String urlString) {
|
||||
StringBuilder input = new StringBuilder();
|
||||
try (InputStreamReader in = new InputStreamReader(new URL(urlString).openStream());){
|
||||
int ch;
|
||||
while ((ch = in.read()) != -1) {
|
||||
input.append((char)ch);
|
||||
}
|
||||
}
|
||||
catch (MalformedURLException e) {
|
||||
LOGGER.warn(e.getMessage());
|
||||
}
|
||||
catch (IOException e) {
|
||||
LOGGER.warn(e.getMessage());
|
||||
}
|
||||
return input.toString();
|
||||
}
|
||||
|
||||
public static String getBase64Info(String img) {
|
||||
String[] imgs;
|
||||
if (StringUtils.isNotBlank((CharSequence)img) && (imgs = img.split("base64,")) != null && imgs.length == 2) {
|
||||
img = imgs[1];
|
||||
}
|
||||
return img;
|
||||
}
|
||||
|
||||
public static String getRequestBody(HttpServletRequest request) throws IOException {
|
||||
String body = null;
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
BufferedReader bufferedReader = null;
|
||||
try (ServletInputStream inputStream = request.getInputStream();){
|
||||
if (inputStream != null) {
|
||||
bufferedReader = new BufferedReader(new InputStreamReader((InputStream)inputStream));
|
||||
char[] charBuffer = new char[128];
|
||||
int bytesRead = -1;
|
||||
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
|
||||
stringBuilder.append(charBuffer, 0, bytesRead);
|
||||
}
|
||||
} else {
|
||||
stringBuilder.append("");
|
||||
}
|
||||
}
|
||||
catch (IOException ex) {
|
||||
throw ex;
|
||||
}
|
||||
finally {
|
||||
if (null != bufferedReader) {
|
||||
bufferedReader.close();
|
||||
}
|
||||
}
|
||||
body = stringBuilder.toString();
|
||||
return body;
|
||||
}
|
||||
|
||||
public static String getSessionIdByRequest(HttpServletRequest request) {
|
||||
String sessionId = null;
|
||||
Cookie[] cookie = request.getCookies();
|
||||
for (int i = 0; i < cookie.length; ++i) {
|
||||
Cookie cook = cookie[i];
|
||||
if (!"JSESSIONID".equals(cook.getName())) continue;
|
||||
sessionId = cook.getValue().toString();
|
||||
}
|
||||
return sessionId;
|
||||
}
|
||||
|
||||
public static Map<String, Object> postRequest(String url, MultiValueMap<String, Object> param) {
|
||||
Map reslutMap = Maps.newLinkedHashMap();
|
||||
try {
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
|
||||
HttpEntity request = new HttpEntity(param, (MultiValueMap)headers);
|
||||
ResponseEntity response = restTemplate.postForEntity(url, (Object)request, Map.class, param);
|
||||
reslutMap = (Map)response.getBody();
|
||||
}
|
||||
catch (Exception e) {
|
||||
LOGGER.warn(e.getMessage());
|
||||
reslutMap.put("info", "error");
|
||||
}
|
||||
return reslutMap;
|
||||
}
|
||||
|
||||
public static boolean checkPwdComplexity(String password) {
|
||||
return password.matches(CAPITAL_LETTER_REG) && password.matches(NUMBER_REG) && password.matches(UPPER_CASE_REG) || password.matches(CAPITAL_LETTER_REG) && password.matches(NUMBER_REG) && password.matches(SPECIAL_CHAR_REG) || password.matches(CAPITAL_LETTER_REG) && password.matches(SPECIAL_CHAR_REG) && password.matches(UPPER_CASE_REG) || password.matches(SPECIAL_CHAR_REG) && password.matches(NUMBER_REG) && password.matches(UPPER_CASE_REG);
|
||||
}
|
||||
|
||||
public static String getSHA256(String str) {
|
||||
String encodeStr = "";
|
||||
try {
|
||||
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
|
||||
messageDigest.update(str.getBytes("UTF-8"));
|
||||
encodeStr = ToolUtil.byte2Hex(messageDigest.digest());
|
||||
}
|
||||
catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {
|
||||
LOGGER.warn(e.getMessage());
|
||||
}
|
||||
return encodeStr;
|
||||
}
|
||||
|
||||
private static String byte2Hex(byte[] bytes) {
|
||||
StringBuilder stringBuffer = new StringBuilder();
|
||||
String temp = null;
|
||||
for (byte i : bytes) {
|
||||
temp = Integer.toHexString(i & 0xFF);
|
||||
if (temp.length() == 1) {
|
||||
stringBuffer.append("0");
|
||||
}
|
||||
stringBuffer.append(temp);
|
||||
}
|
||||
return stringBuffer.toString();
|
||||
}
|
||||
|
||||
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
|
||||
ConcurrentHashMap.KeySetView seen = ConcurrentHashMap.newKeySet();
|
||||
return t -> seen.add(keyExtractor.apply(t));
|
||||
}
|
||||
public static final Logger LOGGER = LoggerFactory.getLogger(ToolUtil.class);
|
||||
public static final int HASH_INTERATIONS = 1024;
|
||||
private static final int SALT_SIZE = 8;
|
||||
private static final String EMAIL_REG = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
|
||||
private static final String CAPITAL_LETTER_REG = ".*[A-Z].*";
|
||||
private static final String UPPER_CASE_REG = ".*[a-z].*";
|
||||
private static final String SPECIAL_CHAR_REG = ".*((?=[\\x21-\\x7e]+)[^A-Za-z0-9]).*";
|
||||
private static final String NUMBER_REG = ".*[0-9].*";
|
||||
private static final String UNKNOWN = "unknown";
|
||||
public static String generateUUID() {
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
return uuid.replaceAll("-", "");
|
||||
}
|
||||
public static String exStackTrace(Exception ex) {
|
||||
StringWriter sw = new StringWriter();
|
||||
PrintWriter pw = new PrintWriter(sw);
|
||||
ex.printStackTrace(pw);
|
||||
return sw.toString();
|
||||
}
|
||||
public static boolean isEmail(String str) {
|
||||
if (StringUtils.isBlank(str)) {
|
||||
return false;
|
||||
}
|
||||
Pattern pattern = Pattern.compile("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$");
|
||||
Matcher isEmail = pattern.matcher(str);
|
||||
if (!isEmail.matches()) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
public static String entryptPassword(String paramStr) {
|
||||
if (StringUtils.isNotEmpty(paramStr)) {
|
||||
byte[] salt = Digests.generateSalt(8);
|
||||
byte[] hashPassword = Digests.sha1(paramStr.getBytes(), salt, 1024);
|
||||
String saltStr = Encodes.encodeHex(salt);
|
||||
String password = Encodes.encodeHex(hashPassword);
|
||||
return password + "," + saltStr;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public static String entryptPassword(String paramStr, String salt) {
|
||||
if (StringUtils.isNotEmpty(paramStr)) {
|
||||
byte[] saltStr = Encodes.decodeHex(salt);
|
||||
byte[] hashPassword = Digests.sha1(paramStr.getBytes(), saltStr, 1024);
|
||||
String password = Encodes.encodeHex(hashPassword);
|
||||
return password;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public static String readFileByLines(InputStream inputStream) throws UnsupportedEncodingException, FileNotFoundException {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
try(InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8");
|
||||
BufferedReader reader = new BufferedReader(isr)) {
|
||||
LOGGER.info("以行为单位读取文件内容,一次读一整行:");
|
||||
String tempString = null;
|
||||
int line = 1;
|
||||
while ((tempString = reader.readLine()) != null) {
|
||||
sb.append(tempString);
|
||||
line++;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOGGER.warn(e.getMessage());
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
public static String getClientIp(HttpServletRequest request) {
|
||||
String ip = request.getHeader("X-Real-IP");
|
||||
LOGGER.info("ipadd : {}", ip);
|
||||
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("X-Forwarded-For");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("Proxy-Client-IP");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getRemoteAddr();
|
||||
}
|
||||
LOGGER.info(" ip --> {}", ip);
|
||||
return ip;
|
||||
}
|
||||
public static String parseGBK(String sIn) {
|
||||
if (sIn == null || "".equals(sIn)) {
|
||||
return sIn;
|
||||
}
|
||||
try {
|
||||
return new String(sIn.getBytes("GBK"), StandardCharsets.ISO_8859_1);
|
||||
} catch (UnsupportedEncodingException usex) {
|
||||
return sIn;
|
||||
}
|
||||
}
|
||||
public static String randomNum(int range) {
|
||||
Double rangeD = Double.valueOf(Math.pow(10.0D, range));
|
||||
int result = (int)(((new SecureRandom()).nextDouble() * 9.0D + 1.0D) * rangeD.intValue());
|
||||
return String.valueOf(result);
|
||||
}
|
||||
public static Map<String, Object> convertBeanToMap(Object condition) {
|
||||
if (condition == null) {
|
||||
return null;
|
||||
}
|
||||
if (condition instanceof Map) {
|
||||
return (Map<String, Object>)condition;
|
||||
}
|
||||
Map<String, Object> objectAsMap = Maps.newHashMap();
|
||||
BeanInfo info = null;
|
||||
try {
|
||||
info = Introspector.getBeanInfo(condition.getClass());
|
||||
} catch (IntrospectionException e) {
|
||||
LOGGER.warn(e.getMessage());
|
||||
}
|
||||
if (info != null && info.getPropertyDescriptors() != null) {
|
||||
for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
|
||||
Method reader = pd.getReadMethod();
|
||||
if (reader != null && !"class".equals(pd.getName())) {
|
||||
try {
|
||||
objectAsMap.put(pd.getName(), reader.invoke(condition, new Object[0]));
|
||||
} catch (IllegalArgumentException|IllegalAccessException|java.lang.reflect.InvocationTargetException e) {
|
||||
LOGGER.warn(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return objectAsMap;
|
||||
}
|
||||
public static void getPassword(String password) {
|
||||
byte[] salt = Digests.generateSalt(8);
|
||||
LOGGER.info("salt:{}", Encodes.encodeHex(salt));
|
||||
byte[] hashPassword = Digests.sha1(password.getBytes(), salt, 1024);
|
||||
LOGGER.info("hashPassword:{}", Encodes.encodeHex(hashPassword));
|
||||
}
|
||||
public static String formatNumberToString(long number) {
|
||||
String[] format = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
|
||||
String[] units = { "", "十", "百", "千", "万", "十", "百", "千", "亿" };
|
||||
String s = String.valueOf(number);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
String index = String.valueOf(s.charAt(i));
|
||||
sb = sb.append(format[Integer.parseInt(index)]);
|
||||
}
|
||||
String sss = String.valueOf(sb);
|
||||
int k = 0;
|
||||
for (int j = sss.length(); j > 0; j--) {
|
||||
k++;
|
||||
if (k <= 8) {
|
||||
sb = sb.insert(j, units[k]);
|
||||
} else {
|
||||
sb = sb.insert(j, units[k - 8]);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
public static String getContentByHtmlUrl(String urlString) {
|
||||
StringBuilder input = new StringBuilder();
|
||||
try (InputStreamReader in = new InputStreamReader((new URL(urlString)).openStream())) {
|
||||
int ch;
|
||||
while ((ch = in.read()) != -1) {
|
||||
input.append((char)ch);
|
||||
}
|
||||
} catch (MalformedURLException e) {
|
||||
LOGGER.warn(e.getMessage());
|
||||
} catch (IOException e) {
|
||||
LOGGER.warn(e.getMessage());
|
||||
}
|
||||
return input.toString();
|
||||
}
|
||||
public static String getBase64Info(String img) {
|
||||
if (StringUtils.isNotBlank(img)) {
|
||||
String[] imgs = img.split("base64,");
|
||||
if (imgs != null && imgs.length == 2) {
|
||||
img = imgs[1];
|
||||
}
|
||||
}
|
||||
return img;
|
||||
}
|
||||
public static String getRequestBody(HttpServletRequest request) throws IOException {
|
||||
String body = null;
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
BufferedReader bufferedReader = null;
|
||||
try (ServletInputStream servletInputStream = request.getInputStream()) {
|
||||
if (servletInputStream != null) {
|
||||
bufferedReader = new BufferedReader(new InputStreamReader((InputStream)servletInputStream));
|
||||
char[] charBuffer = new char[128];
|
||||
int bytesRead = -1;
|
||||
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
|
||||
stringBuilder.append(charBuffer, 0, bytesRead);
|
||||
}
|
||||
} else {
|
||||
stringBuilder.append("");
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
throw ex;
|
||||
} finally {
|
||||
if (null != bufferedReader) {
|
||||
bufferedReader.close();
|
||||
}
|
||||
}
|
||||
body = stringBuilder.toString();
|
||||
return body;
|
||||
}
|
||||
public static String getSessionIdByRequest(HttpServletRequest request) {
|
||||
String sessionId = null;
|
||||
Cookie[] cookie = request.getCookies();
|
||||
for (int i = 0; i < cookie.length; i++) {
|
||||
Cookie cook = cookie[i];
|
||||
if ("JSESSIONID".equals(cook.getName())) {
|
||||
sessionId = cook.getValue().toString();
|
||||
}
|
||||
}
|
||||
return sessionId;
|
||||
}
|
||||
public static Map<String, Object> postRequest(String url, MultiValueMap<String, Object> param) {
|
||||
Map<String, Object> reslutMap = Maps.newLinkedHashMap();
|
||||
try {
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
|
||||
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity(param, (MultiValueMap)headers);
|
||||
ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class, (Map)param);
|
||||
reslutMap = (Map<String, Object>)response.getBody();
|
||||
} catch (Exception e) {
|
||||
LOGGER.warn(e.getMessage());
|
||||
reslutMap.put("info", "error");
|
||||
}
|
||||
return reslutMap;
|
||||
}
|
||||
public static boolean checkPwdComplexity(String password) {
|
||||
return ((password.matches(".*[A-Z].*") && password.matches(".*[0-9].*") && password
|
||||
.matches(".*[a-z].*")) || (password
|
||||
.matches(".*[A-Z].*") && password.matches(".*[0-9].*") && password
|
||||
.matches(".*((?=[\\x21-\\x7e]+)[^A-Za-z0-9]).*")) || (password
|
||||
.matches(".*[A-Z].*") && password.matches(".*((?=[\\x21-\\x7e]+)[^A-Za-z0-9]).*") && password
|
||||
.matches(".*[a-z].*")) || (password
|
||||
.matches(".*((?=[\\x21-\\x7e]+)[^A-Za-z0-9]).*") && password.matches(".*[0-9].*") && password
|
||||
.matches(".*[a-z].*")));
|
||||
}
|
||||
public static String getSHA256(String str) {
|
||||
String encodeStr = "";
|
||||
try {
|
||||
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
|
||||
messageDigest.update(str.getBytes("UTF-8"));
|
||||
encodeStr = byte2Hex(messageDigest.digest());
|
||||
} catch (NoSuchAlgorithmException|UnsupportedEncodingException e) {
|
||||
LOGGER.warn(e.getMessage());
|
||||
}
|
||||
return encodeStr;
|
||||
}
|
||||
private static String byte2Hex(byte[] bytes) {
|
||||
StringBuilder stringBuffer = new StringBuilder();
|
||||
String temp = null;
|
||||
for (byte i : bytes) {
|
||||
temp = Integer.toHexString(i & 0xFF);
|
||||
if (temp.length() == 1)
|
||||
{
|
||||
stringBuffer.append("0");
|
||||
}
|
||||
stringBuffer.append(temp);
|
||||
}
|
||||
return stringBuffer.toString();
|
||||
}
|
||||
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
|
||||
Set<Object> seen = ConcurrentHashMap.newKeySet();
|
||||
return t -> seen.add(keyExtractor.apply(t));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/common/ToolUtil.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+419
-441
@@ -1,5 +1,4 @@
|
||||
package cn.cloudwalk.service.organization.export;
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.batch.param.download.FilePartFinishPara;
|
||||
import cn.cloudwalk.client.organization.batch.param.download.FilePartInitResult;
|
||||
import cn.cloudwalk.client.organization.common.enums.FileStatusEnum;
|
||||
@@ -18,21 +17,14 @@ import cn.cloudwalk.client.organization.result.PersonProListResult;
|
||||
import cn.cloudwalk.client.organization.service.ICommonAppDownloadCenterService;
|
||||
import cn.cloudwalk.client.organization.service.ICommonAppFileManageService;
|
||||
import cn.cloudwalk.client.organization.service.ICommonStorageService;
|
||||
import cn.cloudwalk.client.organization.service.LabelService;
|
||||
import cn.cloudwalk.client.organization.service.OrganizationService;
|
||||
import cn.cloudwalk.client.organization.service.store.result.OrganizationResult;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkCallContext;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.intelligent.davinci.storage.bean.part.dto.PartInitResultDTO;
|
||||
import cn.cloudwalk.intelligent.davinci.storage.manager.FilePartManager;
|
||||
import cn.cloudwalk.intelligent.davinci.storage.manager.FileStorageManager;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import cn.cloudwalk.service.organization.common.CommonDownloadDataConfig;
|
||||
import cn.cloudwalk.service.organization.common.MultipartFileUtils;
|
||||
import cn.cloudwalk.service.organization.config.ChannelFileReader;
|
||||
import cn.cloudwalk.service.organization.export.CommonAppExportFileByLabelHandler;
|
||||
import cn.cloudwalk.service.organization.export.CommonAppExportFileByOrgHandler;
|
||||
import cn.cloudwalk.service.organization.export.CommonAppExportFileHandler;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
@@ -42,451 +34,437 @@ import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.Base64Utils;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@Service
|
||||
@EnableAsync
|
||||
public class CommonAppExportExecuteTask
|
||||
extends AbstractImagStoreService {
|
||||
private static final Logger log = LoggerFactory.getLogger(CommonAppExportExecuteTask.class);
|
||||
@Autowired
|
||||
private ICommonAppDownloadCenterService commonAppDownloadCenterService;
|
||||
@Autowired
|
||||
private CommonDownloadDataConfig commonDownloadDataConfig;
|
||||
@Autowired
|
||||
private ICommonStorageService commonAppStorageService;
|
||||
@Autowired
|
||||
private ImgStorePersonService imgStorePersonService;
|
||||
@Autowired
|
||||
private OrganizationService organizationService;
|
||||
@Autowired
|
||||
private LabelService labelService;
|
||||
@Autowired
|
||||
private ImgStorePersonPropertiesService imgStorePersonPropertiesService;
|
||||
@Autowired
|
||||
private ICommonAppFileManageService iCommonAppFileManageService;
|
||||
@Autowired
|
||||
private FilePartManager filePartManager;
|
||||
@Autowired
|
||||
private FileStorageManager fileStorageManager;
|
||||
@Value(value="${cloudwalk.common-app.download.shardingSize}")
|
||||
private Integer shardingSize;
|
||||
String fileName = "人员信息";
|
||||
String orgFileName = "机构信息";
|
||||
String labelFileName = "标签信息";
|
||||
|
||||
@Async
|
||||
public void execute(ExportRecordTaskParam task, CloudwalkCallContext cloudwalkCallContext) {
|
||||
this.logger.info("开始执行人员信息导出功能");
|
||||
QueryImgPersonParam queryImgPersonParam = new QueryImgPersonParam();
|
||||
BeanUtils.copyProperties((Object)task, (Object)queryImgPersonParam);
|
||||
try {
|
||||
CloudwalkResult<List<ImgStorePersonGetResult>> recordList = this.getPersonData(queryImgPersonParam, cloudwalkCallContext);
|
||||
if (CollectionUtils.isEmpty((Collection)((Collection)recordList.getData()))) {
|
||||
this.logger.info("查询导出记录为空, businessId = {}, task = {}", (Object)task.getBusinessId(), (Object)task);
|
||||
this.exportUpload(task.getBusinessId(), task.getFileId(), null);
|
||||
return;
|
||||
}
|
||||
this.logger.info("导出记录总数为{}", (Object)((List)recordList.getData()).size());
|
||||
HashMap<String, List<ImgStorePersonGetResult>> dataMap = new HashMap<String, List<ImgStorePersonGetResult>>();
|
||||
dataMap.put(this.fileName, (List<ImgStorePersonGetResult>)recordList.getData());
|
||||
PersonProListResult personProListResult = (PersonProListResult)this.imgStorePersonPropertiesService.getList(task.getBusinessId()).getData();
|
||||
List properties = personProListResult.getProperties();
|
||||
ImgPersonProGetResult result1 = new ImgPersonProGetResult();
|
||||
result1.setId("1");
|
||||
result1.setName("门禁设备(在线)");
|
||||
result1.setCode("onlineDevices");
|
||||
result1.setStatus(Integer.valueOf(0));
|
||||
result1.setType(Short.valueOf((short)1));
|
||||
result1.setOrderNum(Integer.valueOf(17));
|
||||
result1.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result2 = new ImgPersonProGetResult();
|
||||
result2.setId("2");
|
||||
result2.setName("门禁设备(离线)");
|
||||
result2.setCode("offlineDevices");
|
||||
result2.setStatus(Integer.valueOf(0));
|
||||
result2.setType(Short.valueOf((short)1));
|
||||
result2.setOrderNum(Integer.valueOf(18));
|
||||
result2.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result3 = new ImgPersonProGetResult();
|
||||
result3.setId("3");
|
||||
result3.setName("派梯楼层权限");
|
||||
result3.setCode("floorNames");
|
||||
result3.setStatus(Integer.valueOf(0));
|
||||
result3.setType(Short.valueOf((short)1));
|
||||
result3.setOrderNum(Integer.valueOf(19));
|
||||
result3.setHasDefault(Integer.valueOf(1));
|
||||
properties.add(result1);
|
||||
properties.add(result2);
|
||||
properties.add(result3);
|
||||
this.logger.info("导出的字段属性为:{}", JSONObject.toJSON((Object)properties));
|
||||
this.commonDownloadDataConfig.setExcelMaxRows(task.getExcelMaxRows());
|
||||
this.commonDownloadDataConfig.setHasContainImage(task.getHasContainImage());
|
||||
Path zipPath = new CommonAppExportFileHandler(task.getBusinessId(), this.fileName, task.getFileId(), dataMap, this.commonDownloadDataConfig, this.fileStorageManager, this.commonAppDownloadCenterService, personProListResult).process();
|
||||
int status = this.commonAppDownloadCenterService.queryDownloadStatus(task.getBusinessId(), task.getFileId());
|
||||
if (status > 1) {
|
||||
this.logger.info("下载中心已取消下载文件,fileId = {}", (Object)task.getFileId());
|
||||
this.exportUpload(task.getBusinessId(), task.getFileId(), null);
|
||||
return;
|
||||
}
|
||||
this.exportUpload(task.getBusinessId(), task.getFileId(), zipPath.toString());
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("导出人员任务失败:{}", (Object)e.getMessage());
|
||||
this.commonAppDownloadCenterService.finishDownload(task.getBusinessId(), task.getFileId(), null, null, FileStatusEnum.ERROR.getCode());
|
||||
throw new RuntimeException("执行导出人员记录任务异常");
|
||||
}
|
||||
}
|
||||
|
||||
@Async
|
||||
public void executeOrg(ExportOrgTaskParam task, CloudwalkCallContext context) {
|
||||
this.logger.info("开始执行机构信息导出功能");
|
||||
QueryOrganizationParam queryImgPersonParam = new QueryOrganizationParam();
|
||||
BeanUtils.copyProperties((Object)task, (Object)queryImgPersonParam);
|
||||
try {
|
||||
CloudwalkResult<List<OrganizationResult>> recordList = this.getOrgData(queryImgPersonParam, context);
|
||||
if (CollectionUtils.isEmpty((Collection)((Collection)recordList.getData()))) {
|
||||
this.logger.info("查询导出记录为空, businessId = {}, task = {}", (Object)task.getBusinessId(), (Object)task);
|
||||
this.exportUpload(task.getBusinessId(), task.getFileId(), null);
|
||||
return;
|
||||
}
|
||||
this.logger.info("导出记录总数为{}", (Object)((List)recordList.getData()).size());
|
||||
HashMap<String, List<OrganizationResult>> dataMap = new HashMap<String, List<OrganizationResult>>();
|
||||
dataMap.put(this.orgFileName, (List<OrganizationResult>)recordList.getData());
|
||||
PersonProListResult personProListResult = new PersonProListResult();
|
||||
ArrayList<ImgPersonProGetResult> properties = new ArrayList<ImgPersonProGetResult>();
|
||||
ImgPersonProGetResult result1 = new ImgPersonProGetResult();
|
||||
result1.setId("1");
|
||||
result1.setName("机构名称");
|
||||
result1.setCode("name");
|
||||
result1.setStatus(Integer.valueOf(0));
|
||||
result1.setType(Short.valueOf((short)1));
|
||||
result1.setOrderNum(Integer.valueOf(1));
|
||||
result1.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result2 = new ImgPersonProGetResult();
|
||||
result2.setId("2");
|
||||
result2.setName("机构id");
|
||||
result2.setCode("id");
|
||||
result2.setStatus(Integer.valueOf(0));
|
||||
result2.setType(Short.valueOf((short)1));
|
||||
result2.setOrderNum(Integer.valueOf(2));
|
||||
result2.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result3 = new ImgPersonProGetResult();
|
||||
result3.setId("3");
|
||||
result3.setName("机构类型");
|
||||
result3.setCode("type");
|
||||
result3.setStatus(Integer.valueOf(0));
|
||||
result3.setType(Short.valueOf((short)1));
|
||||
result3.setOrderNum(Integer.valueOf(3));
|
||||
result3.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result4 = new ImgPersonProGetResult();
|
||||
result4.setId("4");
|
||||
result4.setName("人员数量");
|
||||
result4.setCode("personCount");
|
||||
result4.setStatus(Integer.valueOf(0));
|
||||
result4.setType(Short.valueOf((short)1));
|
||||
result4.setOrderNum(Integer.valueOf(4));
|
||||
result4.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result5 = new ImgPersonProGetResult();
|
||||
result5.setId("5");
|
||||
result5.setName("状态:0-已启用");
|
||||
result5.setCode("isDel");
|
||||
result5.setStatus(Integer.valueOf(0));
|
||||
result5.setType(Short.valueOf((short)1));
|
||||
result5.setOrderNum(Integer.valueOf(5));
|
||||
result5.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result6 = new ImgPersonProGetResult();
|
||||
result6.setId("6");
|
||||
result6.setName("门禁设备(在线)");
|
||||
result6.setCode("onlineDevices");
|
||||
result6.setStatus(Integer.valueOf(0));
|
||||
result6.setType(Short.valueOf((short)1));
|
||||
result6.setOrderNum(Integer.valueOf(6));
|
||||
result6.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result7 = new ImgPersonProGetResult();
|
||||
result7.setId("7");
|
||||
result7.setName("门禁设备(离线)");
|
||||
result7.setCode("offlineDevices");
|
||||
result7.setStatus(Integer.valueOf(0));
|
||||
result7.setType(Short.valueOf((short)1));
|
||||
result7.setOrderNum(Integer.valueOf(7));
|
||||
result7.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result8 = new ImgPersonProGetResult();
|
||||
result8.setId("8");
|
||||
result8.setName("派梯楼层权限");
|
||||
result8.setCode("floorNames");
|
||||
result8.setStatus(Integer.valueOf(0));
|
||||
result8.setType(Short.valueOf((short)1));
|
||||
result8.setOrderNum(Integer.valueOf(8));
|
||||
result8.setHasDefault(Integer.valueOf(1));
|
||||
properties.add(result1);
|
||||
properties.add(result2);
|
||||
properties.add(result3);
|
||||
properties.add(result4);
|
||||
properties.add(result5);
|
||||
properties.add(result6);
|
||||
properties.add(result7);
|
||||
properties.add(result8);
|
||||
personProListResult.setProperties(properties);
|
||||
this.logger.info("导出的字段属性为:{}", JSONObject.toJSON(properties));
|
||||
this.commonDownloadDataConfig.setExcelMaxRows(task.getExcelMaxRows());
|
||||
Path zipPath = new CommonAppExportFileByOrgHandler(task.getBusinessId(), this.fileName, task.getFileId(), dataMap, this.commonDownloadDataConfig, this.fileStorageManager, this.commonAppDownloadCenterService, personProListResult).process();
|
||||
int status = this.commonAppDownloadCenterService.queryDownloadStatus(task.getBusinessId(), task.getFileId());
|
||||
if (status > 1) {
|
||||
this.logger.info("下载中心已取消下载文件,fileId = {}", (Object)task.getFileId());
|
||||
this.exportUpload(task.getBusinessId(), task.getFileId(), null);
|
||||
return;
|
||||
}
|
||||
this.exportUpload(task.getBusinessId(), task.getFileId(), zipPath.toString());
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("导出机构任务失败:{}", e);
|
||||
this.commonAppDownloadCenterService.finishDownload(task.getBusinessId(), task.getFileId(), null, null, FileStatusEnum.ERROR.getCode());
|
||||
throw new RuntimeException("执行导出机构信息任务异常");
|
||||
}
|
||||
}
|
||||
|
||||
@Async
|
||||
public void executeLabel(ExportLabelTaskParam task, CloudwalkCallContext context) {
|
||||
this.logger.info("开始执行标签信息导出功能");
|
||||
PageLabelParam pageLabelParam = new PageLabelParam();
|
||||
BeanUtils.copyProperties((Object)task, (Object)pageLabelParam);
|
||||
try {
|
||||
CloudwalkResult<List<PageLabelResult>> recordList = this.getLabelData(pageLabelParam, context);
|
||||
if (CollectionUtils.isEmpty((Collection)((Collection)recordList.getData()))) {
|
||||
this.logger.info("查询导出记录为空, businessId = {}, task = {}", (Object)task.getBusinessId(), (Object)task);
|
||||
this.exportUpload(task.getBusinessId(), task.getFileId(), null);
|
||||
return;
|
||||
}
|
||||
this.logger.info("导出记录总数为{}", (Object)((List)recordList.getData()).size());
|
||||
HashMap<String, List<PageLabelResult>> dataMap = new HashMap<String, List<PageLabelResult>>();
|
||||
dataMap.put(this.labelFileName, (List<PageLabelResult>)recordList.getData());
|
||||
PersonProListResult personProListResult = new PersonProListResult();
|
||||
ArrayList<ImgPersonProGetResult> properties = new ArrayList<ImgPersonProGetResult>();
|
||||
ImgPersonProGetResult result1 = new ImgPersonProGetResult();
|
||||
result1.setId("1");
|
||||
result1.setName("标签名称");
|
||||
result1.setCode("name");
|
||||
result1.setStatus(Integer.valueOf(0));
|
||||
result1.setType(Short.valueOf((short)1));
|
||||
result1.setOrderNum(Integer.valueOf(1));
|
||||
result1.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result2 = new ImgPersonProGetResult();
|
||||
result2.setId("2");
|
||||
result2.setName("标签id");
|
||||
result2.setCode("id");
|
||||
result2.setStatus(Integer.valueOf(0));
|
||||
result2.setType(Short.valueOf((short)1));
|
||||
result2.setOrderNum(Integer.valueOf(2));
|
||||
result2.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result3 = new ImgPersonProGetResult();
|
||||
result3.setId("3");
|
||||
result3.setName("标签编号");
|
||||
result3.setCode("code");
|
||||
result3.setStatus(Integer.valueOf(0));
|
||||
result3.setType(Short.valueOf((short)1));
|
||||
result3.setOrderNum(Integer.valueOf(3));
|
||||
result3.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result4 = new ImgPersonProGetResult();
|
||||
result4.setId("4");
|
||||
result4.setName("人员数量");
|
||||
result4.setCode("personCount");
|
||||
result4.setStatus(Integer.valueOf(0));
|
||||
result4.setType(Short.valueOf((short)1));
|
||||
result4.setOrderNum(Integer.valueOf(4));
|
||||
result4.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result5 = new ImgPersonProGetResult();
|
||||
result5.setId("5");
|
||||
result5.setName("标签类型:0-手动创建,1-应用初始,2-应用创建");
|
||||
result5.setCode("addType");
|
||||
result5.setStatus(Integer.valueOf(0));
|
||||
result5.setType(Short.valueOf((short)1));
|
||||
result5.setOrderNum(Integer.valueOf(5));
|
||||
result5.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result6 = new ImgPersonProGetResult();
|
||||
result6.setId("6");
|
||||
result6.setName("门禁设备(在线)");
|
||||
result6.setCode("onlineDevices");
|
||||
result6.setStatus(Integer.valueOf(0));
|
||||
result6.setType(Short.valueOf((short)1));
|
||||
result6.setOrderNum(Integer.valueOf(6));
|
||||
result6.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result7 = new ImgPersonProGetResult();
|
||||
result7.setId("7");
|
||||
result7.setName("门禁设备(离线)");
|
||||
result7.setCode("offlineDevices");
|
||||
result7.setStatus(Integer.valueOf(0));
|
||||
result7.setType(Short.valueOf((short)1));
|
||||
result7.setOrderNum(Integer.valueOf(7));
|
||||
result7.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result8 = new ImgPersonProGetResult();
|
||||
result8.setId("8");
|
||||
result8.setName("派梯楼层权限");
|
||||
result8.setCode("floorNames");
|
||||
result8.setStatus(Integer.valueOf(0));
|
||||
result8.setType(Short.valueOf((short)1));
|
||||
result8.setOrderNum(Integer.valueOf(8));
|
||||
result8.setHasDefault(Integer.valueOf(1));
|
||||
properties.add(result1);
|
||||
properties.add(result2);
|
||||
properties.add(result3);
|
||||
properties.add(result4);
|
||||
properties.add(result5);
|
||||
properties.add(result6);
|
||||
properties.add(result7);
|
||||
properties.add(result8);
|
||||
personProListResult.setProperties(properties);
|
||||
this.logger.info("导出的字段属性为:{}", JSONObject.toJSON(properties));
|
||||
this.commonDownloadDataConfig.setExcelMaxRows(task.getExcelMaxRows());
|
||||
Path zipPath = new CommonAppExportFileByLabelHandler(task.getBusinessId(), this.fileName, task.getFileId(), dataMap, this.commonDownloadDataConfig, this.fileStorageManager, this.commonAppDownloadCenterService, personProListResult).process();
|
||||
int status = this.commonAppDownloadCenterService.queryDownloadStatus(task.getBusinessId(), task.getFileId());
|
||||
if (status > 1) {
|
||||
this.logger.info("下载中心已取消下载文件,fileId = {}", (Object)task.getFileId());
|
||||
this.exportUpload(task.getBusinessId(), task.getFileId(), null);
|
||||
return;
|
||||
}
|
||||
this.exportUpload(task.getBusinessId(), task.getFileId(), zipPath.toString());
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("导出标签任务失败:{}", e);
|
||||
this.commonAppDownloadCenterService.finishDownload(task.getBusinessId(), task.getFileId(), null, null, FileStatusEnum.ERROR.getCode());
|
||||
throw new RuntimeException("执行导出标签信息任务异常");
|
||||
}
|
||||
}
|
||||
|
||||
private CloudwalkResult<List<ImgStorePersonGetResult>> getPersonData(QueryImgPersonParam queryImgPersonParam, CloudwalkCallContext cloudwalkCallContext) {
|
||||
CloudwalkResult recordList = new CloudwalkResult();
|
||||
try {
|
||||
recordList = this.imgStorePersonService.listByPage(queryImgPersonParam, cloudwalkCallContext);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("查询记录数据失败");
|
||||
}
|
||||
return recordList;
|
||||
}
|
||||
|
||||
private CloudwalkResult<List<OrganizationResult>> getOrgData(QueryOrganizationParam param, CloudwalkCallContext context) {
|
||||
CloudwalkResult recordList = new CloudwalkResult();
|
||||
try {
|
||||
recordList = this.organizationService.listByPage(param, context);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("查询机构记录数据失败");
|
||||
}
|
||||
return recordList;
|
||||
}
|
||||
|
||||
private CloudwalkResult<List<PageLabelResult>> getLabelData(PageLabelParam param, CloudwalkCallContext cloudwalkCallContext) {
|
||||
CloudwalkResult recordList = new CloudwalkResult();
|
||||
try {
|
||||
recordList = this.labelService.listByPage(param, cloudwalkCallContext);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("查询标签记录数据失败");
|
||||
}
|
||||
return recordList;
|
||||
}
|
||||
|
||||
private void exportUpload(String businessId, String fileId, String zipPathStr) throws IOException {
|
||||
try {
|
||||
if (StringUtils.isNotBlank((CharSequence)zipPathStr)) {
|
||||
this.uploadFile(businessId, fileId, zipPathStr);
|
||||
} else {
|
||||
byte[] data = Base64Utils.decodeFromString((String)"UEsDBBQACAgIAAuPmlAAAAAAAAAAAAAAAAAGAAAAZW1wdHkvAwBQSwcIAAAAAAIAAAAAAAAAUEsBAhQAFAAICAgAC4+aUAAAAAACAAAAAAAAAAYAAAAAAAAAAAAAAAAAAAAAAGVtcHR5L1BLBQYAAAAAAQABADQAAAA2AAAAAAA=");
|
||||
this.uploadFile(businessId, fileId, data, data.length);
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("将导出文件生成的zip上传到文件管理中心发生异常:{}", (Object)e.getMessage());
|
||||
throw new RuntimeException("将导出文件生成的zip上传到文件管理中心发生异常");
|
||||
}
|
||||
finally {
|
||||
this.logger.debug("删除压缩包:{}", (Object)zipPathStr);
|
||||
File file = new File(zipPathStr);
|
||||
if (file.exists()) {
|
||||
Files.delete(file.toPath());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void uploadFile(String businessId, String fileId, byte[] data, long fileSize) {
|
||||
String uuidCode = UUID.randomUUID().toString().replaceAll("-", "");
|
||||
String name = new StringBuffer(uuidCode).append(this.commonDownloadDataConfig.getCompressionType()).toString();
|
||||
String filePath = this.commonAppStorageService.saveFileBySharding(name, data);
|
||||
this.logger.info("存储文件名:fileId = {}, filePath = {}", (Object)fileId, (Object)filePath);
|
||||
int status = this.commonAppDownloadCenterService.queryDownloadStatus(businessId, fileId);
|
||||
if (status == FileStatusEnum.PRODUCING.getCode() || status == FileStatusEnum.ERROR.getCode()) {
|
||||
this.commonAppDownloadCenterService.finishDownload(businessId, fileId, filePath, Long.valueOf(fileSize), FileStatusEnum.FINISH.getCode());
|
||||
} else {
|
||||
this.commonAppStorageService.deleteFile(filePath);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* WARNING - Removed try catching itself - possible behaviour change.
|
||||
*/
|
||||
private void uploadFile(String businessId, String fileId, String zipPathStr) throws IOException {
|
||||
try (ChannelFileReader reader = new ChannelFileReader(zipPathStr, this.shardingSize);){
|
||||
String uuidCode = UUID.randomUUID().toString().replaceAll("-", "");
|
||||
String name = new StringBuffer(uuidCode).append(this.commonDownloadDataConfig.getCompressionType()).toString();
|
||||
FilePartInitResult resp = this.iCommonAppFileManageService.filePartInit(name);
|
||||
if (resp == null) {
|
||||
this.logger.info("分片上传文件初始化返回值为空");
|
||||
return;
|
||||
}
|
||||
AtomicInteger i = new AtomicInteger(1);
|
||||
long fileSize = 0L;
|
||||
while (reader.read() != -1) {
|
||||
this.logger.info("分片上传第{}次", (Object)i.get());
|
||||
fileSize += (long)reader.getArray().length;
|
||||
this.uploadFileBySharding(reader.getArray(), resp.getFilePath(), resp.getUploadId(), this.fileName, String.valueOf(i.getAndAdd(1)));
|
||||
}
|
||||
String filePath = this.filePartFinish(fileSize, resp);
|
||||
if (filePath == null) {
|
||||
this.logger.info("分片上传文件完成接口返回值为空");
|
||||
return;
|
||||
}
|
||||
this.logger.info("分片上传文件完成接口返回值 filePath = {}", (Object)filePath);
|
||||
this.logger.info("存储文件名:fileId = {}, filePath = {}", (Object)fileId, (Object)filePath);
|
||||
int status = this.commonAppDownloadCenterService.queryDownloadStatus(businessId, fileId);
|
||||
if (status == FileStatusEnum.PRODUCING.getCode() || status == FileStatusEnum.ERROR.getCode()) {
|
||||
this.commonAppDownloadCenterService.finishDownload(businessId, fileId, filePath, Long.valueOf(fileSize), FileStatusEnum.FINISH.getCode());
|
||||
} else {
|
||||
this.commonAppStorageService.deleteFile(filePath);
|
||||
}
|
||||
this.logger.info("完成上传任务 fileId = {}", (Object)fileId);
|
||||
}
|
||||
}
|
||||
|
||||
private String filePartFinish(long fileSize, FilePartInitResult resp) {
|
||||
FilePartFinishPara para = new FilePartFinishPara();
|
||||
BeanUtils.copyProperties((Object)resp, (Object)para);
|
||||
para.setFileSize(Long.valueOf(fileSize));
|
||||
para.setReturnType(Integer.valueOf(0));
|
||||
return this.iCommonAppFileManageService.filePartFinish(para);
|
||||
}
|
||||
|
||||
private void uploadFileBySharding(byte[] bytes, String filePath, String uploadId, String fileName, String partNumber) {
|
||||
MultipartFile mfile = MultipartFileUtils.getMultipartFile(fileName, bytes);
|
||||
try {
|
||||
PartInitResultDTO partInitResultDTO = this.filePartManager.append(filePath, Integer.valueOf(partNumber), uploadId, mfile);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("分片更新文件错误{}:{}", (Object)e.getClass().getName(), (Object)e.getMessage());
|
||||
}
|
||||
}
|
||||
public class CommonAppExportExecuteTask extends AbstractImagStoreService {
|
||||
private static final Logger log = LoggerFactory.getLogger(CommonAppExportExecuteTask.class);
|
||||
@Autowired
|
||||
private ICommonAppDownloadCenterService commonAppDownloadCenterService;
|
||||
@Autowired
|
||||
private CommonDownloadDataConfig commonDownloadDataConfig;
|
||||
@Autowired
|
||||
private ICommonStorageService commonAppStorageService;
|
||||
@Autowired
|
||||
private ImgStorePersonService imgStorePersonService;
|
||||
@Autowired
|
||||
private OrganizationService organizationService;
|
||||
@Autowired
|
||||
private LabelService labelService;
|
||||
@Autowired
|
||||
private ImgStorePersonPropertiesService imgStorePersonPropertiesService;
|
||||
@Autowired
|
||||
private ICommonAppFileManageService iCommonAppFileManageService;
|
||||
@Autowired
|
||||
private FilePartManager filePartManager;
|
||||
@Autowired
|
||||
private FileStorageManager fileStorageManager;
|
||||
@Value("${cloudwalk.common-app.download.shardingSize}")
|
||||
private Integer shardingSize;
|
||||
String fileName = "人员信息";
|
||||
String orgFileName = "机构信息";
|
||||
String labelFileName = "标签信息";
|
||||
@Async
|
||||
public void execute(ExportRecordTaskParam task, CloudwalkCallContext cloudwalkCallContext) {
|
||||
this.logger.info("开始执行人员信息导出功能");
|
||||
QueryImgPersonParam queryImgPersonParam = new QueryImgPersonParam();
|
||||
BeanUtils.copyProperties(task, queryImgPersonParam);
|
||||
try {
|
||||
CloudwalkResult<List<ImgStorePersonGetResult>> recordList = getPersonData(queryImgPersonParam, cloudwalkCallContext);
|
||||
if (CollectionUtils.isEmpty((Collection)recordList.getData())) {
|
||||
this.logger.info("查询导出记录为空, businessId = {}, task = {}", task.getBusinessId(), task);
|
||||
exportUpload(task.getBusinessId(), task.getFileId(), null);
|
||||
return;
|
||||
}
|
||||
this.logger.info("导出记录总数为{}", Integer.valueOf(((List)recordList.getData()).size()));
|
||||
Map<String, List<ImgStorePersonGetResult>> dataMap = new HashMap<>();
|
||||
dataMap.put(this.fileName, recordList.getData());
|
||||
PersonProListResult personProListResult = (PersonProListResult)this.imgStorePersonPropertiesService.getList(task.getBusinessId()).getData();
|
||||
List<ImgPersonProGetResult> properties = personProListResult.getProperties();
|
||||
ImgPersonProGetResult result1 = new ImgPersonProGetResult();
|
||||
result1.setId("1");
|
||||
result1.setName("门禁设备(在线)");
|
||||
result1.setCode("onlineDevices");
|
||||
result1.setStatus(Integer.valueOf(0));
|
||||
result1.setType(Short.valueOf((short)1));
|
||||
result1.setOrderNum(Integer.valueOf(17));
|
||||
result1.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result2 = new ImgPersonProGetResult();
|
||||
result2.setId("2");
|
||||
result2.setName("门禁设备(离线)");
|
||||
result2.setCode("offlineDevices");
|
||||
result2.setStatus(Integer.valueOf(0));
|
||||
result2.setType(Short.valueOf((short)1));
|
||||
result2.setOrderNum(Integer.valueOf(18));
|
||||
result2.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result3 = new ImgPersonProGetResult();
|
||||
result3.setId("3");
|
||||
result3.setName("派梯楼层权限");
|
||||
result3.setCode("floorNames");
|
||||
result3.setStatus(Integer.valueOf(0));
|
||||
result3.setType(Short.valueOf((short)1));
|
||||
result3.setOrderNum(Integer.valueOf(19));
|
||||
result3.setHasDefault(Integer.valueOf(1));
|
||||
properties.add(result1);
|
||||
properties.add(result2);
|
||||
properties.add(result3);
|
||||
this.logger.info("导出的字段属性为:{}", JSONObject.toJSON(properties));
|
||||
this.commonDownloadDataConfig.setExcelMaxRows(task.getExcelMaxRows().intValue());
|
||||
this.commonDownloadDataConfig.setHasContainImage(task.getHasContainImage());
|
||||
Path zipPath = (new CommonAppExportFileHandler(task.getBusinessId(), this.fileName, task.getFileId(), dataMap, this.commonDownloadDataConfig, this.fileStorageManager, this.commonAppDownloadCenterService, personProListResult)).process();
|
||||
int status = this.commonAppDownloadCenterService.queryDownloadStatus(task.getBusinessId(), task.getFileId());
|
||||
if (status > 1) {
|
||||
this.logger.info("下载中心已取消下载文件,fileId = {}", task.getFileId());
|
||||
exportUpload(task.getBusinessId(), task.getFileId(), null);
|
||||
return;
|
||||
}
|
||||
exportUpload(task.getBusinessId(), task.getFileId(), zipPath.toString());
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("导出人员任务失败:{}", e.getMessage());
|
||||
this.commonAppDownloadCenterService.finishDownload(task.getBusinessId(), task.getFileId(), null, null, FileStatusEnum.ERROR.getCode());
|
||||
throw new RuntimeException("执行导出人员记录任务异常");
|
||||
}
|
||||
}
|
||||
@Async
|
||||
public void executeOrg(ExportOrgTaskParam task, CloudwalkCallContext context) {
|
||||
this.logger.info("开始执行机构信息导出功能");
|
||||
QueryOrganizationParam queryImgPersonParam = new QueryOrganizationParam();
|
||||
BeanUtils.copyProperties(task, queryImgPersonParam);
|
||||
try {
|
||||
CloudwalkResult<List<OrganizationResult>> recordList = getOrgData(queryImgPersonParam, context);
|
||||
if (CollectionUtils.isEmpty((Collection)recordList.getData())) {
|
||||
this.logger.info("查询导出记录为空, businessId = {}, task = {}", task.getBusinessId(), task);
|
||||
exportUpload(task.getBusinessId(), task.getFileId(), null);
|
||||
return;
|
||||
}
|
||||
this.logger.info("导出记录总数为{}", Integer.valueOf(((List)recordList.getData()).size()));
|
||||
Map<String, List<OrganizationResult>> dataMap = new HashMap<>();
|
||||
dataMap.put(this.orgFileName, recordList.getData());
|
||||
PersonProListResult personProListResult = new PersonProListResult();
|
||||
List<ImgPersonProGetResult> properties = new ArrayList<>();
|
||||
ImgPersonProGetResult result1 = new ImgPersonProGetResult();
|
||||
result1.setId("1");
|
||||
result1.setName("机构名称");
|
||||
result1.setCode("name");
|
||||
result1.setStatus(Integer.valueOf(0));
|
||||
result1.setType(Short.valueOf((short)1));
|
||||
result1.setOrderNum(Integer.valueOf(1));
|
||||
result1.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result2 = new ImgPersonProGetResult();
|
||||
result2.setId("2");
|
||||
result2.setName("机构id");
|
||||
result2.setCode("id");
|
||||
result2.setStatus(Integer.valueOf(0));
|
||||
result2.setType(Short.valueOf((short)1));
|
||||
result2.setOrderNum(Integer.valueOf(2));
|
||||
result2.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result3 = new ImgPersonProGetResult();
|
||||
result3.setId("3");
|
||||
result3.setName("机构类型");
|
||||
result3.setCode("type");
|
||||
result3.setStatus(Integer.valueOf(0));
|
||||
result3.setType(Short.valueOf((short)1));
|
||||
result3.setOrderNum(Integer.valueOf(3));
|
||||
result3.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result4 = new ImgPersonProGetResult();
|
||||
result4.setId("4");
|
||||
result4.setName("人员数量");
|
||||
result4.setCode("personCount");
|
||||
result4.setStatus(Integer.valueOf(0));
|
||||
result4.setType(Short.valueOf((short)1));
|
||||
result4.setOrderNum(Integer.valueOf(4));
|
||||
result4.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result5 = new ImgPersonProGetResult();
|
||||
result5.setId("5");
|
||||
result5.setName("状态:0-已启用");
|
||||
result5.setCode("isDel");
|
||||
result5.setStatus(Integer.valueOf(0));
|
||||
result5.setType(Short.valueOf((short)1));
|
||||
result5.setOrderNum(Integer.valueOf(5));
|
||||
result5.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result6 = new ImgPersonProGetResult();
|
||||
result6.setId("6");
|
||||
result6.setName("门禁设备(在线)");
|
||||
result6.setCode("onlineDevices");
|
||||
result6.setStatus(Integer.valueOf(0));
|
||||
result6.setType(Short.valueOf((short)1));
|
||||
result6.setOrderNum(Integer.valueOf(6));
|
||||
result6.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result7 = new ImgPersonProGetResult();
|
||||
result7.setId("7");
|
||||
result7.setName("门禁设备(离线)");
|
||||
result7.setCode("offlineDevices");
|
||||
result7.setStatus(Integer.valueOf(0));
|
||||
result7.setType(Short.valueOf((short)1));
|
||||
result7.setOrderNum(Integer.valueOf(7));
|
||||
result7.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result8 = new ImgPersonProGetResult();
|
||||
result8.setId("8");
|
||||
result8.setName("派梯楼层权限");
|
||||
result8.setCode("floorNames");
|
||||
result8.setStatus(Integer.valueOf(0));
|
||||
result8.setType(Short.valueOf((short)1));
|
||||
result8.setOrderNum(Integer.valueOf(8));
|
||||
result8.setHasDefault(Integer.valueOf(1));
|
||||
properties.add(result1);
|
||||
properties.add(result2);
|
||||
properties.add(result3);
|
||||
properties.add(result4);
|
||||
properties.add(result5);
|
||||
properties.add(result6);
|
||||
properties.add(result7);
|
||||
properties.add(result8);
|
||||
personProListResult.setProperties(properties);
|
||||
this.logger.info("导出的字段属性为:{}", JSONObject.toJSON(properties));
|
||||
this.commonDownloadDataConfig.setExcelMaxRows(task.getExcelMaxRows().intValue());
|
||||
Path zipPath = (new CommonAppExportFileByOrgHandler(task.getBusinessId(), this.fileName, task.getFileId(), dataMap, this.commonDownloadDataConfig, this.fileStorageManager, this.commonAppDownloadCenterService, personProListResult)).process();
|
||||
int status = this.commonAppDownloadCenterService.queryDownloadStatus(task.getBusinessId(), task.getFileId());
|
||||
if (status > 1) {
|
||||
this.logger.info("下载中心已取消下载文件,fileId = {}", task.getFileId());
|
||||
exportUpload(task.getBusinessId(), task.getFileId(), null);
|
||||
return;
|
||||
}
|
||||
exportUpload(task.getBusinessId(), task.getFileId(), zipPath.toString());
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("导出机构任务失败:{}", e);
|
||||
this.commonAppDownloadCenterService.finishDownload(task.getBusinessId(), task.getFileId(), null, null, FileStatusEnum.ERROR.getCode());
|
||||
throw new RuntimeException("执行导出机构信息任务异常");
|
||||
}
|
||||
}
|
||||
@Async
|
||||
public void executeLabel(ExportLabelTaskParam task, CloudwalkCallContext context) {
|
||||
this.logger.info("开始执行标签信息导出功能");
|
||||
PageLabelParam pageLabelParam = new PageLabelParam();
|
||||
BeanUtils.copyProperties(task, pageLabelParam);
|
||||
try {
|
||||
CloudwalkResult<List<PageLabelResult>> recordList = getLabelData(pageLabelParam, context);
|
||||
if (CollectionUtils.isEmpty((Collection)recordList.getData())) {
|
||||
this.logger.info("查询导出记录为空, businessId = {}, task = {}", task.getBusinessId(), task);
|
||||
exportUpload(task.getBusinessId(), task.getFileId(), null);
|
||||
return;
|
||||
}
|
||||
this.logger.info("导出记录总数为{}", Integer.valueOf(((List)recordList.getData()).size()));
|
||||
Map<String, List<PageLabelResult>> dataMap = new HashMap<>();
|
||||
dataMap.put(this.labelFileName, recordList.getData());
|
||||
PersonProListResult personProListResult = new PersonProListResult();
|
||||
List<ImgPersonProGetResult> properties = new ArrayList<>();
|
||||
ImgPersonProGetResult result1 = new ImgPersonProGetResult();
|
||||
result1.setId("1");
|
||||
result1.setName("标签名称");
|
||||
result1.setCode("name");
|
||||
result1.setStatus(Integer.valueOf(0));
|
||||
result1.setType(Short.valueOf((short)1));
|
||||
result1.setOrderNum(Integer.valueOf(1));
|
||||
result1.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result2 = new ImgPersonProGetResult();
|
||||
result2.setId("2");
|
||||
result2.setName("标签id");
|
||||
result2.setCode("id");
|
||||
result2.setStatus(Integer.valueOf(0));
|
||||
result2.setType(Short.valueOf((short)1));
|
||||
result2.setOrderNum(Integer.valueOf(2));
|
||||
result2.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result3 = new ImgPersonProGetResult();
|
||||
result3.setId("3");
|
||||
result3.setName("标签编号");
|
||||
result3.setCode("code");
|
||||
result3.setStatus(Integer.valueOf(0));
|
||||
result3.setType(Short.valueOf((short)1));
|
||||
result3.setOrderNum(Integer.valueOf(3));
|
||||
result3.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result4 = new ImgPersonProGetResult();
|
||||
result4.setId("4");
|
||||
result4.setName("人员数量");
|
||||
result4.setCode("personCount");
|
||||
result4.setStatus(Integer.valueOf(0));
|
||||
result4.setType(Short.valueOf((short)1));
|
||||
result4.setOrderNum(Integer.valueOf(4));
|
||||
result4.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result5 = new ImgPersonProGetResult();
|
||||
result5.setId("5");
|
||||
result5.setName("标签类型:0-手动创建,1-应用初始,2-应用创建");
|
||||
result5.setCode("addType");
|
||||
result5.setStatus(Integer.valueOf(0));
|
||||
result5.setType(Short.valueOf((short)1));
|
||||
result5.setOrderNum(Integer.valueOf(5));
|
||||
result5.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result6 = new ImgPersonProGetResult();
|
||||
result6.setId("6");
|
||||
result6.setName("门禁设备(在线)");
|
||||
result6.setCode("onlineDevices");
|
||||
result6.setStatus(Integer.valueOf(0));
|
||||
result6.setType(Short.valueOf((short)1));
|
||||
result6.setOrderNum(Integer.valueOf(6));
|
||||
result6.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result7 = new ImgPersonProGetResult();
|
||||
result7.setId("7");
|
||||
result7.setName("门禁设备(离线)");
|
||||
result7.setCode("offlineDevices");
|
||||
result7.setStatus(Integer.valueOf(0));
|
||||
result7.setType(Short.valueOf((short)1));
|
||||
result7.setOrderNum(Integer.valueOf(7));
|
||||
result7.setHasDefault(Integer.valueOf(1));
|
||||
ImgPersonProGetResult result8 = new ImgPersonProGetResult();
|
||||
result8.setId("8");
|
||||
result8.setName("派梯楼层权限");
|
||||
result8.setCode("floorNames");
|
||||
result8.setStatus(Integer.valueOf(0));
|
||||
result8.setType(Short.valueOf((short)1));
|
||||
result8.setOrderNum(Integer.valueOf(8));
|
||||
result8.setHasDefault(Integer.valueOf(1));
|
||||
properties.add(result1);
|
||||
properties.add(result2);
|
||||
properties.add(result3);
|
||||
properties.add(result4);
|
||||
properties.add(result5);
|
||||
properties.add(result6);
|
||||
properties.add(result7);
|
||||
properties.add(result8);
|
||||
personProListResult.setProperties(properties);
|
||||
this.logger.info("导出的字段属性为:{}", JSONObject.toJSON(properties));
|
||||
this.commonDownloadDataConfig.setExcelMaxRows(task.getExcelMaxRows().intValue());
|
||||
Path zipPath = (new CommonAppExportFileByLabelHandler(task.getBusinessId(), this.fileName, task.getFileId(), dataMap, this.commonDownloadDataConfig, this.fileStorageManager, this.commonAppDownloadCenterService, personProListResult)).process();
|
||||
int status = this.commonAppDownloadCenterService.queryDownloadStatus(task.getBusinessId(), task.getFileId());
|
||||
if (status > 1) {
|
||||
this.logger.info("下载中心已取消下载文件,fileId = {}", task.getFileId());
|
||||
exportUpload(task.getBusinessId(), task.getFileId(), null);
|
||||
return;
|
||||
}
|
||||
exportUpload(task.getBusinessId(), task.getFileId(), zipPath.toString());
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("导出标签任务失败:{}", e);
|
||||
this.commonAppDownloadCenterService.finishDownload(task.getBusinessId(), task.getFileId(), null, null, FileStatusEnum.ERROR.getCode());
|
||||
throw new RuntimeException("执行导出标签信息任务异常");
|
||||
}
|
||||
}
|
||||
private CloudwalkResult<List<ImgStorePersonGetResult>> getPersonData(QueryImgPersonParam queryImgPersonParam, CloudwalkCallContext cloudwalkCallContext) {
|
||||
CloudwalkResult<List<ImgStorePersonGetResult>> recordList = new CloudwalkResult();
|
||||
try {
|
||||
recordList = this.imgStorePersonService.listByPage(queryImgPersonParam, cloudwalkCallContext);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("查询记录数据失败");
|
||||
}
|
||||
return recordList;
|
||||
}
|
||||
private CloudwalkResult<List<OrganizationResult>> getOrgData(QueryOrganizationParam param, CloudwalkCallContext context) {
|
||||
CloudwalkResult<List<OrganizationResult>> recordList = new CloudwalkResult();
|
||||
try {
|
||||
recordList = this.organizationService.listByPage(param, context);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("查询机构记录数据失败");
|
||||
}
|
||||
return recordList;
|
||||
}
|
||||
private CloudwalkResult<List<PageLabelResult>> getLabelData(PageLabelParam param, CloudwalkCallContext cloudwalkCallContext) {
|
||||
CloudwalkResult<List<PageLabelResult>> recordList = new CloudwalkResult();
|
||||
try {
|
||||
recordList = this.labelService.listByPage(param, cloudwalkCallContext);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("查询标签记录数据失败");
|
||||
}
|
||||
return recordList;
|
||||
}
|
||||
private void exportUpload(String businessId, String fileId, String zipPathStr) throws IOException {
|
||||
try {
|
||||
if (StringUtils.isNotBlank(zipPathStr)) {
|
||||
uploadFile(businessId, fileId, zipPathStr);
|
||||
} else {
|
||||
byte[] data = Base64Utils.decodeFromString("UEsDBBQACAgIAAuPmlAAAAAAAAAAAAAAAAAGAAAAZW1wdHkvAwBQSwcIAAAAAAIAAAAAAAAAUEsBAhQAFAAICAgAC4+aUAAAAAACAAAAAAAAAAYAAAAAAAAAAAAAAAAAAAAAAGVtcHR5L1BLBQYAAAAAAQABADQAAAA2AAAAAAA=");
|
||||
uploadFile(businessId, fileId, data, data.length);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
this.logger.error("将导出文件生成的zip上传到文件管理中心发生异常:{}", e.getMessage());
|
||||
throw new RuntimeException("将导出文件生成的zip上传到文件管理中心发生异常");
|
||||
} finally {
|
||||
this.logger.debug("删除压缩包:{}", zipPathStr);
|
||||
File file = new File(zipPathStr);
|
||||
if (file.exists()) {
|
||||
Files.delete(file.toPath());
|
||||
}
|
||||
}
|
||||
}
|
||||
private void uploadFile(String businessId, String fileId, byte[] data, long fileSize) {
|
||||
String uuidCode = UUID.randomUUID().toString().replaceAll("-", "");
|
||||
String name = uuidCode + this.commonDownloadDataConfig.getCompressionType();
|
||||
String filePath = this.commonAppStorageService.saveFileBySharding(name, data);
|
||||
this.logger.info("存储文件名:fileId = {}, filePath = {}", fileId, filePath);
|
||||
int status = this.commonAppDownloadCenterService.queryDownloadStatus(businessId, fileId);
|
||||
if (status == FileStatusEnum.PRODUCING.getCode().intValue() || status == FileStatusEnum.ERROR.getCode().intValue()) {
|
||||
this.commonAppDownloadCenterService.finishDownload(businessId, fileId, filePath, Long.valueOf(fileSize), FileStatusEnum.FINISH.getCode());
|
||||
} else {
|
||||
this.commonAppStorageService.deleteFile(filePath);
|
||||
}
|
||||
}
|
||||
private void uploadFile(String businessId, String fileId, String zipPathStr) throws IOException {
|
||||
ChannelFileReader reader = new ChannelFileReader(zipPathStr, this.shardingSize.intValue());
|
||||
try {
|
||||
String uuidCode = UUID.randomUUID().toString().replaceAll("-", "");
|
||||
String name = uuidCode + this.commonDownloadDataConfig.getCompressionType();
|
||||
FilePartInitResult resp = this.iCommonAppFileManageService.filePartInit(name);
|
||||
if (resp == null) {
|
||||
this.logger.info("分片上传文件初始化返回值为空");
|
||||
return;
|
||||
}
|
||||
AtomicInteger i = new AtomicInteger(1);
|
||||
long fileSize = 0L;
|
||||
while (reader.read() != -1) {
|
||||
this.logger.info("分片上传第{}次", Integer.valueOf(i.get()));
|
||||
fileSize += (reader.getArray()).length;
|
||||
uploadFileBySharding(reader.getArray(), resp.getFilePath(), resp.getUploadId(), this.fileName, String.valueOf(i.getAndAdd(1)));
|
||||
}
|
||||
String filePath = filePartFinish(fileSize, resp);
|
||||
if (filePath == null) {
|
||||
this.logger.info("分片上传文件完成接口返回值为空");
|
||||
return;
|
||||
}
|
||||
this.logger.info("分片上传文件完成接口返回值 filePath = {}", filePath);
|
||||
this.logger.info("存储文件名:fileId = {}, filePath = {}", fileId, filePath);
|
||||
int status = this.commonAppDownloadCenterService.queryDownloadStatus(businessId, fileId);
|
||||
if (status == FileStatusEnum.PRODUCING.getCode().intValue() || status == FileStatusEnum.ERROR.getCode().intValue()) {
|
||||
this.commonAppDownloadCenterService.finishDownload(businessId, fileId, filePath, Long.valueOf(fileSize), FileStatusEnum.FINISH.getCode());
|
||||
} else {
|
||||
this.commonAppStorageService.deleteFile(filePath);
|
||||
}
|
||||
this.logger.info("完成上传任务 fileId = {}", fileId);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("分片上传文件报错 {}: {}", e.getClass().getName(), e.getMessage());
|
||||
} finally {
|
||||
reader.close();
|
||||
}
|
||||
}
|
||||
private String filePartFinish(long fileSize, FilePartInitResult resp) {
|
||||
FilePartFinishPara para = new FilePartFinishPara();
|
||||
BeanUtils.copyProperties(resp, para);
|
||||
para.setFileSize(Long.valueOf(fileSize));
|
||||
para.setReturnType(Integer.valueOf(0));
|
||||
return this.iCommonAppFileManageService.filePartFinish(para);
|
||||
}
|
||||
private void uploadFileBySharding(byte[] bytes, String filePath, String uploadId, String fileName, String partNumber) {
|
||||
MultipartFile mfile = MultipartFileUtils.getMultipartFile(fileName, bytes);
|
||||
try {
|
||||
PartInitResultDTO partInitResultDTO = this.filePartManager.append(filePath, Integer.valueOf(partNumber), uploadId, mfile);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("分片更新文件错误{}:{}", e.getClass().getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/export/CommonAppExportExecuteTask.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+241
-288
@@ -1,21 +1,16 @@
|
||||
package cn.cloudwalk.service.organization.export;
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.common.enums.PropertyTypeEnum;
|
||||
import cn.cloudwalk.client.organization.personimg.result.ImgPersonProGetResult;
|
||||
import cn.cloudwalk.client.organization.personimg.result.ImgStorePersonGetResult;
|
||||
import cn.cloudwalk.client.organization.result.PersonProListResult;
|
||||
import cn.cloudwalk.intelligent.davinci.common.exception.DavinciServiceException;
|
||||
import cn.cloudwalk.intelligent.davinci.storage.manager.FileStorageManager;
|
||||
import cn.cloudwalk.service.organization.export.CommonRecordExcelCreater;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.OpenOption;
|
||||
import java.nio.file.Paths;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Instant;
|
||||
import java.util.Collection;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@@ -26,289 +21,247 @@ import org.apache.poi.xssf.usermodel.XSSFRow;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
public class CommonExRecordExcelCreater
|
||||
extends CommonRecordExcelCreater {
|
||||
private static final Logger log = LoggerFactory.getLogger(CommonExRecordExcelCreater.class);
|
||||
private short dateType;
|
||||
private static final String IMAGE_SUFFIX = ".jpg";
|
||||
private Map<Integer, ImgPersonProGetResult> personProMap = new HashMap<Integer, ImgPersonProGetResult>();
|
||||
private FileStorageManager fileStorageManager;
|
||||
|
||||
public CommonExRecordExcelCreater(List<ImgStorePersonGetResult> records, String filePath, int index, FileStorageManager fileStorageManager, PersonProListResult personProListResult, boolean hasContainImage) {
|
||||
super(records, filePath, index);
|
||||
this.fileStorageManager = fileStorageManager;
|
||||
this.personProListResult = personProListResult;
|
||||
this.hasContainImage = hasContainImage;
|
||||
this.dateType = this.wb.getCreationHelper().createDataFormat().getFormat("yyy-mm-dd hh:mm:ss");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void createTitleRow() {
|
||||
XSSFRow titleRow = this.sheet.createRow(2);
|
||||
int columnNum = 0;
|
||||
this.createHeadCell(titleRow, columnNum, "姓名");
|
||||
this.createHeadCell(titleRow, ++columnNum, "用户名");
|
||||
this.createHeadCell(titleRow, ++columnNum, "手机号");
|
||||
this.createHeadCell(titleRow, ++columnNum, "邮箱");
|
||||
this.createHeadCell(titleRow, ++columnNum, "工号");
|
||||
this.createHeadCell(titleRow, ++columnNum, "所属机构");
|
||||
this.createHeadCell(titleRow, ++columnNum, "所属标签");
|
||||
this.createHeadCell(titleRow, ++columnNum, "IC卡号");
|
||||
this.createHeadCell(titleRow, ++columnNum, "IC卡类型");
|
||||
this.createHeadCell(titleRow, ++columnNum, "识别照");
|
||||
this.createHeadCell(titleRow, ++columnNum, "欢迎语");
|
||||
this.createHeadCell(titleRow, ++columnNum, "展示照");
|
||||
this.createHeadCell(titleRow, ++columnNum, "门禁设备(在线)");
|
||||
this.createHeadCell(titleRow, ++columnNum, "门禁设备(离线)");
|
||||
this.createHeadCell(titleRow, ++columnNum, "派梯楼层权限");
|
||||
for (ImgPersonProGetResult imgPersonProGetResult : this.personProListResult.getProperties()) {
|
||||
if (!imgPersonProGetResult.getCode().contains("ext")) continue;
|
||||
this.createHeadCell(titleRow, ++columnNum, imgPersonProGetResult.getName());
|
||||
this.personProMap.put(columnNum, imgPersonProGetResult);
|
||||
}
|
||||
this.sheet.setColumnWidth(1, 5000);
|
||||
this.sheet.setColumnWidth(3, 4000);
|
||||
this.createInfoRow(columnNum);
|
||||
}
|
||||
|
||||
private void createInfoRow(int columnNum) {
|
||||
XSSFRow row0 = this.sheet.createRow(0);
|
||||
XSSFRow row1 = this.sheet.createRow(1);
|
||||
this.createHeadCell(row0, 0, "default-人员批量导入模板");
|
||||
this.createHeadCell(row1, 0, "注:此表中的属性字段由用户在人员属性管理中配置按序生成");
|
||||
CellRangeAddress region0 = new CellRangeAddress(0, 0, 0, columnNum);
|
||||
this.sheet.addMergedRegion(region0);
|
||||
CellRangeAddress region1 = new CellRangeAddress(1, 1, 0, columnNum);
|
||||
this.sheet.addMergedRegion(region1);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void createBodyRows() {
|
||||
if (CollectionUtils.isEmpty((Collection)this.records)) {
|
||||
return;
|
||||
}
|
||||
long start = System.currentTimeMillis();
|
||||
for (int i = 0; i < this.records.size(); ++i) {
|
||||
int rowNum = i + 3;
|
||||
ImgStorePersonGetResult commonRecord = (ImgStorePersonGetResult)this.records.get(i);
|
||||
XSSFRow row = this.sheet.createRow(rowNum);
|
||||
row.setHeight((short)2000);
|
||||
row.createCell(0).setCellValue(commonRecord.getName());
|
||||
row.createCell(1).setCellValue(commonRecord.getUserName());
|
||||
row.createCell(2).setCellValue(commonRecord.getPhone());
|
||||
row.createCell(3).setCellValue(commonRecord.getEmail());
|
||||
row.createCell(4).setCellValue(commonRecord.getPersonCode());
|
||||
row.createCell(5).setCellValue(StringUtils.join((Collection)commonRecord.getOrganizationNames(), (String)","));
|
||||
row.createCell(6).setCellValue(StringUtils.join((Collection)commonRecord.getLabelNames(), (String)","));
|
||||
row.createCell(7).setCellValue(commonRecord.getIcCardNo());
|
||||
row.createCell(8).setCellValue(commonRecord.getIcCardType());
|
||||
row.createCell(10).setCellValue(commonRecord.getWelcome());
|
||||
this.downloadImage(commonRecord.getComparePicture(), commonRecord.getName(), row, 9);
|
||||
this.downloadImage(commonRecord.getShowPicture(), commonRecord.getName(), row, 11);
|
||||
row.createCell(12).setCellValue(commonRecord.getOnlineDevices());
|
||||
row.createCell(13).setCellValue(commonRecord.getOfflineDevices());
|
||||
row.createCell(14).setCellValue(commonRecord.getFloorNames());
|
||||
if (CollectionUtils.isEmpty(this.personProMap)) continue;
|
||||
for (Integer columnIndex : this.personProMap.keySet()) {
|
||||
String getExt = "";
|
||||
switch (columnIndex - 11) {
|
||||
case 1: {
|
||||
getExt = commonRecord.getExt1();
|
||||
break;
|
||||
}
|
||||
case 2: {
|
||||
getExt = commonRecord.getExt2();
|
||||
break;
|
||||
}
|
||||
case 3: {
|
||||
getExt = commonRecord.getExt3();
|
||||
break;
|
||||
}
|
||||
case 4: {
|
||||
getExt = commonRecord.getExt4();
|
||||
break;
|
||||
}
|
||||
case 5: {
|
||||
getExt = commonRecord.getExt5();
|
||||
break;
|
||||
}
|
||||
case 6: {
|
||||
getExt = commonRecord.getExt6();
|
||||
break;
|
||||
}
|
||||
case 7: {
|
||||
getExt = commonRecord.getExt7();
|
||||
break;
|
||||
}
|
||||
case 8: {
|
||||
getExt = commonRecord.getExt8();
|
||||
break;
|
||||
}
|
||||
case 9: {
|
||||
getExt = commonRecord.getExt9();
|
||||
break;
|
||||
}
|
||||
case 10: {
|
||||
getExt = commonRecord.getExt10();
|
||||
break;
|
||||
}
|
||||
case 11: {
|
||||
getExt = commonRecord.getExt11();
|
||||
break;
|
||||
}
|
||||
case 12: {
|
||||
getExt = commonRecord.getExt12();
|
||||
break;
|
||||
}
|
||||
case 13: {
|
||||
getExt = commonRecord.getExt13();
|
||||
break;
|
||||
}
|
||||
case 14: {
|
||||
getExt = commonRecord.getExt14();
|
||||
break;
|
||||
}
|
||||
case 15: {
|
||||
getExt = commonRecord.getExt15();
|
||||
break;
|
||||
}
|
||||
case 16: {
|
||||
getExt = commonRecord.getExt16();
|
||||
break;
|
||||
}
|
||||
case 17: {
|
||||
getExt = commonRecord.getExt17();
|
||||
break;
|
||||
}
|
||||
case 18: {
|
||||
getExt = commonRecord.getExt18();
|
||||
break;
|
||||
}
|
||||
case 19: {
|
||||
getExt = commonRecord.getExt19();
|
||||
break;
|
||||
}
|
||||
case 20: {
|
||||
getExt = commonRecord.getExt20();
|
||||
break;
|
||||
}
|
||||
case 21: {
|
||||
getExt = commonRecord.getExt21();
|
||||
break;
|
||||
}
|
||||
case 22: {
|
||||
getExt = commonRecord.getExt22();
|
||||
break;
|
||||
}
|
||||
case 23: {
|
||||
getExt = commonRecord.getExt23();
|
||||
break;
|
||||
}
|
||||
case 24: {
|
||||
getExt = commonRecord.getExt24();
|
||||
break;
|
||||
}
|
||||
case 25: {
|
||||
getExt = commonRecord.getExt25();
|
||||
break;
|
||||
}
|
||||
case 26: {
|
||||
getExt = commonRecord.getExt26();
|
||||
break;
|
||||
}
|
||||
case 27: {
|
||||
getExt = commonRecord.getExt27();
|
||||
break;
|
||||
}
|
||||
case 28: {
|
||||
getExt = commonRecord.getExt28();
|
||||
break;
|
||||
}
|
||||
case 29: {
|
||||
getExt = commonRecord.getExt29();
|
||||
break;
|
||||
}
|
||||
case 30: {
|
||||
getExt = commonRecord.getExt30();
|
||||
break;
|
||||
}
|
||||
case 31: {
|
||||
getExt = commonRecord.getExt31();
|
||||
break;
|
||||
}
|
||||
case 32: {
|
||||
getExt = commonRecord.getExt32();
|
||||
break;
|
||||
}
|
||||
case 33: {
|
||||
getExt = commonRecord.getExt33();
|
||||
break;
|
||||
}
|
||||
case 34: {
|
||||
getExt = commonRecord.getExt34();
|
||||
break;
|
||||
}
|
||||
case 35: {
|
||||
getExt = commonRecord.getExt35();
|
||||
break;
|
||||
}
|
||||
case 36: {
|
||||
getExt = commonRecord.getExt36();
|
||||
break;
|
||||
}
|
||||
case 37: {
|
||||
getExt = commonRecord.getExt37();
|
||||
break;
|
||||
}
|
||||
case 38: {
|
||||
getExt = commonRecord.getExt38();
|
||||
break;
|
||||
}
|
||||
case 39: {
|
||||
getExt = commonRecord.getExt39();
|
||||
break;
|
||||
}
|
||||
case 40: {
|
||||
getExt = commonRecord.getExt40();
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (this.personProMap.get(columnIndex).getType().shortValue() == PropertyTypeEnum.FILE.getValue()) {
|
||||
this.downloadImage(getExt, commonRecord.getName(), row, columnIndex);
|
||||
continue;
|
||||
}
|
||||
if (this.personProMap.get(columnIndex).getType().shortValue() == PropertyTypeEnum.TIME.getValue()) {
|
||||
if (!StringUtils.isNotBlank((String)getExt)) continue;
|
||||
Instant instant = Instant.ofEpochMilli(Long.valueOf(getExt));
|
||||
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
row.createCell(columnIndex.intValue()).setCellValue(simpleDateFormat.format(Date.from(instant)));
|
||||
continue;
|
||||
}
|
||||
row.createCell(columnIndex.intValue()).setCellValue(getExt);
|
||||
}
|
||||
}
|
||||
long end = System.currentTimeMillis();
|
||||
this.logger.info("导出excel及图片总耗时:{}", (Object)(end - start));
|
||||
}
|
||||
|
||||
private void downloadImage(String picturePath, String name, XSSFRow row, int columnIndex) {
|
||||
if (!this.hasContainImage) {
|
||||
return;
|
||||
}
|
||||
if (StringUtils.isNotBlank((String)picturePath)) {
|
||||
String imageName = System.currentTimeMillis() + "_" + name + IMAGE_SUFFIX;
|
||||
row.createCell(columnIndex).setCellValue(imageName);
|
||||
try (OutputStream out = Files.newOutputStream(Paths.get(this.dirPath + File.separator + imageName, new String[0]), new OpenOption[0]);){
|
||||
byte[] downloadByte = this.fileStorageManager.fileDownload(picturePath);
|
||||
if (null != downloadByte) {
|
||||
out.write(downloadByte);
|
||||
}
|
||||
}
|
||||
catch (DavinciServiceException | IOException e) {
|
||||
this.logger.error("人员导出图片,执行报错 {}: {}", (Object)e.getClass().getName(), (Object)e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
extends CommonRecordExcelCreater
|
||||
{
|
||||
private static final Logger log = LoggerFactory.getLogger(CommonExRecordExcelCreater.class);
|
||||
private short dateType;
|
||||
private static final String IMAGE_SUFFIX = ".jpg";
|
||||
private Map<Integer, ImgPersonProGetResult> personProMap = new HashMap<>();
|
||||
private FileStorageManager fileStorageManager;
|
||||
public CommonExRecordExcelCreater(List<ImgStorePersonGetResult> records, String filePath, int index, FileStorageManager fileStorageManager, PersonProListResult personProListResult, boolean hasContainImage) {
|
||||
super((List)records, filePath, index);
|
||||
this.fileStorageManager = fileStorageManager;
|
||||
this.personProListResult = personProListResult;
|
||||
this.hasContainImage = hasContainImage;
|
||||
this.dateType = this.wb.getCreationHelper().createDataFormat().getFormat("yyy-mm-dd hh:mm:ss");
|
||||
}
|
||||
protected void createTitleRow() {
|
||||
XSSFRow titleRow = this.sheet.createRow(2);
|
||||
int columnNum = 0;
|
||||
createHeadCell(titleRow, columnNum, "姓名");
|
||||
createHeadCell(titleRow, ++columnNum, "用户名");
|
||||
createHeadCell(titleRow, ++columnNum, "手机号");
|
||||
createHeadCell(titleRow, ++columnNum, "邮箱");
|
||||
createHeadCell(titleRow, ++columnNum, "工号");
|
||||
createHeadCell(titleRow, ++columnNum, "所属机构");
|
||||
createHeadCell(titleRow, ++columnNum, "所属标签");
|
||||
createHeadCell(titleRow, ++columnNum, "IC卡号");
|
||||
createHeadCell(titleRow, ++columnNum, "IC卡类型");
|
||||
createHeadCell(titleRow, ++columnNum, "识别照");
|
||||
createHeadCell(titleRow, ++columnNum, "欢迎语");
|
||||
createHeadCell(titleRow, ++columnNum, "展示照");
|
||||
createHeadCell(titleRow, ++columnNum, "门禁设备(在线)");
|
||||
createHeadCell(titleRow, ++columnNum, "门禁设备(离线)");
|
||||
createHeadCell(titleRow, ++columnNum, "派梯楼层权限");
|
||||
for (ImgPersonProGetResult imgPersonProGetResult : this.personProListResult.getProperties()) {
|
||||
if (imgPersonProGetResult.getCode().contains("ext")) {
|
||||
createHeadCell(titleRow, ++columnNum, imgPersonProGetResult.getName());
|
||||
this.personProMap.put(Integer.valueOf(columnNum), imgPersonProGetResult);
|
||||
}
|
||||
}
|
||||
this.sheet.setColumnWidth(1, 5000);
|
||||
this.sheet.setColumnWidth(3, 4000);
|
||||
createInfoRow(columnNum);
|
||||
}
|
||||
private void createInfoRow(int columnNum) {
|
||||
XSSFRow row0 = this.sheet.createRow(0);
|
||||
XSSFRow row1 = this.sheet.createRow(1);
|
||||
createHeadCell(row0, 0, "default-人员批量导入模板");
|
||||
createHeadCell(row1, 0, "注:此表中的属性字段由用户在人员属性管理中配置按序生成");
|
||||
CellRangeAddress region0 = new CellRangeAddress(0, 0, 0, columnNum);
|
||||
this.sheet.addMergedRegion(region0);
|
||||
CellRangeAddress region1 = new CellRangeAddress(1, 1, 0, columnNum);
|
||||
this.sheet.addMergedRegion(region1);
|
||||
}
|
||||
protected void createBodyRows() {
|
||||
if (CollectionUtils.isEmpty(this.records)) {
|
||||
return;
|
||||
}
|
||||
long start = System.currentTimeMillis();
|
||||
for (int i = 0; i < this.records.size(); i++) {
|
||||
int rowNum = i + 3;
|
||||
ImgStorePersonGetResult commonRecord = (ImgStorePersonGetResult)this.records.get(i);
|
||||
XSSFRow row = this.sheet.createRow(rowNum);
|
||||
row.setHeight((short)2000);
|
||||
row.createCell(0).setCellValue(commonRecord.getName());
|
||||
row.createCell(1).setCellValue(commonRecord.getUserName());
|
||||
row.createCell(2).setCellValue(commonRecord.getPhone());
|
||||
row.createCell(3).setCellValue(commonRecord.getEmail());
|
||||
row.createCell(4).setCellValue(commonRecord.getPersonCode());
|
||||
row.createCell(5).setCellValue(StringUtils.join(commonRecord.getOrganizationNames(), ","));
|
||||
row.createCell(6).setCellValue(StringUtils.join(commonRecord.getLabelNames(), ","));
|
||||
row.createCell(7).setCellValue(commonRecord.getIcCardNo());
|
||||
row.createCell(8).setCellValue(commonRecord.getIcCardType());
|
||||
row.createCell(10).setCellValue(commonRecord.getWelcome());
|
||||
downloadImage(commonRecord.getComparePicture(), commonRecord.getName(), row, 9);
|
||||
downloadImage(commonRecord.getShowPicture(), commonRecord.getName(), row, 11);
|
||||
row.createCell(12).setCellValue(commonRecord.getOnlineDevices());
|
||||
row.createCell(13).setCellValue(commonRecord.getOfflineDevices());
|
||||
row.createCell(14).setCellValue(commonRecord.getFloorNames());
|
||||
if (!CollectionUtils.isEmpty(this.personProMap)) {
|
||||
for (Integer columnIndex : this.personProMap.keySet()) {
|
||||
String getExt = "";
|
||||
switch (columnIndex.intValue() - 11) {
|
||||
case 1:
|
||||
getExt = commonRecord.getExt1();
|
||||
break;
|
||||
case 2:
|
||||
getExt = commonRecord.getExt2();
|
||||
break;
|
||||
case 3:
|
||||
getExt = commonRecord.getExt3();
|
||||
break;
|
||||
case 4:
|
||||
getExt = commonRecord.getExt4();
|
||||
break;
|
||||
case 5:
|
||||
getExt = commonRecord.getExt5();
|
||||
break;
|
||||
case 6:
|
||||
getExt = commonRecord.getExt6();
|
||||
break;
|
||||
case 7:
|
||||
getExt = commonRecord.getExt7();
|
||||
break;
|
||||
case 8:
|
||||
getExt = commonRecord.getExt8();
|
||||
break;
|
||||
case 9:
|
||||
getExt = commonRecord.getExt9();
|
||||
break;
|
||||
case 10:
|
||||
getExt = commonRecord.getExt10();
|
||||
break;
|
||||
case 11:
|
||||
getExt = commonRecord.getExt11();
|
||||
break;
|
||||
case 12:
|
||||
getExt = commonRecord.getExt12();
|
||||
break;
|
||||
case 13:
|
||||
getExt = commonRecord.getExt13();
|
||||
break;
|
||||
case 14:
|
||||
getExt = commonRecord.getExt14();
|
||||
break;
|
||||
case 15:
|
||||
getExt = commonRecord.getExt15();
|
||||
break;
|
||||
case 16:
|
||||
getExt = commonRecord.getExt16();
|
||||
break;
|
||||
case 17:
|
||||
getExt = commonRecord.getExt17();
|
||||
break;
|
||||
case 18:
|
||||
getExt = commonRecord.getExt18();
|
||||
break;
|
||||
case 19:
|
||||
getExt = commonRecord.getExt19();
|
||||
break;
|
||||
case 20:
|
||||
getExt = commonRecord.getExt20();
|
||||
break;
|
||||
case 21:
|
||||
getExt = commonRecord.getExt21();
|
||||
break;
|
||||
case 22:
|
||||
getExt = commonRecord.getExt22();
|
||||
break;
|
||||
case 23:
|
||||
getExt = commonRecord.getExt23();
|
||||
break;
|
||||
case 24:
|
||||
getExt = commonRecord.getExt24();
|
||||
break;
|
||||
case 25:
|
||||
getExt = commonRecord.getExt25();
|
||||
break;
|
||||
case 26:
|
||||
getExt = commonRecord.getExt26();
|
||||
break;
|
||||
case 27:
|
||||
getExt = commonRecord.getExt27();
|
||||
break;
|
||||
case 28:
|
||||
getExt = commonRecord.getExt28();
|
||||
break;
|
||||
case 29:
|
||||
getExt = commonRecord.getExt29();
|
||||
break;
|
||||
case 30:
|
||||
getExt = commonRecord.getExt30();
|
||||
break;
|
||||
case 31:
|
||||
getExt = commonRecord.getExt31();
|
||||
break;
|
||||
case 32:
|
||||
getExt = commonRecord.getExt32();
|
||||
break;
|
||||
case 33:
|
||||
getExt = commonRecord.getExt33();
|
||||
break;
|
||||
case 34:
|
||||
getExt = commonRecord.getExt34();
|
||||
break;
|
||||
case 35:
|
||||
getExt = commonRecord.getExt35();
|
||||
break;
|
||||
case 36:
|
||||
getExt = commonRecord.getExt36();
|
||||
break;
|
||||
case 37:
|
||||
getExt = commonRecord.getExt37();
|
||||
break;
|
||||
case 38:
|
||||
getExt = commonRecord.getExt38();
|
||||
break;
|
||||
case 39:
|
||||
getExt = commonRecord.getExt39();
|
||||
break;
|
||||
case 40:
|
||||
getExt = commonRecord.getExt40();
|
||||
break;
|
||||
}
|
||||
if (((ImgPersonProGetResult)this.personProMap.get(columnIndex)).getType().shortValue() == PropertyTypeEnum.FILE.getValue()) {
|
||||
downloadImage(getExt, commonRecord.getName(), row, columnIndex.intValue()); continue;
|
||||
} if (((ImgPersonProGetResult)this.personProMap.get(columnIndex)).getType().shortValue() == PropertyTypeEnum.TIME.getValue()) {
|
||||
if (StringUtils.isNotBlank(getExt)) {
|
||||
Instant instant = Instant.ofEpochMilli(Long.valueOf(getExt).longValue());
|
||||
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
row.createCell(columnIndex.intValue()).setCellValue(simpleDateFormat.format(Date.from(instant)));
|
||||
} continue;
|
||||
}
|
||||
row.createCell(columnIndex.intValue()).setCellValue(getExt);
|
||||
}
|
||||
}
|
||||
}
|
||||
long end = System.currentTimeMillis();
|
||||
this.logger.info("导出excel及图片总耗时:{}", Long.valueOf(end - start));
|
||||
}
|
||||
private void downloadImage(String picturePath, String name, XSSFRow row, int columnIndex) {
|
||||
if (!this.hasContainImage) {
|
||||
return;
|
||||
}
|
||||
if (StringUtils.isNotBlank(picturePath)) {
|
||||
String imageName = System.currentTimeMillis() + "_" + name + ".jpg";
|
||||
row.createCell(columnIndex).setCellValue(imageName);
|
||||
try (OutputStream out = Files.newOutputStream(
|
||||
Paths.get(this.dirPath + File.separator + imageName, new String[0]), new java.nio.file.OpenOption[0])) {
|
||||
byte[] downloadByte = this.fileStorageManager.fileDownload(picturePath);
|
||||
if (null != downloadByte) {
|
||||
out.write(downloadByte);
|
||||
}
|
||||
} catch (DavinciServiceException|java.io.IOException e) {
|
||||
this.logger.error("人员导出图片,执行报错 {}: {}", e.getClass().getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/export/CommonExRecordExcelCreater.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+29
-26
@@ -1,5 +1,4 @@
|
||||
package cn.cloudwalk.service.organization.listener;
|
||||
// 业务服务
|
||||
import cn.cloudwalk.cloud.utils.ApplicationContextUtils;
|
||||
import cn.cloudwalk.cwos.client.event.event.BaseEvent;
|
||||
import cn.cloudwalk.cwos.client.event.event.DeviceGroupRefChangeEvent;
|
||||
@@ -13,31 +12,35 @@ import cn.cloudwalk.service.organization.service.PictureResultEventHandler;
|
||||
import cn.cloudwalk.service.organization.service.corp.handler.EnterpriseChangeHandler;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class ComponentOrganizationEventListener
|
||||
implements EventListener {
|
||||
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
|
||||
public void messageListener(BaseEvent baseEvent) throws RuntimeException {
|
||||
if (baseEvent instanceof PersonCardCompareEvent) {
|
||||
PersonCardCompareEvent personCardCompareEvent = (PersonCardCompareEvent)baseEvent;
|
||||
this.logger.debug("receive personCardCompareEvent kafka message {}", (Object)personCardCompareEvent);
|
||||
((PersonCardCompareEventHandler)ApplicationContextUtils.getBean(PersonCardCompareEventHandler.class)).handler(personCardCompareEvent);
|
||||
} else if (baseEvent instanceof PictureResultEvent) {
|
||||
PictureResultEvent pictureResultEvent = (PictureResultEvent)baseEvent;
|
||||
this.logger.debug("receive pictureResultEvent kafka message {}", (Object)pictureResultEvent);
|
||||
((PictureResultEventHandler)ApplicationContextUtils.getBean(PictureResultEventHandler.class)).handler(pictureResultEvent);
|
||||
} else if (baseEvent instanceof DeviceGroupRefChangeEvent) {
|
||||
DeviceGroupRefChangeEvent deviceGroupRefChangeEvent = (DeviceGroupRefChangeEvent)baseEvent;
|
||||
this.logger.debug("receive deviceGroupRefChangeEvent kafka message {}", (Object)deviceGroupRefChangeEvent);
|
||||
((DeviceGroupRefChangeEventHandler)ApplicationContextUtils.getBean(DeviceGroupRefChangeEventHandler.class)).handler(deviceGroupRefChangeEvent);
|
||||
} else if (baseEvent instanceof EnterpriseChangeEvent) {
|
||||
EnterpriseChangeEvent enterpriseChangeEvent = (EnterpriseChangeEvent)baseEvent;
|
||||
this.logger.debug("receive enterpriseChangeEvent kafka message {}", (Object)enterpriseChangeEvent);
|
||||
((EnterpriseChangeHandler)ApplicationContextUtils.getBean(EnterpriseChangeHandler.class)).handler(enterpriseChangeEvent);
|
||||
} else {
|
||||
this.logger.info("不能识别的baseEvent:{}", (Object)baseEvent);
|
||||
}
|
||||
}
|
||||
implements EventListener
|
||||
{
|
||||
protected final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
public void messageListener(BaseEvent baseEvent) throws RuntimeException {
|
||||
if (baseEvent instanceof PersonCardCompareEvent) {
|
||||
PersonCardCompareEvent personCardCompareEvent = (PersonCardCompareEvent)baseEvent;
|
||||
this.logger.debug("receive personCardCompareEvent kafka message {}", personCardCompareEvent);
|
||||
((PersonCardCompareEventHandler)ApplicationContextUtils.getBean(PersonCardCompareEventHandler.class)).handler(personCardCompareEvent);
|
||||
} else if (baseEvent instanceof PictureResultEvent) {
|
||||
PictureResultEvent pictureResultEvent = (PictureResultEvent)baseEvent;
|
||||
this.logger.debug("receive pictureResultEvent kafka message {}", pictureResultEvent);
|
||||
((PictureResultEventHandler)ApplicationContextUtils.getBean(PictureResultEventHandler.class)).handler(pictureResultEvent);
|
||||
} else if (baseEvent instanceof DeviceGroupRefChangeEvent) {
|
||||
DeviceGroupRefChangeEvent deviceGroupRefChangeEvent = (DeviceGroupRefChangeEvent)baseEvent;
|
||||
this.logger.debug("receive deviceGroupRefChangeEvent kafka message {}", deviceGroupRefChangeEvent);
|
||||
((DeviceGroupRefChangeEventHandler)ApplicationContextUtils.getBean(DeviceGroupRefChangeEventHandler.class)).handler(deviceGroupRefChangeEvent);
|
||||
} else if (baseEvent instanceof EnterpriseChangeEvent) {
|
||||
EnterpriseChangeEvent enterpriseChangeEvent = (EnterpriseChangeEvent)baseEvent;
|
||||
this.logger.debug("receive enterpriseChangeEvent kafka message {}", enterpriseChangeEvent);
|
||||
((EnterpriseChangeHandler)ApplicationContextUtils.getBean(EnterpriseChangeHandler.class)).handler(enterpriseChangeEvent);
|
||||
} else {
|
||||
this.logger.info("不能识别的baseEvent:{}", baseEvent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/listener/ComponentOrganizationEventListener.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+403
-452
@@ -1,5 +1,5 @@
|
||||
package cn.cloudwalk.service.organization.schedule;
|
||||
// 业务服务
|
||||
// 调度服务
|
||||
import cn.cloudwalk.client.organization.batch.service.ImgPersonBatchService;
|
||||
import cn.cloudwalk.client.organization.common.exception.ImageStoreException;
|
||||
import cn.cloudwalk.client.organization.param.QueryZoneForm;
|
||||
@@ -13,6 +13,8 @@ import cn.cloudwalk.cloud.utils.CloudwalkDateUtils;
|
||||
import cn.cloudwalk.data.organization.dto.GetsLabelDTO;
|
||||
import cn.cloudwalk.data.organization.entity.BatchImport;
|
||||
import cn.cloudwalk.data.organization.entity.ImgStorePersonProperties;
|
||||
import cn.cloudwalk.data.organization.entity.Label;
|
||||
import cn.cloudwalk.data.organization.entity.Organization;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStoreLabelMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStoreOrganizationMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonPropertiesMapper;
|
||||
@@ -21,7 +23,6 @@ import cn.cloudwalk.service.organization.common.ExcelUtils;
|
||||
import cn.cloudwalk.service.organization.common.FileUtil;
|
||||
import cn.cloudwalk.service.organization.common.PathUtils;
|
||||
import cn.cloudwalk.service.organization.common.ZipUtil;
|
||||
import cn.cloudwalk.service.organization.schedule.BatchImportContext;
|
||||
import cn.cloudwalk.service.organization.service.feign.ZoneFeignClient;
|
||||
import cn.cloudwalk.task.sdk.starter.job.AbstractJob;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
@@ -35,16 +36,15 @@ import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import javax.annotation.Resource;
|
||||
import org.apache.commons.collections.CollectionUtils;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
@@ -61,455 +61,406 @@ import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
|
||||
@DisallowConcurrentExecution
|
||||
public class PersonBatchImportTask
|
||||
extends AbstractJob {
|
||||
private static final Logger logger = LoggerFactory.getLogger(PersonBatchImportTask.class);
|
||||
@Autowired
|
||||
private PersonBatchImportMapper personBatchImportMapper;
|
||||
@Autowired
|
||||
private MessageSource messageSource;
|
||||
@Autowired
|
||||
@Qualifier(value="personImportExecutor")
|
||||
private ThreadPoolTaskExecutor taskExecutor;
|
||||
@Autowired
|
||||
private PersonFileService personFileService;
|
||||
@Value(value="${cloudwalk.person.import.filePath:/data/cwos/file/temp}")
|
||||
private String tempPath;
|
||||
@Value(value="${cloudwalk.person.import.batch.size: 1000}")
|
||||
private Integer batchSize;
|
||||
@Autowired
|
||||
private CloudwalkSessionContextHolder sessionContextHolder;
|
||||
@Autowired
|
||||
private ImgStorePersonPropertiesMapper propertiesMapper;
|
||||
@Autowired
|
||||
private ImgStoreOrganizationMapper organizationMapper;
|
||||
@Autowired
|
||||
private ImgStoreLabelMapper labelMapper;
|
||||
@Resource
|
||||
private ZoneFeignClient zoneFeignClient;
|
||||
private static final int BATCH_WIDTH = 3;
|
||||
private static final Semaphore BATCH_SEMAPHORE = new Semaphore(3, true);
|
||||
@Autowired
|
||||
private ImgPersonBatchService imgPersonBatchService;
|
||||
|
||||
private void process(BatchImportContext processContext) throws ImageStoreException, InterruptedException {
|
||||
List<File> excelFiles = processContext.getExcelFiles();
|
||||
for (File excel : excelFiles) {
|
||||
this.readExcelFile2DB(excel, processContext);
|
||||
}
|
||||
while (BATCH_SEMAPHORE.availablePermits() != 3) {
|
||||
Thread.sleep(1000L);
|
||||
}
|
||||
}
|
||||
|
||||
private void readExcelFile2DB(File excelFile, BatchImportContext context) throws ImageStoreException {
|
||||
List allOrg = this.organizationMapper.getAllOrg(context.getBatchImport().getBusinessId());
|
||||
context.setOrgMap(allOrg);
|
||||
GetsLabelDTO getsLabelDTO = new GetsLabelDTO();
|
||||
getsLabelDTO.setBusinessId(context.getBatchImport().getBusinessId());
|
||||
List allLabels = this.labelMapper.getAllLabels(getsLabelDTO);
|
||||
context.setLabelMap(allLabels);
|
||||
QueryZoneForm queryZoneForm = new QueryZoneForm();
|
||||
queryZoneForm.setBusinessId(context.getBatchImport().getBusinessId());
|
||||
CloudwalkResult<List<ZoneResult>> zoneDetail = this.zoneFeignClient.findZonelist(queryZoneForm);
|
||||
logger.info("当前楼层信息Task{}", (Object)JSON.toJSONString(zoneDetail));
|
||||
if ("00000000".equals(zoneDetail.getCode())) {
|
||||
List data = (List)zoneDetail.getData();
|
||||
context.setZoneMap(data);
|
||||
}
|
||||
try (FileInputStream inputStream = new FileInputStream(excelFile);
|
||||
Workbook workbook = WorkbookFactory.create((InputStream)inputStream);){
|
||||
Sheet sheet = workbook.getSheetAt(0);
|
||||
Row titleRow = sheet.getRow(2);
|
||||
int endIndex = titleRow.getLastCellNum();
|
||||
HashMap<Integer, String> nameIndexMap = new HashMap<Integer, String>();
|
||||
for (int i = 0; i < endIndex; ++i) {
|
||||
Cell cell = titleRow.getCell(i);
|
||||
String value = cell.getStringCellValue();
|
||||
if (value.contains("(")) {
|
||||
value = value.split("(")[0];
|
||||
}
|
||||
nameIndexMap.put(i, value);
|
||||
}
|
||||
context.setNameIndexMap(nameIndexMap);
|
||||
ArrayList<List<String>> batchRecordList = new ArrayList<List<String>>(this.batchSize);
|
||||
int totalCount = 0;
|
||||
for (Row row : sheet) {
|
||||
if (row.getRowNum() <= 2) continue;
|
||||
ArrayList<String> rowData = new ArrayList<String>();
|
||||
boolean isEmptyRow = true;
|
||||
for (int c = 0; c < endIndex; ++c) {
|
||||
String cellStr;
|
||||
Cell cell = row.getCell(c);
|
||||
if (cell == null) {
|
||||
cellStr = null;
|
||||
} else {
|
||||
cellStr = ExcelUtils.getCellStringValue(cell);
|
||||
if (StringUtils.isNotBlank((CharSequence)cellStr)) {
|
||||
isEmptyRow = false;
|
||||
}
|
||||
}
|
||||
rowData.add(c, cellStr);
|
||||
}
|
||||
if (isEmptyRow) continue;
|
||||
batchRecordList.add(rowData);
|
||||
++totalCount;
|
||||
if (batchRecordList.size() != this.batchSize.intValue()) continue;
|
||||
this.parallelBatchAdd(batchRecordList, context, excelFile.getParent());
|
||||
batchRecordList = new ArrayList(this.batchSize);
|
||||
}
|
||||
if (totalCount == 0) {
|
||||
throw new ImageStoreException("53014040", this.getMessage("53014040"));
|
||||
}
|
||||
this.parallelBatchAdd(batchRecordList, context, excelFile.getParent());
|
||||
}
|
||||
catch (IOException | InvalidFormatException e) {
|
||||
logger.error("", e);
|
||||
throw new ImageStoreException("53014036", this.getMessage("53014036"));
|
||||
}
|
||||
}
|
||||
|
||||
private void parallelBatchAdd(final List<List<String>> batchRecordList, final BatchImportContext context, final String filePath) {
|
||||
try {
|
||||
BATCH_SEMAPHORE.acquire();
|
||||
logger.info("person import task concurrent number :{}", (Object)(3 - BATCH_SEMAPHORE.availablePermits()));
|
||||
}
|
||||
catch (InterruptedException e) {
|
||||
logger.error("", e);
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
this.taskExecutor.submit(new Runnable(){
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
PersonBatchImportTask.this.imgPersonBatchService.handlerBatchPersonImport(batchRecordList, (Object)context, filePath);
|
||||
BatchImport batchImport = context.getBatchImport();
|
||||
BatchImport updateObj = new BatchImport();
|
||||
updateObj.setId(batchImport.getId());
|
||||
updateObj.setCurrentCount(Long.valueOf(context.getFailCount().get() + context.getSuccessCount().get()));
|
||||
PersonBatchImportTask.this.personBatchImportMapper.updateById(updateObj);
|
||||
}
|
||||
catch (Exception e) {
|
||||
logger.error("", e);
|
||||
}
|
||||
finally {
|
||||
BATCH_SEMAPHORE.release();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void cleanFiles(BatchImportContext context) {
|
||||
try {
|
||||
FileUtils.deleteDirectory((File)context.getUnzipFolder());
|
||||
this.personFileService.delete((List)Lists.newArrayList((Object[])new String[]{context.getBatchImport().getFilePath()}));
|
||||
FileUtils.deleteQuietly((File)new File(this.tempPath, context.getBatchImport().getBatchNo() + ".zip"));
|
||||
}
|
||||
catch (Exception ex) {
|
||||
logger.error("", ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
|
||||
BatchImport batchImportRecord = null;
|
||||
BatchImportContext batchImportContext = new BatchImportContext();
|
||||
String remark = null;
|
||||
try {
|
||||
logger.info("start handler import batch, query wait import task");
|
||||
batchImportRecord = this.getBatchImportQueryResult();
|
||||
batchImportContext.setBatchImport(batchImportRecord);
|
||||
if (batchImportRecord == null) {
|
||||
logger.info("start handler import batch, query wait import is empty");
|
||||
return;
|
||||
}
|
||||
logger.info("start handler import batch ,batchInfo:[{}]", (Object)JSONObject.toJSONString((Object)batchImportRecord));
|
||||
this.updateBatchImportRecord(ImportStatus.PROCESSING, "", batchImportRecord.getId(), 0L);
|
||||
long unzipStartTime = System.currentTimeMillis();
|
||||
this.unzipFile(batchImportContext);
|
||||
long unzipSpendTime = System.currentTimeMillis() - unzipStartTime;
|
||||
this.checkFileExists(batchImportContext);
|
||||
long startCalculateTime = System.currentTimeMillis();
|
||||
batchImportContext.setTotalCount(this.calculateRecordSize(batchImportContext));
|
||||
this.updateBatchImportRecord(batchImportContext.getTotalCount(), batchImportRecord.getId());
|
||||
long calculateSpendTime = System.currentTimeMillis() - startCalculateTime;
|
||||
ImgStorePersonProperties condition = new ImgStorePersonProperties();
|
||||
condition.setBusinessId(batchImportContext.getBatchImport().getBusinessId());
|
||||
List personProperties = this.propertiesMapper.select(condition);
|
||||
logger.debug("personProperties:[{}]", (Object)JSONObject.toJSONString((Object)personProperties));
|
||||
batchImportContext.setNameCodeMap(personProperties);
|
||||
this.process(batchImportContext);
|
||||
long cleanStartTime = System.currentTimeMillis();
|
||||
this.cleanFiles(batchImportContext);
|
||||
long cleanSpendTime = System.currentTimeMillis() - cleanStartTime;
|
||||
long processSpendTime = System.currentTimeMillis() - unzipStartTime;
|
||||
remark = String.format("导入完成,导入成功[%s]条,失败[%s]条,总耗时[%s],解压耗时[%s], 统计总数耗时[%s],图片复制耗时[%s],数据插入耗时[%s], 清理文件耗时[%s]", batchImportContext.getSuccessCount(), batchImportContext.getFailCount(), PersonBatchImportTask.convertTime(processSpendTime), PersonBatchImportTask.convertTime(unzipSpendTime), PersonBatchImportTask.convertTime(calculateSpendTime), PersonBatchImportTask.convertTime(batchImportContext.getImageCopyTime().get() / (long)this.taskExecutor.getMaxPoolSize()), PersonBatchImportTask.convertTime(batchImportContext.getInsertTime().get() / (long)this.taskExecutor.getMaxPoolSize()), PersonBatchImportTask.convertTime(cleanSpendTime));
|
||||
BatchImport batchImport = this.personBatchImportMapper.selectById(batchImportRecord.getId());
|
||||
this.updateBatchImportRecord(ImportStatus.COMPLETE, remark, batchImportRecord.getId(), batchImport.getTotalCount());
|
||||
}
|
||||
catch (ImageStoreException ex) {
|
||||
if (batchImportRecord != null) {
|
||||
remark = ex.getMessage();
|
||||
this.updateBatchImportRecord(ImportStatus.EXCEPTION, remark, batchImportRecord.getId(), null);
|
||||
}
|
||||
}
|
||||
catch (InterruptedException e) {
|
||||
if (batchImportRecord != null) {
|
||||
this.updateBatchImportRecord(ImportStatus.EXCEPTION, "导入任务异常终止", batchImportRecord.getId(), null);
|
||||
}
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
private long calculateRecordSize(BatchImportContext context) {
|
||||
List<File> fileList = context.getExcelFiles();
|
||||
long totalCount = 0L;
|
||||
for (File file : fileList) {
|
||||
try {
|
||||
FileInputStream inputStream = new FileInputStream(file);
|
||||
Throwable throwable = null;
|
||||
try {
|
||||
Workbook workbook = WorkbookFactory.create((InputStream)inputStream);
|
||||
Throwable throwable2 = null;
|
||||
try {
|
||||
Sheet sheet = workbook.getSheetAt(0);
|
||||
totalCount += (long)(sheet.getPhysicalNumberOfRows() - 3);
|
||||
}
|
||||
catch (Throwable throwable3) {
|
||||
throwable2 = throwable3;
|
||||
throw throwable3;
|
||||
}
|
||||
finally {
|
||||
if (workbook == null) continue;
|
||||
if (throwable2 != null) {
|
||||
try {
|
||||
workbook.close();
|
||||
}
|
||||
catch (Throwable throwable4) {
|
||||
throwable2.addSuppressed(throwable4);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
workbook.close();
|
||||
}
|
||||
}
|
||||
catch (Throwable throwable5) {
|
||||
throwable = throwable5;
|
||||
throw throwable5;
|
||||
}
|
||||
finally {
|
||||
if (inputStream == null) continue;
|
||||
if (throwable != null) {
|
||||
try {
|
||||
inputStream.close();
|
||||
}
|
||||
catch (Throwable throwable6) {
|
||||
throwable.addSuppressed(throwable6);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
inputStream.close();
|
||||
}
|
||||
}
|
||||
catch (IOException | InvalidFormatException e) {
|
||||
logger.warn("当前文件统计总记录数异常,文件名:{},文件路径:{}", (Object)file.getName(), (Object)file.getPath());
|
||||
}
|
||||
}
|
||||
return totalCount;
|
||||
}
|
||||
|
||||
private void checkFileExists(BatchImportContext context) throws ImageStoreException {
|
||||
List<File> fileList = null;
|
||||
fileList = FileUtil.findExpecteFormatdFile(".+(\\.xls|\\.xlsx)$", context.getUnzipFolder(), null);
|
||||
if (fileList.isEmpty()) {
|
||||
throw new ImageStoreException("53014039", this.getMessage("53014039"));
|
||||
}
|
||||
context.setExcelFiles(fileList);
|
||||
}
|
||||
|
||||
private void unzipFile(BatchImportContext context) throws ImageStoreException {
|
||||
File tempDir = new File(this.tempPath);
|
||||
if (!tempDir.exists()) {
|
||||
tempDir.mkdirs();
|
||||
}
|
||||
File file = new File(this.tempPath, context.getBatchImport().getBatchNo() + ".zip");
|
||||
logger.info("download to local. sourcePath:[{}], localPath:[{}]", (Object)context.getBatchImport().getFilePath(), (Object)file.getAbsolutePath());
|
||||
CloudwalkResult downloadResult = this.personFileService.download(context.getBatchImport().getFilePath());
|
||||
if (!downloadResult.isSuccess()) {
|
||||
throw new ImageStoreException(downloadResult.getCode(), downloadResult.getMessage());
|
||||
}
|
||||
try (InputStream inputStream = (InputStream)downloadResult.getData();){
|
||||
FileUtils.copyInputStreamToFile((InputStream)inputStream, (File)file);
|
||||
}
|
||||
catch (Exception e) {
|
||||
logger.error("download file from storage component exception", e);
|
||||
throw new ImageStoreException("53014037", this.getMessage("53014037"));
|
||||
}
|
||||
if (!file.exists()) {
|
||||
throw new ImageStoreException("53014037", this.getMessage("53014037"));
|
||||
}
|
||||
try {
|
||||
File unzipFolder;
|
||||
if (this.checkUnzip()) {
|
||||
String line;
|
||||
String unzipPath = PathUtils.joinPaths(this.tempPath, "temp", CloudwalkDateUtils.getUUID());
|
||||
unzipFolder = new File(unzipPath);
|
||||
unzipFolder.mkdirs();
|
||||
logger.info("解压前文件路径:{},解压后文件路径:{},编码方式:{}", new Object[]{file.getPath(), unzipFolder.getPath(), "utf-8"});
|
||||
String commandLine = String.format("unzip -q -O %s %s -d %s", "GBK", file.getPath(), unzipFolder.getPath());
|
||||
ProcessBuilder processBuilder = new ProcessBuilder("/bin/sh", "-c", commandLine);
|
||||
processBuilder.redirectErrorStream(true);
|
||||
Process process = processBuilder.start();
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
|
||||
while ((line = reader.readLine()) != null) {
|
||||
logger.info(line);
|
||||
}
|
||||
int result = process.waitFor();
|
||||
if (result == 1 || result == 2) {
|
||||
logger.warn("---unzip 进程退出码:{}", (Object)result);
|
||||
}
|
||||
if (result != 0 && result != 1 && result != 2) {
|
||||
throw new ImageStoreException("53014038", this.getMessage("53014038"));
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
unzipFolder = ZipUtil.unzipFile(file, "UTF-8");
|
||||
}
|
||||
catch (IllegalArgumentException e) {
|
||||
unzipFolder = ZipUtil.unzipFile(file, "GBK");
|
||||
}
|
||||
}
|
||||
context.setUnzipFolder(unzipFolder);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
logger.error(ex.getMessage(), ex);
|
||||
throw new ImageStoreException("53014038", this.getMessage("53014038"));
|
||||
}
|
||||
}
|
||||
|
||||
private boolean checkUnzip() {
|
||||
try {
|
||||
int length;
|
||||
Process process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", "unzip -help"});
|
||||
process.waitFor();
|
||||
InputStream inputStream = process.getInputStream();
|
||||
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
|
||||
byte[] buffer = new byte[1024];
|
||||
while ((length = inputStream.read(buffer)) != -1) {
|
||||
byteArrayOutputStream.write(buffer, 0, length);
|
||||
}
|
||||
String outputResult = byteArrayOutputStream.toString("UTF-8");
|
||||
try {
|
||||
inputStream.close();
|
||||
byteArrayOutputStream.close();
|
||||
}
|
||||
catch (IOException ignored) {
|
||||
logger.error("exception:{}", (Object)ignored.getMessage());
|
||||
}
|
||||
if (outputResult.contains("-O")) {
|
||||
logger.info("支持unzip解压,使用unzip进行解压");
|
||||
return true;
|
||||
}
|
||||
logger.warn("不支持unzip解压,请升级至最新unzip");
|
||||
}
|
||||
catch (IOException | InterruptedException e) {
|
||||
logger.error(e.getMessage());
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private synchronized BatchImport getBatchImportQueryResult() {
|
||||
Long fromTime = System.currentTimeMillis() - 86400000L;
|
||||
List query = this.personBatchImportMapper.selectImportTask(fromTime);
|
||||
BatchImport pendingImport = null;
|
||||
if (CollectionUtils.isNotEmpty((Collection)query)) {
|
||||
for (BatchImport q : query) {
|
||||
if (ImportStatus.from((Integer)q.getStatus()) == ImportStatus.NONE && pendingImport == null) {
|
||||
pendingImport = q;
|
||||
continue;
|
||||
}
|
||||
if (ImportStatus.from((Integer)q.getStatus()) != ImportStatus.PROCESSING) continue;
|
||||
q.setStatus(ImportStatus.EXCEPTION.value());
|
||||
q.setRemark(this.getMessage("53014036"));
|
||||
this.personBatchImportMapper.updateById(q);
|
||||
}
|
||||
}
|
||||
if (pendingImport == null) {
|
||||
return null;
|
||||
}
|
||||
return (BatchImport)BeanCopyUtils.copyProperties(pendingImport, BatchImport.class);
|
||||
}
|
||||
|
||||
private static String convertTime(long executeTime) {
|
||||
long ms = 1000L;
|
||||
long minute = 60L * ms;
|
||||
long hour = 60L * minute;
|
||||
long day = 24L * hour;
|
||||
long days = executeTime / day;
|
||||
long hours = executeTime % day / hour;
|
||||
long minutes = executeTime % hour / minute;
|
||||
long seconds = executeTime % minute / ms;
|
||||
long milliSeconds = executeTime % ms;
|
||||
StringBuilder builder = new StringBuilder();
|
||||
if (days != 0L) {
|
||||
builder.append(days).append("天");
|
||||
}
|
||||
if (hours != 0L) {
|
||||
builder.append(hours).append("小时");
|
||||
}
|
||||
if (minutes != 0L) {
|
||||
builder.append(minutes).append("分");
|
||||
}
|
||||
if (seconds != 0L) {
|
||||
builder.append(seconds).append("秒");
|
||||
}
|
||||
if (builder.length() < 1) {
|
||||
builder.append(milliSeconds).append("毫秒");
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
private void updateBatchImportRecord(ImportStatus status, String remark, String id, Long currentCount) {
|
||||
try {
|
||||
logger.info("设置当前任务[{}]状态为[{}]", (Object)id, (Object)status);
|
||||
BatchImport bi = new BatchImport();
|
||||
bi.setId(id);
|
||||
bi.setStatus(status.value());
|
||||
bi.setCurrentCount(currentCount);
|
||||
if (status == ImportStatus.COMPLETE || status == ImportStatus.EXCEPTION) {
|
||||
bi.setFinishTime(Long.valueOf(System.currentTimeMillis()));
|
||||
}
|
||||
bi.setRemark(StringUtils.left((String)remark, (int)255));
|
||||
this.personBatchImportMapper.updateById(bi);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
logger.error("", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void updateBatchImportRecord(Long totalCount, String id) {
|
||||
try {
|
||||
BatchImport bi = new BatchImport();
|
||||
bi.setId(id);
|
||||
bi.setTotalCount(totalCount);
|
||||
this.personBatchImportMapper.updateById(bi);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
logger.error("", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private String getMessage(String code) {
|
||||
try {
|
||||
return this.messageSource.getMessage(code, null, LocaleContextHolder.getLocale());
|
||||
}
|
||||
catch (Exception ex) {
|
||||
logger.warn("", ex);
|
||||
return code;
|
||||
}
|
||||
}
|
||||
extends AbstractJob
|
||||
{
|
||||
private static final Logger logger = LoggerFactory.getLogger(PersonBatchImportTask.class);
|
||||
@Autowired
|
||||
private PersonBatchImportMapper personBatchImportMapper;
|
||||
@Autowired
|
||||
private MessageSource messageSource;
|
||||
@Autowired
|
||||
@Qualifier("personImportExecutor")
|
||||
private ThreadPoolTaskExecutor taskExecutor;
|
||||
@Autowired
|
||||
private PersonFileService personFileService;
|
||||
@Value("${cloudwalk.person.import.filePath:/data/cwos/file/temp}")
|
||||
private String tempPath;
|
||||
@Value("${cloudwalk.person.import.batch.size: 1000}")
|
||||
private Integer batchSize;
|
||||
@Autowired
|
||||
private CloudwalkSessionContextHolder sessionContextHolder;
|
||||
@Autowired
|
||||
private ImgStorePersonPropertiesMapper propertiesMapper;
|
||||
@Autowired
|
||||
private ImgStoreOrganizationMapper organizationMapper;
|
||||
@Autowired
|
||||
private ImgStoreLabelMapper labelMapper;
|
||||
@Resource
|
||||
private ZoneFeignClient zoneFeignClient;
|
||||
private static final int BATCH_WIDTH = 3;
|
||||
private static final Semaphore BATCH_SEMAPHORE = new Semaphore(3, true);
|
||||
@Autowired
|
||||
private ImgPersonBatchService imgPersonBatchService;
|
||||
private void process(BatchImportContext processContext) throws ImageStoreException, InterruptedException {
|
||||
List<File> excelFiles = processContext.getExcelFiles();
|
||||
for (File excel : excelFiles) {
|
||||
readExcelFile2DB(excel, processContext);
|
||||
}
|
||||
while (BATCH_SEMAPHORE.availablePermits() != 3)
|
||||
{
|
||||
Thread.sleep(1000L);
|
||||
}
|
||||
}
|
||||
private void readExcelFile2DB(File excelFile, BatchImportContext context) throws ImageStoreException {
|
||||
List<Organization> allOrg = this.organizationMapper.getAllOrg(context.getBatchImport().getBusinessId());
|
||||
context.setOrgMap(allOrg);
|
||||
GetsLabelDTO getsLabelDTO = new GetsLabelDTO();
|
||||
getsLabelDTO.setBusinessId(context.getBatchImport().getBusinessId());
|
||||
List<Label> allLabels = this.labelMapper.getAllLabels(getsLabelDTO);
|
||||
context.setLabelMap(allLabels);
|
||||
QueryZoneForm queryZoneForm = new QueryZoneForm();
|
||||
queryZoneForm.setBusinessId(context.getBatchImport().getBusinessId());
|
||||
CloudwalkResult<List<ZoneResult>> zoneDetail = this.zoneFeignClient.findZonelist(queryZoneForm);
|
||||
logger.info("当前楼层信息Task{}", JSON.toJSONString(zoneDetail));
|
||||
if (Objects.equals(zoneDetail.getCode(), "00000000")) {
|
||||
List<ZoneResult> data = (List<ZoneResult>)zoneDetail.getData();
|
||||
context.setZoneMap(data);
|
||||
}
|
||||
try(InputStream inputStream = new FileInputStream(excelFile);
|
||||
Workbook workbook = WorkbookFactory.create(inputStream)) {
|
||||
Sheet sheet = workbook.getSheetAt(0);
|
||||
Row titleRow = sheet.getRow(2);
|
||||
short endIndex = titleRow.getLastCellNum();
|
||||
Map<Integer, String> nameIndexMap = new HashMap<>();
|
||||
for (int i = 0; i < endIndex; i++) {
|
||||
Cell cell = titleRow.getCell(i);
|
||||
String value = cell.getStringCellValue();
|
||||
if (value.contains("(")) {
|
||||
value = value.split("(")[0];
|
||||
}
|
||||
nameIndexMap.put(Integer.valueOf(i), value);
|
||||
}
|
||||
context.setNameIndexMap(nameIndexMap);
|
||||
List<List<String>> batchRecordList = new ArrayList<>(this.batchSize.intValue());
|
||||
int totalCount = 0;
|
||||
for (Row row : sheet) {
|
||||
if (row.getRowNum() <= 2) {
|
||||
continue;
|
||||
}
|
||||
List<String> rowData = new ArrayList<>();
|
||||
boolean isEmptyRow = true;
|
||||
for (int c = 0; c < endIndex; c++) {
|
||||
String cellStr;
|
||||
Cell cell = row.getCell(c);
|
||||
if (cell == null) {
|
||||
cellStr = null;
|
||||
} else {
|
||||
cellStr = ExcelUtils.getCellStringValue(cell);
|
||||
if (StringUtils.isNotBlank(cellStr)) {
|
||||
isEmptyRow = false;
|
||||
}
|
||||
}
|
||||
rowData.add(c, cellStr);
|
||||
}
|
||||
if (isEmptyRow) {
|
||||
continue;
|
||||
}
|
||||
batchRecordList.add(rowData);
|
||||
totalCount++;
|
||||
if (batchRecordList.size() == this.batchSize.intValue()) {
|
||||
parallelBatchAdd(batchRecordList, context, excelFile.getParent());
|
||||
batchRecordList = new ArrayList<>(this.batchSize.intValue());
|
||||
}
|
||||
}
|
||||
if (totalCount == 0)
|
||||
{
|
||||
throw new ImageStoreException("53014040", getMessage("53014040"));
|
||||
}
|
||||
parallelBatchAdd(batchRecordList, context, excelFile.getParent());
|
||||
} catch (IOException|org.apache.poi.openxml4j.exceptions.InvalidFormatException e) {
|
||||
logger.error("", e);
|
||||
throw new ImageStoreException("53014036", getMessage("53014036"));
|
||||
}
|
||||
}
|
||||
private void parallelBatchAdd(final List<List<String>> batchRecordList, final BatchImportContext context, final String filePath) {
|
||||
try {
|
||||
BATCH_SEMAPHORE.acquire();
|
||||
logger.info("person import task concurrent number :{}", Integer.valueOf(3 - BATCH_SEMAPHORE.availablePermits()));
|
||||
} catch (InterruptedException e) {
|
||||
logger.error("", e);
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
this.taskExecutor.submit(new Runnable()
|
||||
{
|
||||
public void run() {
|
||||
try {
|
||||
PersonBatchImportTask.this.imgPersonBatchService.handlerBatchPersonImport(batchRecordList, context, filePath);
|
||||
BatchImport batchImport = context.getBatchImport();
|
||||
BatchImport updateObj = new BatchImport();
|
||||
updateObj.setId(batchImport.getId());
|
||||
updateObj.setCurrentCount(Long.valueOf(context.getFailCount().get() + context.getSuccessCount().get()));
|
||||
PersonBatchImportTask.this.personBatchImportMapper.updateById(updateObj);
|
||||
} catch (Exception e) {
|
||||
PersonBatchImportTask.logger.error("", e);
|
||||
} finally {
|
||||
PersonBatchImportTask.BATCH_SEMAPHORE.release();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
private void cleanFiles(BatchImportContext context) {
|
||||
try {
|
||||
FileUtils.deleteDirectory(context.getUnzipFolder());
|
||||
this.personFileService.delete(Lists.newArrayList((Object[])new String[] { context.getBatchImport().getFilePath() }));
|
||||
FileUtils.deleteQuietly(new File(this.tempPath, context.getBatchImport().getBatchNo() + ".zip"));
|
||||
} catch (Exception ex) {
|
||||
logger.error("", ex);
|
||||
}
|
||||
}
|
||||
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
|
||||
BatchImport batchImportRecord = null;
|
||||
BatchImportContext batchImportContext = new BatchImportContext();
|
||||
String remark = null;
|
||||
try {
|
||||
logger.info("start handler import batch, query wait import task");
|
||||
batchImportRecord = getBatchImportQueryResult();
|
||||
batchImportContext.setBatchImport(batchImportRecord);
|
||||
if (batchImportRecord == null) {
|
||||
logger.info("start handler import batch, query wait import is empty");
|
||||
return;
|
||||
}
|
||||
logger.info("start handler import batch ,batchInfo:[{}]", JSONObject.toJSONString(batchImportRecord));
|
||||
updateBatchImportRecord(ImportStatus.PROCESSING, "", batchImportRecord.getId(), Long.valueOf(0L));
|
||||
long unzipStartTime = System.currentTimeMillis();
|
||||
unzipFile(batchImportContext);
|
||||
long unzipSpendTime = System.currentTimeMillis() - unzipStartTime;
|
||||
checkFileExists(batchImportContext);
|
||||
long startCalculateTime = System.currentTimeMillis();
|
||||
batchImportContext.setTotalCount(calculateRecordSize(batchImportContext));
|
||||
updateBatchImportRecord(Long.valueOf(batchImportContext.getTotalCount()), batchImportRecord.getId());
|
||||
long calculateSpendTime = System.currentTimeMillis() - startCalculateTime;
|
||||
ImgStorePersonProperties condition = new ImgStorePersonProperties();
|
||||
condition.setBusinessId(batchImportContext.getBatchImport().getBusinessId());
|
||||
List<ImgStorePersonProperties> personProperties = this.propertiesMapper.select(condition);
|
||||
logger.debug("personProperties:[{}]", JSONObject.toJSONString(personProperties));
|
||||
batchImportContext.setNameCodeMap(personProperties);
|
||||
process(batchImportContext);
|
||||
long cleanStartTime = System.currentTimeMillis();
|
||||
cleanFiles(batchImportContext);
|
||||
long cleanSpendTime = System.currentTimeMillis() - cleanStartTime;
|
||||
long processSpendTime = System.currentTimeMillis() - unzipStartTime;
|
||||
remark = String.format("导入完成,导入成功[%s]条,失败[%s]条,总耗时[%s],解压耗时[%s], 统计总数耗时[%s],图片复制耗时[%s],数据插入耗时[%s], 清理文件耗时[%s]", new Object[] { batchImportContext
|
||||
.getSuccessCount(), batchImportContext
|
||||
.getFailCount(),
|
||||
convertTime(processSpendTime),
|
||||
convertTime(unzipSpendTime),
|
||||
convertTime(calculateSpendTime),
|
||||
convertTime(batchImportContext.getImageCopyTime().get() / this.taskExecutor.getMaxPoolSize()),
|
||||
convertTime(batchImportContext.getInsertTime().get() / this.taskExecutor.getMaxPoolSize()),
|
||||
convertTime(cleanSpendTime) });
|
||||
BatchImport batchImport = this.personBatchImportMapper.selectById(batchImportRecord.getId());
|
||||
updateBatchImportRecord(ImportStatus.COMPLETE, remark, batchImportRecord.getId(), batchImport.getTotalCount());
|
||||
} catch (ImageStoreException ex) {
|
||||
if (batchImportRecord != null) {
|
||||
remark = ex.getMessage();
|
||||
updateBatchImportRecord(ImportStatus.EXCEPTION, remark, batchImportRecord.getId(), null);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
if (batchImportRecord != null) {
|
||||
updateBatchImportRecord(ImportStatus.EXCEPTION, "导入任务异常终止", batchImportRecord.getId(), null);
|
||||
}
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
private long calculateRecordSize(BatchImportContext context) {
|
||||
List<File> fileList = context.getExcelFiles();
|
||||
long totalCount = 0L;
|
||||
for (File file : fileList) {
|
||||
try(FileInputStream inputStream = new FileInputStream(file);
|
||||
Workbook workbook = WorkbookFactory.create(inputStream)) {
|
||||
Sheet sheet = workbook.getSheetAt(0);
|
||||
totalCount += (sheet.getPhysicalNumberOfRows() - 3);
|
||||
} catch (IOException|org.apache.poi.openxml4j.exceptions.InvalidFormatException e) {
|
||||
logger.warn("当前文件统计总记录数异常,文件名:{},文件路径:{}", file.getName(), file.getPath());
|
||||
}
|
||||
}
|
||||
return totalCount;
|
||||
}
|
||||
private void checkFileExists(BatchImportContext context) throws ImageStoreException {
|
||||
List<File> fileList = null;
|
||||
fileList = FileUtil.findExpecteFormatdFile(".+(\\.xls|\\.xlsx)$", context.getUnzipFolder(), null);
|
||||
if (fileList.isEmpty()) {
|
||||
throw new ImageStoreException("53014039", getMessage("53014039"));
|
||||
}
|
||||
context.setExcelFiles(fileList);
|
||||
}
|
||||
private void unzipFile(BatchImportContext context) throws ImageStoreException {
|
||||
File tempDir = new File(this.tempPath);
|
||||
if (!tempDir.exists()) {
|
||||
tempDir.mkdirs();
|
||||
}
|
||||
File file = new File(this.tempPath, context.getBatchImport().getBatchNo() + ".zip");
|
||||
logger.info("download to local. sourcePath:[{}], localPath:[{}]", context
|
||||
.getBatchImport().getFilePath(), file.getAbsolutePath());
|
||||
CloudwalkResult<InputStream> downloadResult = this.personFileService.download(context.getBatchImport().getFilePath());
|
||||
if (!downloadResult.isSuccess()) {
|
||||
throw new ImageStoreException(downloadResult.getCode(), downloadResult.getMessage());
|
||||
}
|
||||
try (InputStream inputStream = (InputStream)downloadResult.getData()) {
|
||||
FileUtils.copyInputStreamToFile(inputStream, file);
|
||||
} catch (Exception e) {
|
||||
logger.error("download file from storage component exception", e);
|
||||
throw new ImageStoreException("53014037", getMessage("53014037"));
|
||||
}
|
||||
if (!file.exists()) {
|
||||
throw new ImageStoreException("53014037", getMessage("53014037"));
|
||||
}
|
||||
try {
|
||||
File unzipFolder;
|
||||
if (checkUnzip()) {
|
||||
String unzipPath = PathUtils.joinPaths(new String[] { this.tempPath, "temp", CloudwalkDateUtils.getUUID() });
|
||||
unzipFolder = new File(unzipPath);
|
||||
unzipFolder.mkdirs();
|
||||
logger.info("解压前文件路径:{},解压后文件路径:{},编码方式:{}", new Object[] { file.getPath(), unzipFolder.getPath(), "utf-8" });
|
||||
String commandLine = String.format("unzip -q -O %s %s -d %s", new Object[] { "GBK", file.getPath(), unzipFolder.getPath() });
|
||||
ProcessBuilder processBuilder = new ProcessBuilder(new String[] { "/bin/sh", "-c", commandLine });
|
||||
processBuilder.redirectErrorStream(true);
|
||||
Process process = processBuilder.start();
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
logger.info(line);
|
||||
}
|
||||
int result = process.waitFor();
|
||||
if (result == 1 || result == 2) {
|
||||
logger.warn("---unzip 进程退出码:{}", Integer.valueOf(result));
|
||||
}
|
||||
if (result != 0 && result != 1 && result != 2) {
|
||||
throw new ImageStoreException("53014038", getMessage("53014038"));
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
unzipFolder = ZipUtil.unzipFile(file, "UTF-8");
|
||||
} catch (IllegalArgumentException e) {
|
||||
unzipFolder = ZipUtil.unzipFile(file, "GBK");
|
||||
}
|
||||
}
|
||||
context.setUnzipFolder(unzipFolder);
|
||||
} catch (Exception ex) {
|
||||
logger.error(ex.getMessage(), ex);
|
||||
throw new ImageStoreException("53014038", getMessage("53014038"));
|
||||
}
|
||||
}
|
||||
private boolean checkUnzip() {
|
||||
try {
|
||||
Process process = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", "unzip -help" });
|
||||
process.waitFor();
|
||||
InputStream inputStream = process.getInputStream();
|
||||
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
|
||||
byte[] buffer = new byte[1024];
|
||||
int length;
|
||||
while ((length = inputStream.read(buffer)) != -1) {
|
||||
byteArrayOutputStream.write(buffer, 0, length);
|
||||
}
|
||||
String outputResult = byteArrayOutputStream.toString("UTF-8");
|
||||
try {
|
||||
inputStream.close();
|
||||
byteArrayOutputStream.close();
|
||||
} catch (IOException ignored) {
|
||||
logger.error("exception:{}", ignored.getMessage());
|
||||
}
|
||||
if (outputResult.contains("-O")) {
|
||||
logger.info("支持unzip解压,使用unzip进行解压");
|
||||
return true;
|
||||
}
|
||||
logger.warn("不支持unzip解压,请升级至最新unzip");
|
||||
}
|
||||
catch (IOException|InterruptedException e) {
|
||||
logger.error(e.getMessage());
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
private synchronized BatchImport getBatchImportQueryResult() {
|
||||
Long fromTime = Long.valueOf(System.currentTimeMillis() - 86400000L);
|
||||
List<BatchImport> query = this.personBatchImportMapper.selectImportTask(fromTime);
|
||||
BatchImport pendingImport = null;
|
||||
if (CollectionUtils.isNotEmpty(query)) {
|
||||
for (BatchImport q : query) {
|
||||
if (ImportStatus.from(q.getStatus()) == ImportStatus.NONE && pendingImport == null) {
|
||||
pendingImport = q;
|
||||
continue;
|
||||
}
|
||||
if (ImportStatus.from(q.getStatus()) == ImportStatus.PROCESSING) {
|
||||
q.setStatus(ImportStatus.EXCEPTION.value());
|
||||
q.setRemark(getMessage("53014036"));
|
||||
this.personBatchImportMapper.updateById(q);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pendingImport == null) {
|
||||
return null;
|
||||
}
|
||||
return (BatchImport)BeanCopyUtils.copyProperties(pendingImport, BatchImport.class);
|
||||
}
|
||||
private static String convertTime(long executeTime) {
|
||||
long ms = 1000L;
|
||||
long minute = 60L * ms;
|
||||
long hour = 60L * minute;
|
||||
long day = 24L * hour;
|
||||
long days = executeTime / day;
|
||||
long hours = executeTime % day / hour;
|
||||
long minutes = executeTime % hour / minute;
|
||||
long seconds = executeTime % minute / ms;
|
||||
long milliSeconds = executeTime % ms;
|
||||
StringBuilder builder = new StringBuilder();
|
||||
if (days != 0L) {
|
||||
builder.append(days).append("天");
|
||||
}
|
||||
if (hours != 0L) {
|
||||
builder.append(hours).append("小时");
|
||||
}
|
||||
if (minutes != 0L) {
|
||||
builder.append(minutes).append("分");
|
||||
}
|
||||
if (seconds != 0L) {
|
||||
builder.append(seconds).append("秒");
|
||||
}
|
||||
if (builder.length() < 1) {
|
||||
builder.append(milliSeconds).append("毫秒");
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
private void updateBatchImportRecord(ImportStatus status, String remark, String id, Long currentCount) {
|
||||
try {
|
||||
logger.info("设置当前任务[{}]状态为[{}]", id, status);
|
||||
BatchImport bi = new BatchImport();
|
||||
bi.setId(id);
|
||||
bi.setStatus(status.value());
|
||||
bi.setCurrentCount(currentCount);
|
||||
if (status == ImportStatus.COMPLETE || status == ImportStatus.EXCEPTION) {
|
||||
bi.setFinishTime(Long.valueOf(System.currentTimeMillis()));
|
||||
}
|
||||
bi.setRemark(StringUtils.left(remark, 255));
|
||||
this.personBatchImportMapper.updateById(bi);
|
||||
} catch (Exception ex) {
|
||||
logger.error("", ex);
|
||||
}
|
||||
}
|
||||
private void updateBatchImportRecord(Long totalCount, String id) {
|
||||
try {
|
||||
BatchImport bi = new BatchImport();
|
||||
bi.setId(id);
|
||||
bi.setTotalCount(totalCount);
|
||||
this.personBatchImportMapper.updateById(bi);
|
||||
} catch (Exception ex) {
|
||||
logger.error("", ex);
|
||||
}
|
||||
}
|
||||
private String getMessage(String code) {
|
||||
try {
|
||||
return this.messageSource.getMessage(code, null, LocaleContextHolder.getLocale());
|
||||
} catch (Exception ex) {
|
||||
logger.warn("", ex);
|
||||
return code;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/schedule/PersonBatchImportTask.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+19
-18
@@ -1,5 +1,5 @@
|
||||
package cn.cloudwalk.service.organization.schedule;
|
||||
// 业务服务
|
||||
// 调度服务
|
||||
import cn.cloudwalk.service.organization.service.CpImageStorePersonValidateManager;
|
||||
import cn.cloudwalk.task.sdk.starter.config.context.ContextAwareHolder;
|
||||
import org.quartz.Job;
|
||||
@@ -9,22 +9,23 @@ import org.quartz.Trigger;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
public class PersonValidateTask
|
||||
implements Job {
|
||||
private static final Logger log = LoggerFactory.getLogger(PersonValidateTask.class);
|
||||
@Autowired
|
||||
private CpImageStorePersonValidateManager cpImageStorePersonValidateManager;
|
||||
|
||||
public PersonValidateTask() {
|
||||
ContextAwareHolder.autowireBean((Object)this);
|
||||
}
|
||||
|
||||
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
|
||||
Trigger trigger = jobExecutionContext.getTrigger();
|
||||
String dataJson = trigger.getJobDataMap().getString("VALIDATE_TRIGGER_KEY");
|
||||
log.info("PersonValidateTask time:{},data:{}", (Object)trigger.getStartTime(), (Object)dataJson);
|
||||
this.cpImageStorePersonValidateManager.syncDataToGroup(dataJson);
|
||||
}
|
||||
public class PersonValidateTask implements Job {
|
||||
private static final Logger log = LoggerFactory.getLogger(PersonValidateTask.class);
|
||||
public PersonValidateTask() {
|
||||
ContextAwareHolder.autowireBean(this);
|
||||
}
|
||||
@Autowired
|
||||
private CpImageStorePersonValidateManager cpImageStorePersonValidateManager;
|
||||
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
|
||||
Trigger trigger = jobExecutionContext.getTrigger();
|
||||
String dataJson = trigger.getJobDataMap().getString("VALIDATE_TRIGGER_KEY");
|
||||
log.info("PersonValidateTask time:{},data:{}", trigger.getStartTime(), dataJson);
|
||||
this.cpImageStorePersonValidateManager.syncDataToGroup(dataJson);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/schedule/PersonValidateTask.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+80
-85
@@ -1,9 +1,6 @@
|
||||
package cn.cloudwalk.service.organization.schedule;
|
||||
// 业务服务
|
||||
// 调度服务
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.service.organization.schedule.DelayPersonValidateTask;
|
||||
import cn.cloudwalk.service.organization.schedule.PersonBatchImportTask;
|
||||
import cn.cloudwalk.service.organization.schedule.PersonValidateTask;
|
||||
import cn.cloudwalk.task.data.dto.param.TaskModifyParam;
|
||||
import cn.cloudwalk.task.sdk.client.TaskExecClient;
|
||||
import cn.cloudwalk.task.sdk.dto.JobDetailResult;
|
||||
@@ -21,87 +18,85 @@ import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class ScheduleTaskInitialize
|
||||
implements CommandLineRunner {
|
||||
private static final Logger log = LoggerFactory.getLogger(ScheduleTaskInitialize.class);
|
||||
@Value(value="${job.person.batch-import.cron:0 0/1 * * * ?}")
|
||||
private String batchPersonImportJobCron;
|
||||
@Value(value="${group-person.syn.config.delay-handle-validate.cron:0 0/10 * * * ?}")
|
||||
private String delayHandleValidateCron;
|
||||
@Autowired
|
||||
private QuartzTaskProperties quartzTaskProperties;
|
||||
private static final String BATCH_PERSON_IMPORT_JOB = "QZ_PERSON_BATCH_IMPORT_JOB";
|
||||
@Autowired
|
||||
private TaskService taskService;
|
||||
@Autowired
|
||||
private TaskExecClient taskExecClient;
|
||||
|
||||
public void run(String ... strings) throws Exception {
|
||||
this.initBatchPersonImportTask();
|
||||
this.initPersonValidateTask();
|
||||
this.initDelayPersonValidateTask();
|
||||
}
|
||||
|
||||
private void initBatchPersonImportTask() {
|
||||
TaskModifyParam taskModifyParam = new TaskModifyParam();
|
||||
taskModifyParam.setJobDescription("解析人员管理页面上传的批量导入文件,导入人员数据");
|
||||
taskModifyParam.setJobName("通用人员人员批量导入定时任务");
|
||||
taskModifyParam.setJobGroup(BATCH_PERSON_IMPORT_JOB);
|
||||
taskModifyParam.setClazz(PersonBatchImportTask.class);
|
||||
taskModifyParam.setRetry(Boolean.valueOf(false));
|
||||
taskModifyParam.setPriority(Integer.valueOf(1));
|
||||
taskModifyParam.setStartTime(Long.valueOf(System.currentTimeMillis()));
|
||||
taskModifyParam.setExpression(this.batchPersonImportJobCron);
|
||||
taskModifyParam.setNeedListener(Boolean.valueOf(true));
|
||||
this.taskService.addCronJob(taskModifyParam);
|
||||
}
|
||||
|
||||
private void initPersonValidateTask() {
|
||||
try {
|
||||
Scheduler scheduler = this.taskExecClient.getScheduler(this.quartzTaskProperties.getSchedulerName());
|
||||
JobKey jobKey = new JobKey("PERSON_VALIDATE_JOB_NAME", "QZ_PERSON_VALIDATE_JOB");
|
||||
boolean exist = scheduler.checkExists(jobKey);
|
||||
if (exist) {
|
||||
log.info("{},{}:已存在", (Object)"PERSON_VALIDATE_JOB_NAME", (Object)"QZ_PERSON_VALIDATE_JOB");
|
||||
return;
|
||||
}
|
||||
JobDetail jobDetail = JobBuilder.newJob(PersonValidateTask.class).withIdentity("PERSON_VALIDATE_JOB_NAME", "QZ_PERSON_VALIDATE_JOB").storeDurably().withDescription("人员有效期同步下发任务").build();
|
||||
scheduler.addJob(jobDetail, false);
|
||||
}
|
||||
catch (SchedulerException e) {
|
||||
log.error("创建job失败:{}", (Object)e.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void initDelayPersonValidateTask() {
|
||||
TaskModifyParam taskModifyParam = new TaskModifyParam();
|
||||
taskModifyParam.setJobDescription("延迟处理人员有效期任务");
|
||||
taskModifyParam.setJobName("延迟处理人员有效期任务");
|
||||
taskModifyParam.setJobGroup("CP_DELAY_HANDLE_VALIDATE");
|
||||
taskModifyParam.setClazz(DelayPersonValidateTask.class);
|
||||
taskModifyParam.setRetry(Boolean.valueOf(false));
|
||||
taskModifyParam.setPriority(Integer.valueOf(1));
|
||||
taskModifyParam.setStartTime(Long.valueOf(System.currentTimeMillis()));
|
||||
taskModifyParam.setExpression(this.delayHandleValidateCron);
|
||||
taskModifyParam.setNeedListener(Boolean.valueOf(true));
|
||||
CloudwalkResult job = this.taskService.findJob(taskModifyParam);
|
||||
log.debug("initDelayPersonValidateTask job:[{}]", (Object)JSON.toJSONString((Object)job));
|
||||
if (job.isSuccess()) {
|
||||
JobDetailResult jobDetailResult = (JobDetailResult)job.getData();
|
||||
log.info("initDelayPersonValidateTask job success:[{}]", (Object)JSON.toJSONString((Object)jobDetailResult));
|
||||
if (null != jobDetailResult) {
|
||||
if (taskModifyParam.getExpression().equals(jobDetailResult.getExpression())) {
|
||||
return;
|
||||
}
|
||||
log.debug("initDelayPersonValidateTask job modifyJobTime");
|
||||
this.taskService.modifyJobTime(taskModifyParam);
|
||||
return;
|
||||
}
|
||||
}
|
||||
log.debug("initDelayPersonValidateTask job addCronJob");
|
||||
this.taskService.addCronJob(taskModifyParam);
|
||||
}
|
||||
public class ScheduleTaskInitialize implements CommandLineRunner {
|
||||
private static final Logger log = LoggerFactory.getLogger(ScheduleTaskInitialize.class);
|
||||
@Value("${job.person.batch-import.cron:0 0/1 * * * ?}")
|
||||
private String batchPersonImportJobCron;
|
||||
@Value("${group-person.syn.config.delay-handle-validate.cron:0 0/10 * * * ?}")
|
||||
private String delayHandleValidateCron;
|
||||
@Autowired
|
||||
private QuartzTaskProperties quartzTaskProperties;
|
||||
private static final String BATCH_PERSON_IMPORT_JOB = "QZ_PERSON_BATCH_IMPORT_JOB";
|
||||
@Autowired
|
||||
private TaskService taskService;
|
||||
@Autowired
|
||||
private TaskExecClient taskExecClient;
|
||||
public void run(String... strings) throws Exception {
|
||||
initBatchPersonImportTask();
|
||||
initPersonValidateTask();
|
||||
initDelayPersonValidateTask();
|
||||
}
|
||||
private void initBatchPersonImportTask() {
|
||||
TaskModifyParam taskModifyParam = new TaskModifyParam();
|
||||
taskModifyParam.setJobDescription("解析人员管理页面上传的批量导入文件,导入人员数据");
|
||||
taskModifyParam.setJobName("通用人员人员批量导入定时任务");
|
||||
taskModifyParam.setJobGroup("QZ_PERSON_BATCH_IMPORT_JOB");
|
||||
taskModifyParam.setClazz(PersonBatchImportTask.class);
|
||||
taskModifyParam.setRetry(Boolean.valueOf(false));
|
||||
taskModifyParam.setPriority(Integer.valueOf(1));
|
||||
taskModifyParam.setStartTime(Long.valueOf(System.currentTimeMillis()));
|
||||
taskModifyParam.setExpression(this.batchPersonImportJobCron);
|
||||
taskModifyParam.setNeedListener(Boolean.valueOf(true));
|
||||
this.taskService.addCronJob(taskModifyParam);
|
||||
}
|
||||
private void initPersonValidateTask() {
|
||||
try {
|
||||
Scheduler scheduler = this.taskExecClient.getScheduler(this.quartzTaskProperties.getSchedulerName());
|
||||
JobKey jobKey = new JobKey("PERSON_VALIDATE_JOB_NAME", "QZ_PERSON_VALIDATE_JOB");
|
||||
boolean exist = scheduler.checkExists(jobKey);
|
||||
if (exist) {
|
||||
log.info("{},{}:已存在", "PERSON_VALIDATE_JOB_NAME", "QZ_PERSON_VALIDATE_JOB");
|
||||
return;
|
||||
}
|
||||
JobDetail jobDetail = JobBuilder.newJob(PersonValidateTask.class).withIdentity("PERSON_VALIDATE_JOB_NAME", "QZ_PERSON_VALIDATE_JOB").storeDurably().withDescription("人员有效期同步下发任务").build();
|
||||
scheduler.addJob(jobDetail, false);
|
||||
} catch (SchedulerException e) {
|
||||
log.error("创建job失败:{}", e.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
private void initDelayPersonValidateTask() {
|
||||
TaskModifyParam taskModifyParam = new TaskModifyParam();
|
||||
taskModifyParam.setJobDescription("延迟处理人员有效期任务");
|
||||
taskModifyParam.setJobName("延迟处理人员有效期任务");
|
||||
taskModifyParam.setJobGroup("CP_DELAY_HANDLE_VALIDATE");
|
||||
taskModifyParam.setClazz(DelayPersonValidateTask.class);
|
||||
taskModifyParam.setRetry(Boolean.valueOf(false));
|
||||
taskModifyParam.setPriority(Integer.valueOf(1));
|
||||
taskModifyParam.setStartTime(Long.valueOf(System.currentTimeMillis()));
|
||||
taskModifyParam.setExpression(this.delayHandleValidateCron);
|
||||
taskModifyParam.setNeedListener(Boolean.valueOf(true));
|
||||
CloudwalkResult<JobDetailResult> job = this.taskService.findJob(taskModifyParam);
|
||||
log.debug("initDelayPersonValidateTask job:[{}]", JSON.toJSONString(job));
|
||||
if (job.isSuccess()) {
|
||||
JobDetailResult jobDetailResult = (JobDetailResult)job.getData();
|
||||
log.info("initDelayPersonValidateTask job success:[{}]", JSON.toJSONString(jobDetailResult));
|
||||
if (null != jobDetailResult) {
|
||||
if (taskModifyParam.getExpression().equals(jobDetailResult.getExpression())) {
|
||||
return;
|
||||
}
|
||||
log.debug("initDelayPersonValidateTask job modifyJobTime");
|
||||
this.taskService.modifyJobTime(taskModifyParam);
|
||||
return;
|
||||
}
|
||||
}
|
||||
log.debug("initDelayPersonValidateTask job addCronJob");
|
||||
this.taskService.addCronJob(taskModifyParam);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/schedule/ScheduleTaskInitialize.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+619
-563
File diff suppressed because it is too large
Load Diff
+403
@@ -0,0 +1,403 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.common.enums.AreaTypeCodeEnum;
|
||||
import cn.cloudwalk.client.organization.param.AddAreaTypeParam;
|
||||
import cn.cloudwalk.client.organization.param.AreaTypePropertyParam;
|
||||
import cn.cloudwalk.client.organization.param.DelAreaTypeParam;
|
||||
import cn.cloudwalk.client.organization.param.EditAreaTypeParam;
|
||||
import cn.cloudwalk.client.organization.param.QueryAreaTypeParam;
|
||||
import cn.cloudwalk.client.organization.result.AreaTypeListResult;
|
||||
import cn.cloudwalk.client.organization.result.AreaTypeResult;
|
||||
import cn.cloudwalk.client.organization.service.AreaTypeService;
|
||||
import cn.cloudwalk.cloud.annotation.CloudwalkParamsValidate;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkCallContext;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
import cn.cloudwalk.cloud.page.CloudwalkPageAble;
|
||||
import cn.cloudwalk.cloud.page.CloudwalkPageInfo;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.cloud.utils.BeanCopyUtils;
|
||||
import cn.cloudwalk.cloud.utils.CloudwalkDateUtils;
|
||||
import cn.cloudwalk.data.organization.dto.AreaTypeQueryDTO;
|
||||
import cn.cloudwalk.data.organization.dto.GetsAreaDTO;
|
||||
import cn.cloudwalk.data.organization.entity.Area;
|
||||
import cn.cloudwalk.data.organization.entity.AreaType;
|
||||
import cn.cloudwalk.data.organization.entity.AreaTypeProperties;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStoreAreaMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStoreAreaTypeMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStoreAreaTypePropertiesMapper;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import com.github.pagehelper.Page;
|
||||
import com.github.pagehelper.PageHelper;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import javax.annotation.Resource;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
@Primary
|
||||
@Service
|
||||
public class AreaTypeServiceImpl
|
||||
extends AbstractImagStoreService
|
||||
implements AreaTypeService
|
||||
{
|
||||
@Resource
|
||||
private ImgStoreAreaMapper areaMapper;
|
||||
@Resource
|
||||
private ImgStoreAreaTypeMapper areaTypeMapper;
|
||||
@Resource
|
||||
private ImgStoreAreaTypePropertiesMapper areaTypePropertiesMapper;
|
||||
private static final String EXT = "ext";
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<String> add(AddAreaTypeParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId;
|
||||
if (StringUtils.isEmpty(param.getBusinessId())) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
} else {
|
||||
businessId = param.getBusinessId();
|
||||
}
|
||||
if (businessId.equals("cloudwalk")) {
|
||||
throw new ServiceException("53003818", getMessage("53003818"));
|
||||
}
|
||||
Set<String> nameMap = new HashSet<>();
|
||||
List<AreaTypePropertyParam> properties = param.getProperties();
|
||||
for (AreaTypePropertyParam propertyParam : properties) {
|
||||
nameMap.add(propertyParam.getName());
|
||||
}
|
||||
if (nameMap.size() < properties.size()) {
|
||||
throw new ServiceException("53003805", getMessage("53003805"));
|
||||
}
|
||||
AreaTypeQueryDTO areaTypeQueryDTO = (AreaTypeQueryDTO)BeanCopyUtils.copyProperties(param, AreaTypeQueryDTO.class);
|
||||
areaTypeQueryDTO.setStatus(Integer.valueOf(0));
|
||||
areaTypeQueryDTO.setBusinessId(businessId);
|
||||
List<AreaType> select = this.areaTypeMapper.selectByCondition(areaTypeQueryDTO);
|
||||
if (!CollectionUtils.isEmpty(select)) {
|
||||
throw new ServiceException("53004803", getMessage("53004803"));
|
||||
}
|
||||
AreaType areaType = (AreaType)BeanCopyUtils.copyProperties(param, AreaType.class);
|
||||
String uuid = CloudwalkDateUtils.getUUID();
|
||||
areaType.setId(uuid);
|
||||
areaType.setBusinessId(businessId);
|
||||
areaType.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
areaType.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
areaType.setCreateUserId(context.getUser().getCaller());
|
||||
areaType.setLastUpdateUserId(context.getUser().getCaller());
|
||||
this.areaTypeMapper.insertSelective(areaType);
|
||||
int index = 1;
|
||||
if (!CollectionUtils.isEmpty(properties))
|
||||
{
|
||||
for (AreaTypePropertyParam propertyParam : properties) {
|
||||
AreaTypeProperties property = (AreaTypeProperties)BeanCopyUtils.copyProperties(propertyParam, AreaTypeProperties.class);
|
||||
property.setId(CloudwalkDateUtils.getUUID());
|
||||
property.setBusinessId(businessId);
|
||||
property.setAreaTypeId(uuid);
|
||||
property.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
property.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
property.setCreateUserId(context.getUser().getCaller());
|
||||
property.setLastUpdateUserId(context.getUser().getCaller());
|
||||
property.setCode("ext" + index++);
|
||||
this.areaTypePropertiesMapper.insertSelective(property);
|
||||
}
|
||||
}
|
||||
return CloudwalkResult.success(uuid);
|
||||
}
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> edit(EditAreaTypeParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId;
|
||||
if (StringUtils.isEmpty(param.getBusinessId())) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
} else {
|
||||
businessId = param.getBusinessId();
|
||||
}
|
||||
if (businessId.equals("cloudwalk")) {
|
||||
throw new ServiceException("53003818", getMessage("53003818"));
|
||||
}
|
||||
Set<String> nameMap = new HashSet<>();
|
||||
List<AreaTypePropertyParam> properties = param.getProperties();
|
||||
for (AreaTypePropertyParam propertyParam : properties) {
|
||||
nameMap.add(propertyParam.getName());
|
||||
}
|
||||
if (nameMap.size() < properties.size()) {
|
||||
throw new ServiceException("53003805", getMessage("53003805"));
|
||||
}
|
||||
AreaTypeQueryDTO areaTypeQuery = new AreaTypeQueryDTO();
|
||||
areaTypeQuery.setName(param.getName());
|
||||
areaTypeQuery.setStatus(Integer.valueOf(0));
|
||||
areaTypeQuery.setBusinessId(businessId);
|
||||
List<AreaType> select = this.areaTypeMapper.selectByCondition(areaTypeQuery);
|
||||
if (!CollectionUtils.isEmpty(select)) {
|
||||
for (AreaType type : select) {
|
||||
if (!type.getId().equals(param.getId())) {
|
||||
throw new ServiceException("53004803", getMessage("53004803"));
|
||||
}
|
||||
}
|
||||
}
|
||||
boolean hasOrganization = false;
|
||||
boolean hasChildren = false;
|
||||
GetsAreaDTO areaDTO = new GetsAreaDTO();
|
||||
areaDTO.setTypeId(param.getId());
|
||||
areaDTO.setIsDel(Short.valueOf((short)0));
|
||||
List<Area> areas = this.areaMapper.gets(areaDTO);
|
||||
if (!CollectionUtils.isEmpty(areas)) {
|
||||
hasOrganization = true;
|
||||
List<String> parentIds = new ArrayList<>();
|
||||
for (Area area : areas) {
|
||||
parentIds.add(area.getId());
|
||||
}
|
||||
areaDTO = new GetsAreaDTO();
|
||||
areaDTO.setIsDel(Short.valueOf((short)0));
|
||||
areaDTO.setParentIds(parentIds);
|
||||
List<Area> childrens = this.areaMapper.gets(areaDTO);
|
||||
if (childrens != null && childrens.size() > 0) {
|
||||
hasChildren = true;
|
||||
}
|
||||
}
|
||||
if (param.getHasLowerLevel().intValue() == 0 && hasChildren) {
|
||||
throw new ServiceException("53004813", getMessage("53004813"));
|
||||
}
|
||||
AreaType areaType = (AreaType)BeanCopyUtils.copyProperties(areaTypeQuery, AreaType.class);
|
||||
areaType.setId(param.getId());
|
||||
areaType.setHasLowerLevel(param.getHasLowerLevel());
|
||||
areaType.setLastUpdateUserId(context.getUser().getCaller());
|
||||
areaType.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.areaTypeMapper.updateByPrimaryKeySelective(areaType);
|
||||
AreaTypeProperties proQuery = new AreaTypeProperties();
|
||||
proQuery.setAreaTypeId(param.getId());
|
||||
List<AreaTypeProperties> typePropertiesDB = this.areaTypePropertiesMapper.select(proQuery);
|
||||
if (properties != null)
|
||||
{
|
||||
if (CollectionUtils.isEmpty(typePropertiesDB)) {
|
||||
int index = 1;
|
||||
for (AreaTypePropertyParam propertyParam : properties) {
|
||||
AreaTypeProperties property = (AreaTypeProperties)BeanCopyUtils.copyProperties(propertyParam, AreaTypeProperties.class);
|
||||
property.setId(CloudwalkDateUtils.getUUID());
|
||||
property.setBusinessId(businessId);
|
||||
property.setAreaTypeId(param.getId());
|
||||
property.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
property.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
property.setCreateUserId(context.getUser().getCaller());
|
||||
property.setLastUpdateUserId(context.getUser().getCaller());
|
||||
property.setCode("ext" + index++);
|
||||
property.setStatus(Integer.valueOf(0));
|
||||
this.areaTypePropertiesMapper.insertSelective(property);
|
||||
}
|
||||
} else {
|
||||
Map<String, AreaTypeProperties> DBMap = new HashMap<>();
|
||||
Set<String> codeSet = new HashSet<>();
|
||||
for (AreaTypeProperties areaTypeProperties : typePropertiesDB) {
|
||||
String code = areaTypeProperties.getCode();
|
||||
codeSet.add(code);
|
||||
DBMap.put(areaTypeProperties.getId(), areaTypeProperties);
|
||||
}
|
||||
List<AreaTypeProperties> newList = BeanCopyUtils.copy(properties, AreaTypeProperties.class);
|
||||
List<AreaTypeProperties> newListCopy = new ArrayList<>(newList);
|
||||
newListCopy.retainAll(typePropertiesDB);
|
||||
if (!CollectionUtils.isEmpty(newListCopy)) {
|
||||
for (AreaTypeProperties areaTypeProperties : newListCopy) {
|
||||
if (hasOrganization && areaTypeProperties.getHasRequired().intValue() == 1) {
|
||||
Integer hasRequired = ((AreaTypeProperties)DBMap.get(areaTypeProperties.getId())).getHasRequired();
|
||||
if (hasRequired != null && hasRequired.intValue() == 0) {
|
||||
throw new ServiceException("53004815", getMessage("53004815"));
|
||||
}
|
||||
}
|
||||
areaTypeProperties.setStatus(Integer.valueOf(0));
|
||||
areaTypeProperties.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
areaTypeProperties.setLastUpdateUserId(context.getUser().getCaller());
|
||||
this.areaTypePropertiesMapper.updateByPrimaryKeySelective(areaTypeProperties);
|
||||
}
|
||||
}
|
||||
typePropertiesDB.removeAll(newListCopy);
|
||||
if (!CollectionUtils.isEmpty(typePropertiesDB)) {
|
||||
for (AreaTypeProperties areaTypeProperties : typePropertiesDB) {
|
||||
areaTypeProperties.setStatus(Integer.valueOf(1));
|
||||
areaTypeProperties.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
areaTypeProperties.setLastUpdateUserId(context.getUser().getCaller());
|
||||
this.areaTypePropertiesMapper.updateByPrimaryKeySelective(areaTypeProperties);
|
||||
codeSet.remove(areaTypeProperties.getCode());
|
||||
String typeId = param.getId();
|
||||
String codeProperty = areaTypeProperties.getCode();
|
||||
this.areaMapper.removePropertyByTypeIdAndCode(typeId, codeProperty);
|
||||
}
|
||||
}
|
||||
newList.removeAll(newListCopy);
|
||||
if (!CollectionUtils.isEmpty(newList)) {
|
||||
for (AreaTypeProperties areaTypeProperties : newList) {
|
||||
if (areaTypeProperties.getHasRequired().intValue() == 1 && hasOrganization) {
|
||||
throw new ServiceException("53003814", getMessage("53003814"));
|
||||
}
|
||||
areaTypeProperties.setId(CloudwalkDateUtils.getUUID());
|
||||
areaTypeProperties.setBusinessId(businessId);
|
||||
areaTypeProperties.setAreaTypeId(param.getId());
|
||||
areaTypeProperties.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
areaTypeProperties.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
areaTypeProperties.setCreateUserId(context.getUser().getCaller());
|
||||
areaTypeProperties.setLastUpdateUserId(context.getUser().getCaller());
|
||||
areaTypeProperties.setCode(getCode(codeSet));
|
||||
areaTypeProperties.setStatus(Integer.valueOf(0));
|
||||
this.areaTypePropertiesMapper.insertSelective(areaTypeProperties);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
public CloudwalkResult<Boolean> delete(DelAreaTypeParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
List<String> ids = param.getIds();
|
||||
if (!CollectionUtils.isEmpty(ids)) {
|
||||
for (String typeId : ids) {
|
||||
GetsAreaDTO getsAreaDTO = new GetsAreaDTO();
|
||||
getsAreaDTO.setTypeId(typeId);
|
||||
getsAreaDTO.setIsDel(Short.valueOf((short)0));
|
||||
List<Area> gets = this.areaMapper.gets(getsAreaDTO);
|
||||
if (!CollectionUtils.isEmpty(gets)) {
|
||||
throw new ServiceException("53004854", getMessage("53004854"));
|
||||
}
|
||||
}
|
||||
for (String id : ids) {
|
||||
AreaType areaType = this.areaTypeMapper.selectByPrimaryKey(id);
|
||||
if (areaType == null) {
|
||||
throw new ServiceException("53015104", getMessage("53015104"));
|
||||
}
|
||||
areaType.setId(id);
|
||||
AreaType areaTypeDB = this.areaTypeMapper.selectByPrimaryKey(id);
|
||||
if ("cloudwalk".equals(areaTypeDB.getBusinessId())) {
|
||||
throw new ServiceException("53003818", getMessage("53003818"));
|
||||
}
|
||||
areaType.setStatus(Integer.valueOf(1));
|
||||
areaType.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
areaType.setLastUpdateUserId(context.getUser().getCaller());
|
||||
this.areaTypeMapper.updateByPrimaryKeySelective(areaType);
|
||||
AreaTypeProperties record = new AreaTypeProperties();
|
||||
record.setAreaTypeId(id);
|
||||
record.setStatus(Integer.valueOf(1));
|
||||
record.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
record.setLastUpdateUserId(context.getUser().getCaller());
|
||||
this.areaTypePropertiesMapper.updateByTypeKey(record);
|
||||
}
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
public CloudwalkResult<CloudwalkPageAble<AreaTypeListResult>> page(QueryAreaTypeParam param, CloudwalkPageInfo page, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId = context.getCompany().getCompanyId();
|
||||
List<AreaTypeListResult> results = new ArrayList<>();
|
||||
AreaTypeQueryDTO record = (AreaTypeQueryDTO)BeanCopyUtils.copyProperties(param, AreaTypeQueryDTO.class);
|
||||
record.setBusinessId(businessId);
|
||||
record.setStatus(Integer.valueOf(0));
|
||||
try {
|
||||
PageHelper.startPage(page.getCurrentPage(), page.getPageSize());
|
||||
Page<AreaType> gets = (Page<AreaType>)this.areaTypeMapper.select(record);
|
||||
List<AreaType> result = gets.getResult();
|
||||
Map<String, Integer> deletableMap = AreaTypeCodeEnum.deletable(AreaTypeCodeEnum.PARK.getGroup());
|
||||
for (AreaType areaType : result) {
|
||||
AreaTypeListResult typeResult = (AreaTypeListResult)BeanCopyUtils.copyProperties(areaType, AreaTypeListResult.class);
|
||||
typeResult.setDeletable(deletableMap.getOrDefault(areaType.getCode(), Integer.valueOf(1)));
|
||||
AreaTypeProperties recordQuery = new AreaTypeProperties();
|
||||
recordQuery.setStatus(Integer.valueOf(0));
|
||||
recordQuery.setAreaTypeId(areaType.getId());
|
||||
List<AreaTypeProperties> propertiesList = this.areaTypePropertiesMapper.select(recordQuery);
|
||||
if (!CollectionUtils.isEmpty(propertiesList)) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (AreaTypeProperties areaTypeProperties : propertiesList) {
|
||||
builder.append("," + areaTypeProperties.getName());
|
||||
}
|
||||
typeResult.setProperties(builder.substring(1));
|
||||
} else {
|
||||
typeResult.setProperties("");
|
||||
}
|
||||
results.add(typeResult);
|
||||
}
|
||||
CloudwalkPageAble<AreaTypeListResult> pageAble = new CloudwalkPageAble(results, page, gets.getTotal());
|
||||
return CloudwalkResult.success(pageAble);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("分页查询区域类型信息失败,原因:", e);
|
||||
throw new ServiceException("53004804", getMessage("53004804"));
|
||||
}
|
||||
}
|
||||
public CloudwalkResult<List<AreaTypeListResult>> getList(QueryAreaTypeParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId;
|
||||
if (StringUtils.isEmpty(param.getBusinessId())) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
} else {
|
||||
businessId = param.getBusinessId();
|
||||
}
|
||||
List<AreaTypeListResult> results = new ArrayList<>();
|
||||
AreaTypeQueryDTO record = (AreaTypeQueryDTO)BeanCopyUtils.copyProperties(param, AreaTypeQueryDTO.class);
|
||||
record.setBusinessId(businessId);
|
||||
record.setStatus(Integer.valueOf(0));
|
||||
List<AreaType> result = this.areaTypeMapper.select(record);
|
||||
for (AreaType areaType : result) {
|
||||
AreaTypeListResult typeResult = (AreaTypeListResult)BeanCopyUtils.copyProperties(areaType, AreaTypeListResult.class);
|
||||
AreaTypeProperties recordQuery = new AreaTypeProperties();
|
||||
recordQuery.setStatus(Integer.valueOf(0));
|
||||
recordQuery.setAreaTypeId(areaType.getId());
|
||||
List<AreaTypeProperties> propertiesList = this.areaTypePropertiesMapper.select(recordQuery);
|
||||
if (!CollectionUtils.isEmpty(propertiesList)) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (AreaTypeProperties areaTypeProperties : propertiesList) {
|
||||
builder.append("," + areaTypeProperties.getName());
|
||||
}
|
||||
typeResult.setProperties(builder.substring(1));
|
||||
} else {
|
||||
typeResult.setProperties("");
|
||||
}
|
||||
results.add(typeResult);
|
||||
}
|
||||
record = new AreaTypeQueryDTO();
|
||||
record.setBusinessId("cloudwalk");
|
||||
record.setStatus(Integer.valueOf(0));
|
||||
record.setHasDefault(Integer.valueOf(1));
|
||||
List<AreaType> areaTypes = this.areaTypeMapper.select(record);
|
||||
if (!CollectionUtils.isEmpty(areaTypes)) {
|
||||
for (AreaType areaType : areaTypes) {
|
||||
AreaTypeListResult typeResult = (AreaTypeListResult)BeanCopyUtils.copyProperties(areaType, AreaTypeListResult.class);
|
||||
AreaTypeProperties recordQuery = new AreaTypeProperties();
|
||||
recordQuery.setStatus(Integer.valueOf(0));
|
||||
recordQuery.setAreaTypeId(areaType.getId());
|
||||
List<AreaTypeProperties> propertiesList = this.areaTypePropertiesMapper.select(recordQuery);
|
||||
if (!CollectionUtils.isEmpty(propertiesList)) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (AreaTypeProperties areaTypeProperties : propertiesList) {
|
||||
builder.append("," + areaTypeProperties.getName());
|
||||
}
|
||||
typeResult.setProperties(builder.substring(1));
|
||||
}
|
||||
results.add(typeResult);
|
||||
}
|
||||
}
|
||||
return CloudwalkResult.success(results);
|
||||
}
|
||||
public CloudwalkResult<AreaTypeResult> detail(QueryAreaTypeParam param, CloudwalkCallContext cloudwalkContext) throws ServiceException {
|
||||
if (StringUtils.isEmpty(param.getId())) {
|
||||
throw new ServiceException("53060410", getMessage("53060410"));
|
||||
}
|
||||
AreaType areaType = this.areaTypeMapper.selectByPrimaryKey(param.getId());
|
||||
AreaTypeResult result = (AreaTypeResult)BeanCopyUtils.copyProperties(areaType, AreaTypeResult.class);
|
||||
AreaTypeProperties proQuery = new AreaTypeProperties();
|
||||
proQuery.setAreaTypeId(param.getId());
|
||||
List<AreaTypeProperties> typeProperties = this.areaTypePropertiesMapper.select(proQuery);
|
||||
result.setProperties(BeanCopyUtils.copy(typeProperties, AreaTypePropertyParam.class));
|
||||
return CloudwalkResult.success(result);
|
||||
}
|
||||
private String getCode(Set<String> codeSet) {
|
||||
for (int i = 1; i <= 30; i++) {
|
||||
if (codeSet.add("ext" + i)) {
|
||||
return "ext" + i;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/AreaTypeServiceImpl.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+251
-239
@@ -1,6 +1,7 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.device.mgn.atomic.param.CoreDeviceQueryParam;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.result.AtomicDeviceGetResult;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.service.AtomicDeviceService;
|
||||
import cn.cloudwalk.client.organization.common.enums.CertPropertyEnum;
|
||||
import cn.cloudwalk.client.organization.common.enums.RegistryTypeEnum;
|
||||
@@ -21,25 +22,24 @@ import cn.cloudwalk.cloud.utils.BeanCopyUtils;
|
||||
import cn.cloudwalk.data.organization.entity.ImgStorePersonAudit;
|
||||
import cn.cloudwalk.data.organization.entity.ImgStorePersonProperties;
|
||||
import cn.cloudwalk.data.organization.entity.PersonRegistry;
|
||||
import cn.cloudwalk.data.organization.entity.PersonRegistryDevice;
|
||||
import cn.cloudwalk.data.organization.entity.PersonRegistryProperties;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonAuditMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonPropertiesMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.PersonRegistryDeviceMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.PersonRegistryPropertiesMapper;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import cn.cloudwalk.service.organization.service.CommonPersonRegistryService;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Sets;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Resource;
|
||||
@@ -50,243 +50,255 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
import org.springside.modules.utils.Collections3;
|
||||
|
||||
@Service(value="CertRegistryHandler")
|
||||
@Service("CertRegistryHandler")
|
||||
public class CertRegistryHandler
|
||||
extends AbstractImagStoreService
|
||||
implements IPersonRegistryHandler {
|
||||
@Resource
|
||||
private UUIDSerial uuidSerial;
|
||||
@Resource
|
||||
private CommonPersonRegistryService commonPersonRegistryService;
|
||||
@Resource
|
||||
private AtomicDeviceService atomicDeviceService;
|
||||
@Resource
|
||||
private ImgStorePersonPropertiesMapper imgStorePersonPropertiesMapper;
|
||||
@Resource
|
||||
private PersonRegistryPropertiesMapper personRegistryPropertiesMapper;
|
||||
@Resource
|
||||
private PersonRegistryDeviceMapper personRegistryDeviceMapper;
|
||||
@Resource
|
||||
private ImgStorePersonAuditMapper imgStorePersonAuditMapper;
|
||||
|
||||
@CloudwalkParamsValidate
|
||||
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class}, value="transactionManager")
|
||||
public CloudwalkResult<Boolean> save(AddPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId = context.getCompany().getCompanyId();
|
||||
param.setBusinessId(businessId);
|
||||
CloudwalkResult<Boolean> result = this.validateParams(param, context);
|
||||
if (!result.isSuccess()) {
|
||||
return result;
|
||||
}
|
||||
PersonRegistry personRegistry = this.commonPersonRegistryService.getByBusinessAndType(businessId, RegistryTypeEnum.CERT_REGISTRY.getValue());
|
||||
if (null != personRegistry) {
|
||||
param.setId(personRegistry.getId());
|
||||
this.update(param, context);
|
||||
} else {
|
||||
this.insert(param, context);
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
private CloudwalkResult<Boolean> validateParams(AddPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
if (Objects.equals(param.getDeviceStatus(), StatusEnum.CLOSE.getValue()) && StringUtils.isBlank((CharSequence)param.getOrganizationIds()) && StringUtils.isBlank((CharSequence)param.getLabelIds())) {
|
||||
this.logger.warn("人证注册审核关闭,注册默认组织/注册默认标签需要二选一,身份证属性:[{}]", (Object)JSON.toJSONString((Object)param.getPropertyList()));
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
if (CollectionUtils.isEmpty((Collection)param.getPropertyList())) {
|
||||
this.logger.warn("身份证属性未设置,身份证属性:[{}]", (Object)JSON.toJSONString((Object)param.getPropertyList()));
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
Optional<BindPropertyParam> optionalCardId = param.getPropertyList().stream().filter(propertyParam -> Objects.equals(propertyParam.getProperty(), CertPropertyEnum.CARD_ID.getValue())).findFirst();
|
||||
if (!optionalCardId.isPresent() || optionalCardId.isPresent() && StringUtils.isBlank((CharSequence)optionalCardId.get().getBindPropertyId())) {
|
||||
this.logger.warn("身份证号未选择关联属性,身份证属性:[{}]", (Object)JSON.toJSONString((Object)param.getPropertyList()));
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
Optional<BindPropertyParam> optionalName = param.getPropertyList().stream().filter(propertyParam -> Objects.equals(propertyParam.getProperty(), CertPropertyEnum.NAME.getValue())).findFirst();
|
||||
if (optionalName.isPresent()) {
|
||||
if (StringUtils.isBlank((CharSequence)optionalName.get().getBindPropertyId())) {
|
||||
this.logger.warn("姓名未正确关联属性,身份证属性:[{}]", (Object)JSON.toJSONString((Object)param.getPropertyList()));
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
ImgStorePersonProperties queryPersonPro = new ImgStorePersonProperties();
|
||||
queryPersonPro.setBusinessId(param.getBusinessId());
|
||||
queryPersonPro.setStatus(StatusEnum.VALID.getValue());
|
||||
queryPersonPro.setId(optionalName.get().getBindPropertyId());
|
||||
List personPropertyList = this.imgStorePersonPropertiesMapper.select(queryPersonPro);
|
||||
if (CollectionUtils.isEmpty((Collection)personPropertyList) || !Objects.equals(((ImgStorePersonProperties)personPropertyList.get(0)).getCode(), "name")) {
|
||||
this.logger.warn("姓名未正确关联属性,身份证属性:[{}]", (Object)JSON.toJSONString((Object)param.getPropertyList()));
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
}
|
||||
HashSet propertySet = Sets.newHashSet();
|
||||
HashSet bindPropertySet = Sets.newHashSet();
|
||||
param.getPropertyList().forEach(propertyParam -> {
|
||||
propertySet.add(propertyParam.getProperty());
|
||||
bindPropertySet.add(propertyParam.getBindPropertyId());
|
||||
});
|
||||
if (propertySet.size() < param.getPropertyList().size() || bindPropertySet.size() < param.getPropertyList().size()) {
|
||||
this.logger.warn("身份证属性和人员属性为一对一关系,不能一对多,身份证属性:[{}]", (Object)JSON.toJSONString((Object)param.getPropertyList()));
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
this.commonPersonRegistryService.validateOrg(param);
|
||||
this.commonPersonRegistryService.validateLabel(param);
|
||||
this.commonPersonRegistryService.validateDevice(param, context);
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
private CloudwalkResult<Boolean> insert(AddPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String id = this.uuidSerial.uuid();
|
||||
this.commonPersonRegistryService.insertPersonRegistry(id, param, context);
|
||||
this.commonPersonRegistryService.batchInsertPersonRegistryProperty(id, param);
|
||||
this.commonPersonRegistryService.batchInsertPersonRegistryDevice(id, param, context, true);
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
private CloudwalkResult<Boolean> update(AddPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
this.commonPersonRegistryService.updatePersonRegistry(param, context);
|
||||
this.commonPersonRegistryService.batchUpdatePersonRegistryProperty(param);
|
||||
this.commonPersonRegistryService.batchUpdatePersonRegistryDevice(param, context, true);
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
public CloudwalkResult<PersonRegistryResult> detail(QueryPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId = param.getBusinessId();
|
||||
if (StringUtils.isBlank((CharSequence)businessId)) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
param.setBusinessId(businessId);
|
||||
PersonRegistryResult result = new PersonRegistryResult();
|
||||
result.setDeviceStatus(StatusEnum.OPEN.getValue());
|
||||
List<Object> proResultList = Lists.newArrayListWithCapacity((int)CertPropertyEnum.values().length);
|
||||
PersonPropertiesResult proResult = null;
|
||||
for (CertPropertyEnum certProperty : CertPropertyEnum.values()) {
|
||||
proResult = new PersonPropertiesResult();
|
||||
proResult.setBindProp(certProperty.getValue());
|
||||
proResult.setBindPropName(certProperty.getDescription());
|
||||
proResult.setOrderNum(Integer.valueOf(certProperty.getSort()));
|
||||
proResultList.add(proResult);
|
||||
}
|
||||
proResultList = proResultList.stream().sorted(Comparator.comparing(PersonPropertiesResult::getOrderNum)).collect(Collectors.toList());
|
||||
result.setPropertyList((List)proResultList);
|
||||
PersonRegistry dbPersonRegistry = this.commonPersonRegistryService.getByBusinessAndType(businessId, RegistryTypeEnum.CERT_REGISTRY.getValue());
|
||||
if (null != dbPersonRegistry) {
|
||||
BeanCopyUtils.copyProperties((Object)dbPersonRegistry, (Object)result);
|
||||
this.commonPersonRegistryService.setOrg(dbPersonRegistry, result);
|
||||
this.commonPersonRegistryService.setLabel(dbPersonRegistry, result);
|
||||
List dbPersonRegistryDeviceList = this.personRegistryDeviceMapper.select(dbPersonRegistry.getId(), null);
|
||||
if (!CollectionUtils.isEmpty((Collection)dbPersonRegistryDeviceList)) {
|
||||
CoreDeviceQueryParam coreDeviceQueryParam = new CoreDeviceQueryParam();
|
||||
coreDeviceQueryParam.setBusinessId(businessId);
|
||||
coreDeviceQueryParam.setDeviceCodes(Collections3.extractToList((Collection)dbPersonRegistryDeviceList, (String)"deviceCode"));
|
||||
CloudwalkResult deviceGetResult = this.atomicDeviceService.list(coreDeviceQueryParam, context);
|
||||
if (!CollectionUtils.isEmpty((Collection)((Collection)deviceGetResult.getData()))) {
|
||||
ArrayList deviceResultList = Lists.newArrayListWithCapacity((int)((List)deviceGetResult.getData()).size());
|
||||
((List)deviceGetResult.getData()).forEach(device -> {
|
||||
DeviceResult deviceResult = new DeviceResult();
|
||||
deviceResult.setDeviceCode(device.getDeviceCode());
|
||||
deviceResult.setDeviceName(device.getDeviceName());
|
||||
deviceResultList.add(deviceResult);
|
||||
});
|
||||
result.setDeviceList((List)deviceResultList);
|
||||
}
|
||||
}
|
||||
List dbPersonRegistryProList = this.personRegistryPropertiesMapper.select(dbPersonRegistry.getId(), null);
|
||||
ImgStorePersonProperties queryPersonPro = new ImgStorePersonProperties();
|
||||
queryPersonPro.setBusinessId(businessId);
|
||||
queryPersonPro.setStatus(StatusEnum.VALID.getValue());
|
||||
List personPropertyList = this.imgStorePersonPropertiesMapper.select(queryPersonPro);
|
||||
result.getPropertyList().forEach(property -> {
|
||||
Optional<ImgStorePersonProperties> propertyOptional;
|
||||
Optional<PersonRegistryProperties> registryPropertyOptional = dbPersonRegistryProList.stream().filter(personProperty -> Objects.equals(personProperty.getBindPropertyCode(), property.getBindProp())).findFirst();
|
||||
if (registryPropertyOptional.isPresent() && (propertyOptional = personPropertyList.stream().filter(personProperty -> Objects.equals(personProperty.getId(), ((PersonRegistryProperties)registryPropertyOptional.get()).getPersonPropertyId())).findFirst()).isPresent()) {
|
||||
int orderNum = property.getOrderNum();
|
||||
BeanCopyUtils.copyProperties((Object)propertyOptional.get(), (Object)property);
|
||||
property.setOrderNum(Integer.valueOf(orderNum));
|
||||
property.setHasChecked(StatusEnum.CHECKED.getValue());
|
||||
}
|
||||
if (Objects.equals(property.getBindProp(), CertPropertyEnum.CARD_ID.getValue())) {
|
||||
property.setHasUnique(StatusEnum.UNIQUE.getValue());
|
||||
}
|
||||
});
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
public CloudwalkResult<List<PersonPropertiesResult>> getRegistryPropertyList(QueryPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId = param.getBusinessId();
|
||||
if (StringUtils.isBlank((CharSequence)businessId)) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
PersonRegistry dbPersonRegistry = (PersonRegistry)this.commonPersonRegistryService.getResultByBusinessAndType(businessId, RegistryTypeEnum.CERT_REGISTRY.getValue()).getData();
|
||||
this.commonPersonRegistryService.validateDevice(param, dbPersonRegistry);
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
public CloudwalkResult<List<PersonPropertiesResult>> getAuditPropertyList(QueryPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
ImgStorePersonAudit personAudit;
|
||||
String businessId = param.getBusinessId();
|
||||
if (StringUtils.isBlank((CharSequence)businessId)) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
PersonRegistry dbPersonRegistry = (PersonRegistry)this.commonPersonRegistryService.getResultByBusinessAndType(businessId, RegistryTypeEnum.CERT_REGISTRY.getValue()).getData();
|
||||
List<PersonPropertiesResult> propertyList = this.getPersonPropertyList(dbPersonRegistry, false);
|
||||
if (StringUtils.isNotBlank((CharSequence)param.getPersonAuditId()) && null != (personAudit = this.imgStorePersonAuditMapper.selectByPrimaryKey(param.getPersonAuditId(), null))) {
|
||||
for (PersonPropertiesResult property : propertyList) {
|
||||
Field auditField = ReflectionUtils.findField(ImgStorePersonAudit.class, (String)property.getCode());
|
||||
auditField.setAccessible(true);
|
||||
Object value = ReflectionUtils.getField((Field)auditField, (Object)personAudit);
|
||||
property.setValue(String.valueOf(Optional.ofNullable(value).orElse("")));
|
||||
}
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
private List<PersonPropertiesResult> getPersonPropertyList(PersonRegistry personRegistry, boolean isChecked) {
|
||||
List dbPersonRegistryProList = this.personRegistryPropertiesMapper.select(personRegistry.getId(), null);
|
||||
Map<String, PersonRegistryProperties> personRegistryProMap = dbPersonRegistryProList.stream().collect(Collectors.toMap(map -> map.getPersonPropertyId(), map -> map));
|
||||
List personProIdList = Collections3.extractToList((Collection)dbPersonRegistryProList, (String)"personPropertyId");
|
||||
ImgStorePersonProperties queryPersonPro = new ImgStorePersonProperties();
|
||||
queryPersonPro.setBusinessId(personRegistry.getBusinessId());
|
||||
queryPersonPro.setStatus(StatusEnum.VALID.getValue());
|
||||
List dbPersonProList = this.imgStorePersonPropertiesMapper.select(queryPersonPro);
|
||||
List<PersonPropertiesResult> proResultList = BeanCopyUtils.copy((Collection)dbPersonProList, PersonPropertiesResult.class);
|
||||
proResultList = proResultList.stream().filter(proResult -> personProIdList.contains(proResult.getId()) == isChecked).collect(Collectors.toList());
|
||||
if (isChecked) {
|
||||
proResultList.forEach(proResult -> {
|
||||
proResult.setBindProp(((PersonRegistryProperties)personRegistryProMap.get(proResult.getId())).getBindPropertyCode());
|
||||
proResult.setOrderNum(Integer.valueOf(CertPropertyEnum.getSort((String)proResult.getBindProp())));
|
||||
if (Objects.equals(proResult.getBindProp(), CertPropertyEnum.CARD_ID.getValue())) {
|
||||
proResult.setHasUnique(StatusEnum.UNIQUE.getValue());
|
||||
}
|
||||
});
|
||||
}
|
||||
proResultList = proResultList.stream().sorted(Comparator.comparing(PersonPropertiesResult::getOrderNum)).collect(Collectors.toList());
|
||||
return proResultList;
|
||||
}
|
||||
|
||||
public CloudwalkResult<PersonPropertiesResult> getUniqueRegistryProperty(QueryPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId = param.getBusinessId();
|
||||
if (StringUtils.isBlank((CharSequence)businessId)) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
PersonRegistry dbPersonRegistry = (PersonRegistry)this.commonPersonRegistryService.getResultByBusinessAndType(businessId, RegistryTypeEnum.CERT_REGISTRY.getValue()).getData();
|
||||
List<PersonPropertiesResult> propertyList = this.getPersonPropertyList(dbPersonRegistry, true);
|
||||
AtomicReference result = new AtomicReference();
|
||||
propertyList.stream().filter(property -> Objects.equals(CertPropertyEnum.CARD_ID.getValue(), property.getBindProp())).findFirst().ifPresent(personPropertiesResult -> result.set(personPropertiesResult));
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
public CloudwalkResult<PersonPropertiesResult> getBindProperty(QueryPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
AtomicReference result = new AtomicReference();
|
||||
String businessId = param.getBusinessId();
|
||||
if (StringUtils.isBlank((CharSequence)businessId)) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
PersonRegistry dbPersonRegistry = (PersonRegistry)this.commonPersonRegistryService.getResultByBusinessAndType(businessId, RegistryTypeEnum.CERT_REGISTRY.getValue()).getData();
|
||||
List<PersonPropertiesResult> propertyResultList = this.getPersonPropertyList(dbPersonRegistry, true);
|
||||
propertyResultList.stream().filter(property -> Objects.equals(property.getBindProp(), param.getBindPropertyCode())).findFirst().ifPresent(property -> result.set(property));
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
implements IPersonRegistryHandler
|
||||
{
|
||||
@Resource
|
||||
private UUIDSerial uuidSerial;
|
||||
@Resource
|
||||
private CommonPersonRegistryService commonPersonRegistryService;
|
||||
@Resource
|
||||
private AtomicDeviceService atomicDeviceService;
|
||||
@Resource
|
||||
private ImgStorePersonPropertiesMapper imgStorePersonPropertiesMapper;
|
||||
@Resource
|
||||
private PersonRegistryPropertiesMapper personRegistryPropertiesMapper;
|
||||
@Resource
|
||||
private PersonRegistryDeviceMapper personRegistryDeviceMapper;
|
||||
@Resource
|
||||
private ImgStorePersonAuditMapper imgStorePersonAuditMapper;
|
||||
@CloudwalkParamsValidate
|
||||
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class}, value = "transactionManager")
|
||||
public CloudwalkResult<Boolean> save(AddPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId = context.getCompany().getCompanyId();
|
||||
param.setBusinessId(businessId);
|
||||
CloudwalkResult<Boolean> result = validateParams(param, context);
|
||||
if (!result.isSuccess()) {
|
||||
return result;
|
||||
}
|
||||
PersonRegistry personRegistry = this.commonPersonRegistryService.getByBusinessAndType(businessId, RegistryTypeEnum.CERT_REGISTRY.getValue());
|
||||
if (null != personRegistry) {
|
||||
param.setId(personRegistry.getId());
|
||||
update(param, context);
|
||||
} else {
|
||||
insert(param, context);
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.valueOf(true));
|
||||
}
|
||||
private CloudwalkResult<Boolean> validateParams(AddPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
if (Objects.equals(param.getDeviceStatus(), StatusEnum.CLOSE.getValue()) &&
|
||||
StringUtils.isBlank(param.getOrganizationIds()) && StringUtils.isBlank(param.getLabelIds())) {
|
||||
this.logger.warn("人证注册审核关闭,注册默认组织/注册默认标签需要二选一,身份证属性:[{}]", JSON.toJSONString(param.getPropertyList()));
|
||||
return CloudwalkResult.fail("53014529",
|
||||
getMessage("53014529"));
|
||||
}
|
||||
if (CollectionUtils.isEmpty(param.getPropertyList())) {
|
||||
this.logger.warn("身份证属性未设置,身份证属性:[{}]", JSON.toJSONString(param.getPropertyList()));
|
||||
return CloudwalkResult.fail("53014525",
|
||||
getMessage("53014525"));
|
||||
}
|
||||
Optional<BindPropertyParam> optionalCardId = param.getPropertyList().stream().filter(propertyParam -> Objects.equals(propertyParam.getProperty(), CertPropertyEnum.CARD_ID.getValue())).findFirst();
|
||||
if (!optionalCardId.isPresent() || (optionalCardId.isPresent() &&
|
||||
StringUtils.isBlank(((BindPropertyParam)optionalCardId.get()).getBindPropertyId()))) {
|
||||
this.logger.warn("身份证号未选择关联属性,身份证属性:[{}]", JSON.toJSONString(param.getPropertyList()));
|
||||
return CloudwalkResult.fail("53014526",
|
||||
getMessage("53014526"));
|
||||
}
|
||||
Optional<BindPropertyParam> optionalName = param.getPropertyList().stream().filter(propertyParam -> Objects.equals(propertyParam.getProperty(), CertPropertyEnum.NAME.getValue())).findFirst();
|
||||
if (optionalName.isPresent()) {
|
||||
if (StringUtils.isBlank(((BindPropertyParam)optionalName.get()).getBindPropertyId())) {
|
||||
this.logger.warn("姓名未正确关联属性,身份证属性:[{}]", JSON.toJSONString(param.getPropertyList()));
|
||||
return CloudwalkResult.fail("53014527",
|
||||
getMessage("53014527"));
|
||||
}
|
||||
ImgStorePersonProperties queryPersonPro = new ImgStorePersonProperties();
|
||||
queryPersonPro.setBusinessId(param.getBusinessId());
|
||||
queryPersonPro.setStatus(StatusEnum.VALID.getValue());
|
||||
queryPersonPro.setId(((BindPropertyParam)optionalName.get()).getBindPropertyId());
|
||||
List<ImgStorePersonProperties> personPropertyList = this.imgStorePersonPropertiesMapper.select(queryPersonPro);
|
||||
if (CollectionUtils.isEmpty(personPropertyList) ||
|
||||
!Objects.equals(((ImgStorePersonProperties)personPropertyList.get(0)).getCode(), "name")) {
|
||||
this.logger.warn("姓名未正确关联属性,身份证属性:[{}]", JSON.toJSONString(param.getPropertyList()));
|
||||
return CloudwalkResult.fail("53014527",
|
||||
getMessage("53014527"));
|
||||
}
|
||||
}
|
||||
Set<String> propertySet = Sets.newHashSet();
|
||||
Set<String> bindPropertySet = Sets.newHashSet();
|
||||
param.getPropertyList().forEach(propertyParam -> {
|
||||
propertySet.add(propertyParam.getProperty());
|
||||
bindPropertySet.add(propertyParam.getBindPropertyId());
|
||||
});
|
||||
if (propertySet.size() < param.getPropertyList().size() || bindPropertySet.size() < param.getPropertyList()
|
||||
.size()) {
|
||||
this.logger.warn("身份证属性和人员属性为一对一关系,不能一对多,身份证属性:[{}]", JSON.toJSONString(param.getPropertyList()));
|
||||
return CloudwalkResult.fail("53014528",
|
||||
getMessage("53014528"));
|
||||
}
|
||||
this.commonPersonRegistryService.validateOrg(param);
|
||||
this.commonPersonRegistryService.validateLabel(param);
|
||||
this.commonPersonRegistryService.validateDevice(param, context);
|
||||
return CloudwalkResult.success(Boolean.valueOf(true));
|
||||
}
|
||||
private CloudwalkResult<Boolean> insert(AddPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String id = this.uuidSerial.uuid();
|
||||
this.commonPersonRegistryService.insertPersonRegistry(id, param, context);
|
||||
this.commonPersonRegistryService.batchInsertPersonRegistryProperty(id, param);
|
||||
this.commonPersonRegistryService.batchInsertPersonRegistryDevice(id, param, context, Boolean.valueOf(true));
|
||||
return CloudwalkResult.success(Boolean.valueOf(true));
|
||||
}
|
||||
private CloudwalkResult<Boolean> update(AddPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
this.commonPersonRegistryService.updatePersonRegistry(param, context);
|
||||
this.commonPersonRegistryService.batchUpdatePersonRegistryProperty(param);
|
||||
this.commonPersonRegistryService.batchUpdatePersonRegistryDevice(param, context, Boolean.valueOf(true));
|
||||
return CloudwalkResult.success(Boolean.valueOf(true));
|
||||
}
|
||||
public CloudwalkResult<PersonRegistryResult> detail(QueryPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId = param.getBusinessId();
|
||||
if (StringUtils.isBlank(businessId)) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
param.setBusinessId(businessId);
|
||||
PersonRegistryResult result = new PersonRegistryResult();
|
||||
result.setDeviceStatus(StatusEnum.OPEN.getValue());
|
||||
List<PersonPropertiesResult> proResultList = Lists.newArrayListWithCapacity((CertPropertyEnum.values()).length);
|
||||
PersonPropertiesResult proResult = null;
|
||||
for (CertPropertyEnum certProperty : CertPropertyEnum.values()) {
|
||||
proResult = new PersonPropertiesResult();
|
||||
proResult.setBindProp(certProperty.getValue());
|
||||
proResult.setBindPropName(certProperty.getDescription());
|
||||
proResult.setOrderNum(Integer.valueOf(certProperty.getSort()));
|
||||
proResultList.add(proResult);
|
||||
}
|
||||
proResultList = (List<PersonPropertiesResult>)proResultList.stream().sorted(Comparator.comparing(PersonPropertiesResult::getOrderNum)).collect(Collectors.toList());
|
||||
result.setPropertyList(proResultList);
|
||||
PersonRegistry dbPersonRegistry = this.commonPersonRegistryService.getByBusinessAndType(businessId, RegistryTypeEnum.CERT_REGISTRY.getValue());
|
||||
if (null != dbPersonRegistry) {
|
||||
BeanCopyUtils.copyProperties(dbPersonRegistry, result);
|
||||
this.commonPersonRegistryService.setOrg(dbPersonRegistry, result);
|
||||
this.commonPersonRegistryService.setLabel(dbPersonRegistry, result);
|
||||
List<PersonRegistryDevice> dbPersonRegistryDeviceList = this.personRegistryDeviceMapper.select(dbPersonRegistry.getId(), null);
|
||||
if (!CollectionUtils.isEmpty(dbPersonRegistryDeviceList)) {
|
||||
CoreDeviceQueryParam coreDeviceQueryParam = new CoreDeviceQueryParam();
|
||||
coreDeviceQueryParam.setBusinessId(businessId);
|
||||
coreDeviceQueryParam
|
||||
.setDeviceCodes(Collections3.extractToList(dbPersonRegistryDeviceList, "deviceCode"));
|
||||
CloudwalkResult<List<AtomicDeviceGetResult>> deviceGetResult = this.atomicDeviceService.list(coreDeviceQueryParam, context);
|
||||
if (!CollectionUtils.isEmpty((Collection)deviceGetResult.getData())) {
|
||||
List<DeviceResult> deviceResultList = Lists.newArrayListWithCapacity(((List)deviceGetResult.getData()).size());
|
||||
((List)deviceGetResult.getData()).forEach(device -> {
|
||||
DeviceResult deviceResult = new DeviceResult();
|
||||
deviceResult.setDeviceCode(device.getDeviceCode());
|
||||
deviceResult.setDeviceName(device.getDeviceName());
|
||||
deviceResultList.add(deviceResult);
|
||||
});
|
||||
result.setDeviceList(deviceResultList);
|
||||
}
|
||||
}
|
||||
List<PersonRegistryProperties> dbPersonRegistryProList = this.personRegistryPropertiesMapper.select(dbPersonRegistry.getId(), null);
|
||||
ImgStorePersonProperties queryPersonPro = new ImgStorePersonProperties();
|
||||
queryPersonPro.setBusinessId(businessId);
|
||||
queryPersonPro.setStatus(StatusEnum.VALID.getValue());
|
||||
List<ImgStorePersonProperties> personPropertyList = this.imgStorePersonPropertiesMapper.select(queryPersonPro);
|
||||
result.getPropertyList().forEach(property -> {
|
||||
Optional<PersonRegistryProperties> registryPropertyOptional = dbPersonRegistryProList.stream().filter(v -> true).findFirst();
|
||||
if (registryPropertyOptional.isPresent()) {
|
||||
Optional<ImgStorePersonProperties> propertyOptional = personPropertyList.stream().filter(v -> true).findFirst();
|
||||
if (propertyOptional.isPresent()) {
|
||||
int orderNum = property.getOrderNum().intValue();
|
||||
BeanCopyUtils.copyProperties(propertyOptional.get(), property);
|
||||
property.setOrderNum(Integer.valueOf(orderNum));
|
||||
property.setHasChecked(StatusEnum.CHECKED.getValue());
|
||||
}
|
||||
}
|
||||
if (Objects.equals(property.getBindProp(), CertPropertyEnum.CARD_ID.getValue())) {
|
||||
property.setHasUnique(StatusEnum.UNIQUE.getValue());
|
||||
}
|
||||
});
|
||||
}
|
||||
return CloudwalkResult.success(result);
|
||||
}
|
||||
public CloudwalkResult<List<PersonPropertiesResult>> getRegistryPropertyList(QueryPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId = param.getBusinessId();
|
||||
if (StringUtils.isBlank(businessId)) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
PersonRegistry dbPersonRegistry = (PersonRegistry)this.commonPersonRegistryService.getResultByBusinessAndType(businessId, RegistryTypeEnum.CERT_REGISTRY.getValue()).getData();
|
||||
this.commonPersonRegistryService.validateDevice(param, dbPersonRegistry);
|
||||
return CloudwalkResult.success(getPersonPropertyList(dbPersonRegistry, true));
|
||||
}
|
||||
public CloudwalkResult<List<PersonPropertiesResult>> getAuditPropertyList(QueryPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId = param.getBusinessId();
|
||||
if (StringUtils.isBlank(businessId)) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
PersonRegistry dbPersonRegistry = (PersonRegistry)this.commonPersonRegistryService.getResultByBusinessAndType(businessId, RegistryTypeEnum.CERT_REGISTRY.getValue()).getData();
|
||||
List<PersonPropertiesResult> propertyList = getPersonPropertyList(dbPersonRegistry, false);
|
||||
if (StringUtils.isNotBlank(param.getPersonAuditId())) {
|
||||
ImgStorePersonAudit personAudit = this.imgStorePersonAuditMapper.selectByPrimaryKey(param.getPersonAuditId(), null);
|
||||
if (null != personAudit) {
|
||||
for (PersonPropertiesResult property : propertyList) {
|
||||
Field auditField = ReflectionUtils.findField(ImgStorePersonAudit.class, property.getCode());
|
||||
auditField.setAccessible(true);
|
||||
Object value = ReflectionUtils.getField(auditField, personAudit);
|
||||
property.setValue(String.valueOf(Optional.<Object>ofNullable(value).orElse("")));
|
||||
}
|
||||
}
|
||||
}
|
||||
return CloudwalkResult.success(propertyList);
|
||||
}
|
||||
private List<PersonPropertiesResult> getPersonPropertyList(PersonRegistry personRegistry, boolean isChecked) {
|
||||
List<PersonRegistryProperties> dbPersonRegistryProList = this.personRegistryPropertiesMapper.select(personRegistry.getId(), null);
|
||||
Map<String, PersonRegistryProperties> personRegistryProMap = (Map<String, PersonRegistryProperties>)dbPersonRegistryProList.stream().collect(Collectors.toMap(map -> map.getPersonPropertyId(), map -> map));
|
||||
List<String> personProIdList = Collections3.extractToList(dbPersonRegistryProList, "personPropertyId");
|
||||
ImgStorePersonProperties queryPersonPro = new ImgStorePersonProperties();
|
||||
queryPersonPro.setBusinessId(personRegistry.getBusinessId());
|
||||
queryPersonPro.setStatus(StatusEnum.VALID.getValue());
|
||||
List<ImgStorePersonProperties> dbPersonProList = this.imgStorePersonPropertiesMapper.select(queryPersonPro);
|
||||
List<PersonPropertiesResult> proResultList = BeanCopyUtils.copy(dbPersonProList, PersonPropertiesResult.class);
|
||||
proResultList = (List<PersonPropertiesResult>)proResultList.stream().filter(proResult -> (personProIdList.contains(proResult.getId()) == isChecked)).collect(Collectors.toList());
|
||||
if (isChecked) {
|
||||
proResultList.forEach(proResult -> {
|
||||
proResult.setBindProp(((PersonRegistryProperties)personRegistryProMap.get(proResult.getId())).getBindPropertyCode());
|
||||
proResult.setOrderNum(Integer.valueOf(CertPropertyEnum.getSort(proResult.getBindProp())));
|
||||
if (Objects.equals(proResult.getBindProp(), CertPropertyEnum.CARD_ID.getValue())) {
|
||||
proResult.setHasUnique(StatusEnum.UNIQUE.getValue());
|
||||
}
|
||||
});
|
||||
}
|
||||
proResultList = (List<PersonPropertiesResult>)proResultList.stream().sorted(Comparator.comparing(PersonPropertiesResult::getOrderNum)).collect(Collectors.toList());
|
||||
return proResultList;
|
||||
}
|
||||
public CloudwalkResult<PersonPropertiesResult> getUniqueRegistryProperty(QueryPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId = param.getBusinessId();
|
||||
if (StringUtils.isBlank(businessId)) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
PersonRegistry dbPersonRegistry = (PersonRegistry)this.commonPersonRegistryService.getResultByBusinessAndType(businessId, RegistryTypeEnum.CERT_REGISTRY.getValue()).getData();
|
||||
List<PersonPropertiesResult> propertyList = getPersonPropertyList(dbPersonRegistry, true);
|
||||
AtomicReference<PersonPropertiesResult> result = new AtomicReference<>();
|
||||
propertyList.stream()
|
||||
.filter(property -> Objects.equals(CertPropertyEnum.CARD_ID.getValue(), property.getBindProp()))
|
||||
.findFirst().ifPresent(personPropertiesResult -> result.set(personPropertiesResult));
|
||||
return CloudwalkResult.success(result.get());
|
||||
}
|
||||
public CloudwalkResult<PersonPropertiesResult> getBindProperty(QueryPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
AtomicReference<PersonPropertiesResult> result = new AtomicReference<>();
|
||||
String businessId = param.getBusinessId();
|
||||
if (StringUtils.isBlank(businessId)) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
PersonRegistry dbPersonRegistry = (PersonRegistry)this.commonPersonRegistryService.getResultByBusinessAndType(businessId, RegistryTypeEnum.CERT_REGISTRY.getValue()).getData();
|
||||
List<PersonPropertiesResult> propertyResultList = getPersonPropertyList(dbPersonRegistry, true);
|
||||
propertyResultList.stream().filter(property -> Objects.equals(property.getBindProp(), param.getBindPropertyCode())).findFirst().ifPresent(property -> result.set(property));
|
||||
return CloudwalkResult.success(result.get());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/CertRegistryHandler.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+98
-98
@@ -27,105 +27,105 @@ import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
@Service
|
||||
public class CommonAppDownloadCenterServiceImpl
|
||||
implements ICommonAppDownloadCenterService {
|
||||
private static final Logger log = LoggerFactory.getLogger(CommonAppDownloadCenterServiceImpl.class);
|
||||
@Autowired
|
||||
private ApplicationService applicationService;
|
||||
@Autowired
|
||||
private ComponentInnerKafkaConfig componentInnerKafkaConfig;
|
||||
@Resource
|
||||
private MessageCenterFeignClient messageCenterFeignClient;
|
||||
private static final Map<String, CloudwalkCallContext> CXT_MAP = new ConcurrentHashMap<String, CloudwalkCallContext>();
|
||||
|
||||
public String createDownload(CloudwalkCallContext cloudwalkCallContext, String fileName, String businessId) {
|
||||
try {
|
||||
String applicationId = this.getApplicationId(businessId);
|
||||
cloudwalkCallContext.setApplicationId(applicationId);
|
||||
CXT_MAP.put(businessId, cloudwalkCallContext);
|
||||
return this.fileInit(cloudwalkCallContext, fileName);
|
||||
}
|
||||
catch (ServiceException e) {
|
||||
log.error("下载任务初始化接口错误", (Object)e.getMessage());
|
||||
throw new RuntimeException("下载任务创建失败");
|
||||
}
|
||||
}
|
||||
|
||||
private String fileInit(CloudwalkCallContext cloudwalkCallContext, String fileName) throws ServiceException {
|
||||
FileInitParam fileInitParam = new FileInitParam();
|
||||
fileInitParam.setFileName(fileName);
|
||||
fileInitParam.setApplicationId(cloudwalkCallContext.getApplicationId());
|
||||
cloudwalkCallContext.setCallTime(CloudwalkDateUtils.getCurrentDate());
|
||||
log.info("创建下载任务 context:{}", (Object)JsonUtils.toJson(cloudwalkCallContext));
|
||||
try {
|
||||
CloudwalkResult<String> result = this.messageCenterFeignClient.initFile(fileInitParam, cloudwalkCallContext.getCompany().getCompanyId(), cloudwalkCallContext.getUser().getCaller());
|
||||
if ("00000000".equals(result.getCode())) {
|
||||
return (String)result.getData();
|
||||
}
|
||||
log.error("下载任务创建失败,code={},message={}", (Object)result.getCode(), (Object)result.getMessage());
|
||||
throw new RuntimeException("下载任务创建失败");
|
||||
}
|
||||
catch (Exception e) {
|
||||
log.error("下载任务初始化失败:{}", (Object)e.getMessage());
|
||||
throw new RuntimeException("下载任务创建失败");
|
||||
}
|
||||
}
|
||||
|
||||
private String getApplicationId(String businessId) throws ServiceException {
|
||||
ApplicationQueryParam param = new ApplicationQueryParam();
|
||||
param.setBusinessId(businessId);
|
||||
param.setStatus(CommonStatusEnum.ENABLE.getCode());
|
||||
param.setServiceCode(this.componentInnerKafkaConfig.getServiceCode());
|
||||
ArrayList<String> businessIds = new ArrayList<String>();
|
||||
businessIds.add(businessId);
|
||||
param.setBusinessIds(businessIds);
|
||||
CloudwalkResult listCloudwalkResult = this.applicationService.query(param);
|
||||
String applicationId = null;
|
||||
if (!CollectionUtils.isEmpty((Collection)((Collection)listCloudwalkResult.getData()))) {
|
||||
applicationId = ((ApplicationResult)((List)listCloudwalkResult.getData()).get(0)).getId();
|
||||
}
|
||||
return applicationId;
|
||||
}
|
||||
|
||||
public boolean finishDownload(String businessId, String fileId, String path, Long fileSize, Integer fileStatus) {
|
||||
try {
|
||||
FileFinishParam fileFinishParam = new FileFinishParam();
|
||||
fileFinishParam.setFileId(fileId);
|
||||
fileFinishParam.setFilePath(path);
|
||||
fileFinishParam.setFileSize(fileSize);
|
||||
fileFinishParam.setFileStatus(fileStatus);
|
||||
CloudwalkCallContext cloudwalkCallContext = CXT_MAP.get(businessId);
|
||||
cloudwalkCallContext.setCallTime(CloudwalkDateUtils.getCurrentDate());
|
||||
CloudwalkResult<Boolean> result = this.messageCenterFeignClient.finishFile(fileFinishParam, businessId, cloudwalkCallContext.getUser().getCaller());
|
||||
if ("00000000".equals(result.getCode())) {
|
||||
return true;
|
||||
}
|
||||
log.error("下载任务初始化失败:code={},message={}", (Object)result.getCode(), (Object)result.getMessage());
|
||||
}
|
||||
catch (ServiceException e) {
|
||||
log.error("下载任务完成接口错误", (Object)e.getMessage());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public int queryDownloadStatus(String businessId, String fileId) {
|
||||
try {
|
||||
FileGetParam fileGetParam = new FileGetParam();
|
||||
fileGetParam.setFileId(fileId);
|
||||
CloudwalkCallContext cloudwalkCallContext = CXT_MAP.get(businessId);
|
||||
cloudwalkCallContext.setCallTime(CloudwalkDateUtils.getCurrentDate());
|
||||
CloudwalkResult<FileResult> result = this.messageCenterFeignClient.getFile(fileGetParam, businessId, cloudwalkCallContext.getUser().getCaller());
|
||||
if ("00000000".equals(result.getCode())) {
|
||||
return ((FileResult)result.getData()).getStatus();
|
||||
}
|
||||
log.error("下载任务初始化失败:code={},message={}", (Object)result.getCode(), (Object)result.getMessage());
|
||||
}
|
||||
catch (ServiceException e) {
|
||||
log.error("下载任务完成接口错误", (Object)e.getMessage());
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
implements ICommonAppDownloadCenterService
|
||||
{
|
||||
private static final Logger log = LoggerFactory.getLogger(CommonAppDownloadCenterServiceImpl.class);
|
||||
@Autowired
|
||||
private ApplicationService applicationService;
|
||||
@Autowired
|
||||
private ComponentInnerKafkaConfig componentInnerKafkaConfig;
|
||||
@Resource
|
||||
private MessageCenterFeignClient messageCenterFeignClient;
|
||||
private static final Map<String, CloudwalkCallContext> CXT_MAP = new ConcurrentHashMap<>();
|
||||
public String createDownload(CloudwalkCallContext cloudwalkCallContext, String fileName, String businessId) {
|
||||
try {
|
||||
String applicationId = getApplicationId(businessId);
|
||||
cloudwalkCallContext.setApplicationId(applicationId);
|
||||
CXT_MAP.put(businessId, cloudwalkCallContext);
|
||||
return fileInit(cloudwalkCallContext, fileName);
|
||||
} catch (ServiceException e) {
|
||||
log.error("下载任务初始化接口错误", e.getMessage());
|
||||
throw new RuntimeException("下载任务创建失败");
|
||||
}
|
||||
}
|
||||
private String fileInit(CloudwalkCallContext cloudwalkCallContext, String fileName) throws ServiceException {
|
||||
FileInitParam fileInitParam = new FileInitParam();
|
||||
fileInitParam.setFileName(fileName);
|
||||
fileInitParam.setApplicationId(cloudwalkCallContext.getApplicationId());
|
||||
cloudwalkCallContext.setCallTime(CloudwalkDateUtils.getCurrentDate());
|
||||
log.info("创建下载任务 context:{}", JsonUtils.toJson(cloudwalkCallContext));
|
||||
try {
|
||||
CloudwalkResult<String> result = this.messageCenterFeignClient.initFile(fileInitParam, cloudwalkCallContext.getCompany().getCompanyId(), cloudwalkCallContext.getUser().getCaller());
|
||||
if ("00000000".equals(result.getCode())) {
|
||||
return (String)result.getData();
|
||||
}
|
||||
log.error("下载任务创建失败,code={},message={}", result.getCode(), result.getMessage());
|
||||
throw new RuntimeException("下载任务创建失败");
|
||||
}
|
||||
catch (Exception e) {
|
||||
log.error("下载任务初始化失败:{}", e.getMessage());
|
||||
throw new RuntimeException("下载任务创建失败");
|
||||
}
|
||||
}
|
||||
private String getApplicationId(String businessId) throws ServiceException {
|
||||
ApplicationQueryParam param = new ApplicationQueryParam();
|
||||
param.setBusinessId(businessId);
|
||||
param.setStatus(CommonStatusEnum.ENABLE.getCode());
|
||||
param.setServiceCode(this.componentInnerKafkaConfig.getServiceCode());
|
||||
List<String> businessIds = new ArrayList<>();
|
||||
businessIds.add(businessId);
|
||||
param.setBusinessIds(businessIds);
|
||||
CloudwalkResult<List<ApplicationResult>> listCloudwalkResult = this.applicationService.query(param);
|
||||
String applicationId = null;
|
||||
if (!CollectionUtils.isEmpty((Collection)listCloudwalkResult.getData())) {
|
||||
applicationId = ((ApplicationResult)((List<ApplicationResult>)listCloudwalkResult.getData()).get(0)).getId();
|
||||
}
|
||||
return applicationId;
|
||||
}
|
||||
public boolean finishDownload(String businessId, String fileId, String path, Long fileSize, Integer fileStatus) {
|
||||
try {
|
||||
FileFinishParam fileFinishParam = new FileFinishParam();
|
||||
fileFinishParam.setFileId(fileId);
|
||||
fileFinishParam.setFilePath(path);
|
||||
fileFinishParam.setFileSize(fileSize);
|
||||
fileFinishParam.setFileStatus(fileStatus);
|
||||
CloudwalkCallContext cloudwalkCallContext = CXT_MAP.get(businessId);
|
||||
cloudwalkCallContext.setCallTime(CloudwalkDateUtils.getCurrentDate());
|
||||
CloudwalkResult<Boolean> result = this.messageCenterFeignClient.finishFile(fileFinishParam, businessId, cloudwalkCallContext.getUser().getCaller());
|
||||
if ("00000000".equals(result.getCode())) {
|
||||
return true;
|
||||
}
|
||||
log.error("下载任务初始化失败:code={},message={}", result.getCode(), result.getMessage());
|
||||
}
|
||||
catch (ServiceException e) {
|
||||
log.error("下载任务完成接口错误", e.getMessage());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public int queryDownloadStatus(String businessId, String fileId) {
|
||||
try {
|
||||
FileGetParam fileGetParam = new FileGetParam();
|
||||
fileGetParam.setFileId(fileId);
|
||||
CloudwalkCallContext cloudwalkCallContext = CXT_MAP.get(businessId);
|
||||
cloudwalkCallContext.setCallTime(CloudwalkDateUtils.getCurrentDate());
|
||||
CloudwalkResult<FileResult> result = this.messageCenterFeignClient.getFile(fileGetParam, businessId, cloudwalkCallContext.getUser().getCaller());
|
||||
if ("00000000".equals(result.getCode()))
|
||||
{
|
||||
return ((FileResult)result.getData()).getStatus().intValue();
|
||||
}
|
||||
log.error("下载任务初始化失败:code={},message={}", result.getCode(), result.getMessage());
|
||||
}
|
||||
catch (ServiceException e) {
|
||||
log.error("下载任务完成接口错误", e.getMessage());
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/CommonAppDownloadCenterServiceImpl.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+74
-78
@@ -19,85 +19,81 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@EnableAsync
|
||||
public class CommonAppExportTaskServiceImpl
|
||||
extends AbstractImagStoreService
|
||||
implements ICommonAppExportTaskService {
|
||||
private static final Logger log = LoggerFactory.getLogger(CommonAppExportTaskServiceImpl.class);
|
||||
@Autowired
|
||||
private ICommonAppDownloadCenterService commonAppDownloadCenterService;
|
||||
@Autowired
|
||||
private ImgStorePersonService imgStorePersonService;
|
||||
@Autowired
|
||||
private CommonAppExportExecuteTask commonAppExportExecuteTask;
|
||||
@Autowired
|
||||
private CommonDownloadDataConfig commonAppRecordDataConfig;
|
||||
@Autowired
|
||||
private ComponentInnerKafkaConfig componentInnerKafkaConfig;
|
||||
String fileName = "人员信息";
|
||||
String orgFileName = "机构信息";
|
||||
String labelFileName = "标签信息";
|
||||
|
||||
public String add(CloudwalkCallContext cloudwalkCallContext, ExportRecordTaskParam task) throws ServiceException {
|
||||
String name = this.createFileName(this.fileName);
|
||||
this.logger.info("创建下载任务,任务文件名称:name = {}", (Object)name);
|
||||
this.updateCloudwalkContext(cloudwalkCallContext, task);
|
||||
String fileId = this.commonAppDownloadCenterService.createDownload(cloudwalkCallContext, name, task.getBusinessId());
|
||||
task.setFileId(fileId);
|
||||
task.setFileName(name);
|
||||
this.commonAppExportExecuteTask.execute(task, cloudwalkCallContext);
|
||||
return fileId;
|
||||
}
|
||||
|
||||
public String addOrgExport(CloudwalkCallContext context, ExportOrgTaskParam task) throws ServiceException {
|
||||
String name = this.createFileName(this.orgFileName);
|
||||
this.logger.info("创建下载任务,任务文件名称:name = {}", (Object)name);
|
||||
ExportRecordTaskParam taskParam = new ExportRecordTaskParam();
|
||||
taskParam.setBusinessId(task.getBusinessId());
|
||||
this.updateCloudwalkContext(context, taskParam);
|
||||
String fileId = this.commonAppDownloadCenterService.createDownload(context, name, task.getBusinessId());
|
||||
task.setFileId(fileId);
|
||||
task.setFileName(name);
|
||||
this.commonAppExportExecuteTask.executeOrg(task, context);
|
||||
return fileId;
|
||||
}
|
||||
|
||||
public String addLabelExport(CloudwalkCallContext context, ExportLabelTaskParam task) throws ServiceException {
|
||||
String name = this.createFileName(this.labelFileName);
|
||||
this.logger.info("创建下载任务,任务文件名称:name = {}", (Object)name);
|
||||
ExportRecordTaskParam taskParam = new ExportRecordTaskParam();
|
||||
taskParam.setBusinessId(task.getBusinessId());
|
||||
this.updateCloudwalkContext(context, taskParam);
|
||||
String fileId = this.commonAppDownloadCenterService.createDownload(context, name, task.getBusinessId());
|
||||
task.setFileId(fileId);
|
||||
task.setFileName(name);
|
||||
this.commonAppExportExecuteTask.executeLabel(task, context);
|
||||
return fileId;
|
||||
}
|
||||
|
||||
private void updateCloudwalkContext(CloudwalkCallContext cloudwalkCallContext, ExportRecordTaskParam task) {
|
||||
cloudwalkCallContext.setServiceCode(this.componentInnerKafkaConfig.getServiceCode());
|
||||
UserContext userContext = new UserContext();
|
||||
userContext.setCaller(cloudwalkCallContext.getUser().getCaller());
|
||||
userContext.setCallerName(cloudwalkCallContext.getUser().getCallerName());
|
||||
cloudwalkCallContext.setUser(userContext);
|
||||
CompanyContext companyContext = new CompanyContext();
|
||||
companyContext.setCompanyId(task.getBusinessId());
|
||||
cloudwalkCallContext.setCompany(companyContext);
|
||||
}
|
||||
|
||||
private String createFileName(String type) {
|
||||
StringBuilder nameBuilder = new StringBuilder();
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
nameBuilder.append(type);
|
||||
nameBuilder.append("_");
|
||||
nameBuilder.append(now.getYear()).append(now.getMonthValue()).append(now.getDayOfMonth());
|
||||
nameBuilder.append("_");
|
||||
nameBuilder.append(now.getHour()).append(now.getMinute()).append(now.getSecond());
|
||||
return nameBuilder.toString();
|
||||
}
|
||||
public class CommonAppExportTaskServiceImpl extends AbstractImagStoreService implements ICommonAppExportTaskService {
|
||||
private static final Logger log = LoggerFactory.getLogger(CommonAppExportTaskServiceImpl.class);
|
||||
@Autowired
|
||||
private ICommonAppDownloadCenterService commonAppDownloadCenterService;
|
||||
@Autowired
|
||||
private ImgStorePersonService imgStorePersonService;
|
||||
@Autowired
|
||||
private CommonAppExportExecuteTask commonAppExportExecuteTask;
|
||||
@Autowired
|
||||
private CommonDownloadDataConfig commonAppRecordDataConfig;
|
||||
@Autowired
|
||||
private ComponentInnerKafkaConfig componentInnerKafkaConfig;
|
||||
String fileName = "人员信息";
|
||||
String orgFileName = "机构信息";
|
||||
String labelFileName = "标签信息";
|
||||
public String add(CloudwalkCallContext cloudwalkCallContext, ExportRecordTaskParam task) throws ServiceException {
|
||||
String name = createFileName(this.fileName);
|
||||
this.logger.info("创建下载任务,任务文件名称:name = {}", name);
|
||||
updateCloudwalkContext(cloudwalkCallContext, task);
|
||||
String fileId = this.commonAppDownloadCenterService.createDownload(cloudwalkCallContext, name, task.getBusinessId());
|
||||
task.setFileId(fileId);
|
||||
task.setFileName(name);
|
||||
this.commonAppExportExecuteTask.execute(task, cloudwalkCallContext);
|
||||
return fileId;
|
||||
}
|
||||
public String addOrgExport(CloudwalkCallContext context, ExportOrgTaskParam task) throws ServiceException {
|
||||
String name = createFileName(this.orgFileName);
|
||||
this.logger.info("创建下载任务,任务文件名称:name = {}", name);
|
||||
ExportRecordTaskParam taskParam = new ExportRecordTaskParam();
|
||||
taskParam.setBusinessId(task.getBusinessId());
|
||||
updateCloudwalkContext(context, taskParam);
|
||||
String fileId = this.commonAppDownloadCenterService.createDownload(context, name, task.getBusinessId());
|
||||
task.setFileId(fileId);
|
||||
task.setFileName(name);
|
||||
this.commonAppExportExecuteTask.executeOrg(task, context);
|
||||
return fileId;
|
||||
}
|
||||
public String addLabelExport(CloudwalkCallContext context, ExportLabelTaskParam task) throws ServiceException {
|
||||
String name = createFileName(this.labelFileName);
|
||||
this.logger.info("创建下载任务,任务文件名称:name = {}", name);
|
||||
ExportRecordTaskParam taskParam = new ExportRecordTaskParam();
|
||||
taskParam.setBusinessId(task.getBusinessId());
|
||||
updateCloudwalkContext(context, taskParam);
|
||||
String fileId = this.commonAppDownloadCenterService.createDownload(context, name, task.getBusinessId());
|
||||
task.setFileId(fileId);
|
||||
task.setFileName(name);
|
||||
this.commonAppExportExecuteTask.executeLabel(task, context);
|
||||
return fileId;
|
||||
}
|
||||
private void updateCloudwalkContext(CloudwalkCallContext cloudwalkCallContext, ExportRecordTaskParam task) {
|
||||
cloudwalkCallContext.setServiceCode(this.componentInnerKafkaConfig.getServiceCode());
|
||||
UserContext userContext = new UserContext();
|
||||
userContext.setCaller(cloudwalkCallContext.getUser().getCaller());
|
||||
userContext.setCallerName(cloudwalkCallContext.getUser().getCallerName());
|
||||
cloudwalkCallContext.setUser(userContext);
|
||||
CompanyContext companyContext = new CompanyContext();
|
||||
companyContext.setCompanyId(task.getBusinessId());
|
||||
cloudwalkCallContext.setCompany(companyContext);
|
||||
}
|
||||
private String createFileName(String type) {
|
||||
StringBuilder nameBuilder = new StringBuilder();
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
nameBuilder.append(type);
|
||||
nameBuilder.append("_");
|
||||
nameBuilder.append(now.getYear()).append(now.getMonthValue()).append(now.getDayOfMonth());
|
||||
nameBuilder.append("_");
|
||||
nameBuilder.append(now.getHour()).append(now.getMinute()).append(now.getSecond());
|
||||
return nameBuilder.toString();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/CommonAppExportTaskServiceImpl.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+38
-41
@@ -13,47 +13,44 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class CommonAppFileManageServiceImpl
|
||||
implements ICommonAppFileManageService {
|
||||
private static final Logger log = LoggerFactory.getLogger(CommonAppFileManageServiceImpl.class);
|
||||
@Autowired
|
||||
private FilePartManager filePartManager;
|
||||
|
||||
public FilePartInitResult filePartInit(String fileName) {
|
||||
FilePartInitResult result = new FilePartInitResult();
|
||||
PartInitDTO dto = new PartInitDTO();
|
||||
dto.setFileName(fileName);
|
||||
PartInitResultDTO partInitResultDTO = new PartInitResultDTO();
|
||||
try {
|
||||
partInitResultDTO = this.filePartManager.init(dto);
|
||||
}
|
||||
catch (DavinciServiceException e) {
|
||||
log.error("分片上传文件初始化接口错误 request = {}", (Object)fileName);
|
||||
}
|
||||
BeanUtils.copyProperties((Object)partInitResultDTO, (Object)result);
|
||||
return result;
|
||||
}
|
||||
|
||||
public FilePartInitResult filePartAppend(FilePartAppendPara para) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public String filePartFinish(FilePartFinishPara para) {
|
||||
PartFinishDTO partFinishDTO = new PartFinishDTO();
|
||||
partFinishDTO.setFilePath(para.getFilePath());
|
||||
partFinishDTO.setFileSize(para.getFileSize());
|
||||
partFinishDTO.setReturnType(para.getReturnType());
|
||||
partFinishDTO.setUploadId(para.getUploadId());
|
||||
try {
|
||||
return this.filePartManager.finish(partFinishDTO);
|
||||
}
|
||||
catch (DavinciServiceException e) {
|
||||
log.error("分片上传文件完成接口错误{}:{}", (Object)((Object)((Object)e)).getClass().getName(), (Object)e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
public class CommonAppFileManageServiceImpl implements ICommonAppFileManageService {
|
||||
private static final Logger log = LoggerFactory.getLogger(CommonAppFileManageServiceImpl.class);
|
||||
@Autowired
|
||||
private FilePartManager filePartManager;
|
||||
public FilePartInitResult filePartInit(String fileName) {
|
||||
FilePartInitResult result = new FilePartInitResult();
|
||||
PartInitDTO dto = new PartInitDTO();
|
||||
dto.setFileName(fileName);
|
||||
PartInitResultDTO partInitResultDTO = new PartInitResultDTO();
|
||||
try {
|
||||
partInitResultDTO = this.filePartManager.init(dto);
|
||||
} catch (DavinciServiceException e) {
|
||||
log.error("分片上传文件初始化接口错误 request = {}", fileName);
|
||||
}
|
||||
BeanUtils.copyProperties(partInitResultDTO, result);
|
||||
return result;
|
||||
}
|
||||
public FilePartInitResult filePartAppend(FilePartAppendPara para) {
|
||||
return null;
|
||||
}
|
||||
public String filePartFinish(FilePartFinishPara para) {
|
||||
PartFinishDTO partFinishDTO = new PartFinishDTO();
|
||||
partFinishDTO.setFilePath(para.getFilePath());
|
||||
partFinishDTO.setFileSize(para.getFileSize());
|
||||
partFinishDTO.setReturnType(para.getReturnType());
|
||||
partFinishDTO.setUploadId(para.getUploadId());
|
||||
try {
|
||||
return this.filePartManager.finish(partFinishDTO);
|
||||
} catch (DavinciServiceException e) {
|
||||
log.error("分片上传文件完成接口错误{}:{}", e.getClass().getName(), e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/CommonAppFileManageServiceImpl.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+98
-106
@@ -14,6 +14,7 @@ import cn.cloudwalk.intelligent.davinci.storage.manager.FileStorageManager;
|
||||
import cn.cloudwalk.service.organization.common.MultipartFileUtils;
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
@@ -21,114 +22,105 @@ import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@Service
|
||||
public class CommonCwosStorageServiceImpl
|
||||
implements ICommonStorageService {
|
||||
private static final Logger log = LoggerFactory.getLogger(CommonCwosStorageServiceImpl.class);
|
||||
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
@Value(value="${cloudwalk.component.file.urlPrefix}")
|
||||
private String fileUrlPrefix;
|
||||
@Value(value="${cloudwalk.common-app.download.shardingSize}")
|
||||
private Integer shardingSize;
|
||||
@Autowired
|
||||
private FileStorageManager fileStorageManager;
|
||||
@Autowired
|
||||
private FilePartManager filePartManager;
|
||||
@Autowired
|
||||
private ICommonAppFileManageService iCommonAppFileManageService;
|
||||
@Autowired
|
||||
private UUIDSerial uuidSerial;
|
||||
|
||||
public String getPrefix() {
|
||||
return this.fileUrlPrefix;
|
||||
}
|
||||
|
||||
public String getImgUrl(String path) {
|
||||
return this.fileUrlPrefix + path;
|
||||
}
|
||||
|
||||
public String saveFile(String name, byte[] bytes) {
|
||||
MultipartFile mfile = MultipartFileUtils.getMultipartFile(name, bytes);
|
||||
try {
|
||||
return this.fileStorageManager.fileUpload(mfile);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("上传文件错误 request = {}", (Object)mfile);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean deleteFile(String path) {
|
||||
FileRemoveDTO fileRemoveDTO = new FileRemoveDTO();
|
||||
ArrayList<String> fileList = new ArrayList<String>();
|
||||
fileList.add(path);
|
||||
fileRemoveDTO.setFileList(fileList);
|
||||
try {
|
||||
this.fileStorageManager.remove(fileRemoveDTO);
|
||||
}
|
||||
catch (DavinciServiceException e) {
|
||||
this.logger.error("删除文件失败 request = {}", (Object)fileRemoveDTO);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public String saveImg(byte[] bytes) {
|
||||
return this.saveFile(this.generateJpgName(), bytes);
|
||||
}
|
||||
|
||||
public String generateJpgName() {
|
||||
return File.separatorChar + "common" + File.separatorChar + TimeUtils.getCurrentTime((TimeUtils.FormatterEnums)TimeUtils.FormatterEnums.FORMAT) + File.separatorChar + this.uuidSerial.uuid() + ".jpg";
|
||||
}
|
||||
|
||||
public String generateFileName(String ext) {
|
||||
return File.separatorChar + "common" + File.separatorChar + TimeUtils.getCurrentTime((TimeUtils.FormatterEnums)TimeUtils.FormatterEnums.FORMAT) + File.separatorChar + this.uuidSerial.uuid() + "." + ext;
|
||||
}
|
||||
|
||||
public String saveFileBySharding(String fileName, byte[] bytes) {
|
||||
FilePartInitResult resp = this.iCommonAppFileManageService.filePartInit(fileName);
|
||||
if (resp == null) {
|
||||
this.logger.info("分片上传文件初始化返回值为空");
|
||||
return null;
|
||||
}
|
||||
int byteSize = bytes.length;
|
||||
int count = byteSize / this.shardingSize + 1;
|
||||
for (int i = 0; i < count; ++i) {
|
||||
byte[] tmpByte = null;
|
||||
if (i + 1 == count) {
|
||||
tmpByte = new byte[byteSize - i * this.shardingSize];
|
||||
System.arraycopy(bytes, i * this.shardingSize, tmpByte, 0, tmpByte.length);
|
||||
} else {
|
||||
tmpByte = new byte[this.shardingSize.intValue()];
|
||||
System.arraycopy(bytes, i * this.shardingSize, tmpByte, 0, tmpByte.length);
|
||||
}
|
||||
this.uploadFileBySharding(tmpByte, resp.getFilePath(), resp.getUploadId(), fileName, String.valueOf(i));
|
||||
}
|
||||
String filePath = this.filePartFinish(bytes, resp);
|
||||
if (filePath == null) {
|
||||
this.logger.info("分片上传文件完成接口返回值为空");
|
||||
return null;
|
||||
}
|
||||
this.logger.info("分片上传文件完成接口返回值 filePath = {}", (Object)filePath);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
private String filePartFinish(byte[] bytes, FilePartInitResult resp) {
|
||||
FilePartFinishPara para = new FilePartFinishPara();
|
||||
BeanUtils.copyProperties((Object)resp, (Object)para);
|
||||
para.setFileSize(Long.valueOf(bytes.length));
|
||||
para.setReturnType(Integer.valueOf(0));
|
||||
return this.iCommonAppFileManageService.filePartFinish(para);
|
||||
}
|
||||
|
||||
private void uploadFileBySharding(byte[] bytes, String filePath, String uploadId, String fileName, String partNumber) {
|
||||
MultipartFile mfile = MultipartFileUtils.getMultipartFile(fileName, bytes);
|
||||
try {
|
||||
PartInitResultDTO partInitResultDTO = this.filePartManager.append(filePath, Integer.valueOf(partNumber), uploadId, mfile);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("分片更新文件错误{}:{}", (Object)e.getClass().getName(), (Object)e.getMessage());
|
||||
}
|
||||
}
|
||||
private static final Logger log = LoggerFactory.getLogger(CommonCwosStorageServiceImpl.class);
|
||||
protected final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
@Value("${cloudwalk.component.file.urlPrefix}")
|
||||
private String fileUrlPrefix;
|
||||
@Value("${cloudwalk.common-app.download.shardingSize}")
|
||||
private Integer shardingSize;
|
||||
@Autowired
|
||||
private FileStorageManager fileStorageManager;
|
||||
@Autowired
|
||||
private FilePartManager filePartManager;
|
||||
@Autowired
|
||||
private ICommonAppFileManageService iCommonAppFileManageService;
|
||||
@Autowired
|
||||
private UUIDSerial uuidSerial;
|
||||
public String getPrefix() {
|
||||
return this.fileUrlPrefix;
|
||||
}
|
||||
public String getImgUrl(String path) {
|
||||
return this.fileUrlPrefix + path;
|
||||
}
|
||||
public String saveFile(String name, byte[] bytes) {
|
||||
MultipartFile mfile = MultipartFileUtils.getMultipartFile(name, bytes);
|
||||
try {
|
||||
return this.fileStorageManager.fileUpload(mfile);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("上传文件错误 request = {}", mfile);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
public boolean deleteFile(String path) {
|
||||
FileRemoveDTO fileRemoveDTO = new FileRemoveDTO();
|
||||
List<String> fileList = new ArrayList<>();
|
||||
fileList.add(path);
|
||||
fileRemoveDTO.setFileList(fileList);
|
||||
try {
|
||||
this.fileStorageManager.remove(fileRemoveDTO);
|
||||
} catch (DavinciServiceException e) {
|
||||
this.logger.error("删除文件失败 request = {}", fileRemoveDTO);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
public String saveImg(byte[] bytes) {
|
||||
return saveFile(generateJpgName(), bytes);
|
||||
}
|
||||
public String generateJpgName() {
|
||||
return File.separatorChar + "common" + File.separatorChar + TimeUtils.getCurrentTime(TimeUtils.FormatterEnums.FORMAT) + File.separatorChar + this.uuidSerial.uuid() + ".jpg";
|
||||
}
|
||||
public String generateFileName(String ext) {
|
||||
return File.separatorChar + "common" + File.separatorChar + TimeUtils.getCurrentTime(TimeUtils.FormatterEnums.FORMAT) + File.separatorChar + this.uuidSerial.uuid() + "." + ext;
|
||||
}
|
||||
public String saveFileBySharding(String fileName, byte[] bytes) {
|
||||
FilePartInitResult resp = this.iCommonAppFileManageService.filePartInit(fileName);
|
||||
if (resp == null) {
|
||||
this.logger.info("分片上传文件初始化返回值为空");
|
||||
return null;
|
||||
}
|
||||
int byteSize = bytes.length;
|
||||
int count = byteSize / this.shardingSize.intValue() + 1;
|
||||
for (int i = 0; i < count; i++) {
|
||||
byte[] tmpByte = null;
|
||||
if (i + 1 == count) {
|
||||
tmpByte = new byte[byteSize - i * this.shardingSize.intValue()];
|
||||
System.arraycopy(bytes, i * this.shardingSize.intValue(), tmpByte, 0, tmpByte.length);
|
||||
} else {
|
||||
tmpByte = new byte[this.shardingSize.intValue()];
|
||||
System.arraycopy(bytes, i * this.shardingSize.intValue(), tmpByte, 0, tmpByte.length);
|
||||
}
|
||||
uploadFileBySharding(tmpByte, resp.getFilePath(), resp.getUploadId(), fileName, String.valueOf(i));
|
||||
}
|
||||
String filePath = filePartFinish(bytes, resp);
|
||||
if (filePath == null) {
|
||||
this.logger.info("分片上传文件完成接口返回值为空");
|
||||
return null;
|
||||
}
|
||||
this.logger.info("分片上传文件完成接口返回值 filePath = {}", filePath);
|
||||
return filePath;
|
||||
}
|
||||
private String filePartFinish(byte[] bytes, FilePartInitResult resp) {
|
||||
FilePartFinishPara para = new FilePartFinishPara();
|
||||
BeanUtils.copyProperties(resp, para);
|
||||
para.setFileSize(Long.valueOf(bytes.length));
|
||||
para.setReturnType(Integer.valueOf(0));
|
||||
return this.iCommonAppFileManageService.filePartFinish(para);
|
||||
}
|
||||
private void uploadFileBySharding(byte[] bytes, String filePath, String uploadId, String fileName, String partNumber) {
|
||||
MultipartFile mfile = MultipartFileUtils.getMultipartFile(fileName, bytes);
|
||||
try {
|
||||
PartInitResultDTO partInitResultDTO = this.filePartManager.append(filePath, Integer.valueOf(partNumber), uploadId, mfile);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("分片更新文件错误{}:{}", e.getClass().getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/CommonCwosStorageServiceImpl.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+287
-288
@@ -3,10 +3,12 @@ package cn.cloudwalk.service.organization.service;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.param.CoreAppDeviceAddParam;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.param.CoreAppDeviceParam;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.param.CoreDeviceQueryParam;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.result.AtomicDeviceGetResult;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.service.AtomicDeviceService;
|
||||
import cn.cloudwalk.client.organization.common.enums.RegistryTypeEnum;
|
||||
import cn.cloudwalk.client.organization.common.enums.StatusEnum;
|
||||
import cn.cloudwalk.client.organization.service.store.param.AddPersonRegistryParam;
|
||||
import cn.cloudwalk.client.organization.service.store.param.BindPropertyParam;
|
||||
import cn.cloudwalk.client.organization.service.store.param.QueryPersonRegistryParam;
|
||||
import cn.cloudwalk.client.organization.service.store.result.LabelResult;
|
||||
import cn.cloudwalk.client.organization.service.store.result.OrganizationResult;
|
||||
@@ -19,6 +21,8 @@ import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.cloud.serial.UUIDSerial;
|
||||
import cn.cloudwalk.cloud.utils.BeanCopyUtils;
|
||||
import cn.cloudwalk.data.organization.dto.PersonRegistryDTO;
|
||||
import cn.cloudwalk.data.organization.entity.Label;
|
||||
import cn.cloudwalk.data.organization.entity.Organization;
|
||||
import cn.cloudwalk.data.organization.entity.PersonRegistry;
|
||||
import cn.cloudwalk.data.organization.entity.PersonRegistryDevice;
|
||||
import cn.cloudwalk.data.organization.entity.PersonRegistryProperties;
|
||||
@@ -32,7 +36,6 @@ import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import cn.cloudwalk.service.organization.service.feign.DeviceAppFeignClient;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.google.common.collect.Lists;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
@@ -44,294 +47,290 @@ import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springside.modules.utils.Collections3;
|
||||
|
||||
@Service
|
||||
public class CommonPersonRegistryService
|
||||
extends AbstractImagStoreService {
|
||||
@Resource
|
||||
private UUIDSerial uuidSerial;
|
||||
@Resource
|
||||
private AtomicDeviceService atomicDeviceService;
|
||||
@Resource
|
||||
private DeviceAppFeignClient deviceAppFeignClient;
|
||||
@Resource
|
||||
private ApplicationFeignClient applicationFeignClient;
|
||||
@Resource
|
||||
private PersonRegistryMapper personRegistryMapper;
|
||||
@Resource
|
||||
private ImgStoreOrganizationMapper imgStoreOrganizationMapper;
|
||||
@Resource
|
||||
private ImgStoreLabelMapper imgStoreLabelMapper;
|
||||
@Resource
|
||||
private PersonRegistryPropertiesMapper personRegistryPropertiesMapper;
|
||||
@Resource
|
||||
private PersonRegistryDeviceMapper personRegistryDeviceMapper;
|
||||
@Value(value="${cloudwalk.component-organization.kafka.service-code}")
|
||||
private String serviceCode;
|
||||
|
||||
public PersonRegistry getByBusinessAndType(String businessId, Integer type) {
|
||||
PersonRegistryDTO queryPersonRegistry = new PersonRegistryDTO();
|
||||
queryPersonRegistry.setBusinessId(businessId);
|
||||
queryPersonRegistry.setType(type);
|
||||
List personRegistryList = this.personRegistryMapper.selectByCondition(queryPersonRegistry);
|
||||
if (CollectionUtils.isEmpty((Collection)personRegistryList)) {
|
||||
return null;
|
||||
}
|
||||
return (PersonRegistry)personRegistryList.get(0);
|
||||
}
|
||||
|
||||
public CloudwalkResult<PersonRegistry> getResultByBusinessAndType(String businessId, Integer type) throws ServiceException {
|
||||
PersonRegistryDTO queryPersonRegistry = new PersonRegistryDTO();
|
||||
queryPersonRegistry.setBusinessId(businessId);
|
||||
queryPersonRegistry.setType(type);
|
||||
List personRegistryList = this.personRegistryMapper.selectByCondition(queryPersonRegistry);
|
||||
if (CollectionUtils.isEmpty((Collection)personRegistryList)) {
|
||||
this.logger.warn("该租户不存在人员注册配置,租户ID:[{}]", (Object)businessId);
|
||||
throw new ServiceException("53014517", this.getMessage("53014517"));
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
public void insertPersonRegistry(String id, AddPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
PersonRegistry personRegistry = (PersonRegistry)BeanCopyUtils.copyProperties((Object)param, PersonRegistry.class);
|
||||
personRegistry.setId(id);
|
||||
personRegistry.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
personRegistry.setCreateUserId(context.getUser().getCaller());
|
||||
personRegistry.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
personRegistry.setLastUpdateUserId(context.getUser().getCaller());
|
||||
int result = this.personRegistryMapper.insertSelective(personRegistry);
|
||||
if (result == 0) {
|
||||
this.logger.warn("新增人员注册配置失败,人员注册配置:[{}]", (Object)JSONObject.toJSONString((Object)personRegistry));
|
||||
throw new ServiceException("53014515", this.getMessage("53014515"));
|
||||
}
|
||||
}
|
||||
|
||||
public void updatePersonRegistry(AddPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
PersonRegistry personRegistry = (PersonRegistry)BeanCopyUtils.copyProperties((Object)param, PersonRegistry.class);
|
||||
personRegistry.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
personRegistry.setLastUpdateUserId(context.getUser().getCaller());
|
||||
int result = this.personRegistryMapper.updateByPrimaryKeySelective(personRegistry);
|
||||
if (result == 0) {
|
||||
this.logger.warn("修改人员注册配置失败,人员注册配置:[{}]", (Object)JSONObject.toJSONString((Object)personRegistry));
|
||||
throw new ServiceException("53014516", this.getMessage("53014516"));
|
||||
}
|
||||
}
|
||||
|
||||
public void batchInsertPersonRegistryProperty(String id, AddPersonRegistryParam param) {
|
||||
ArrayList propertyList = Lists.newArrayList();
|
||||
if (Objects.equals(RegistryTypeEnum.CERT_REGISTRY.getValue(), param.getType())) {
|
||||
param.getPropertyList().forEach(propertyParam -> {
|
||||
PersonRegistryProperties property = new PersonRegistryProperties();
|
||||
property.setId(this.uuidSerial.uuid());
|
||||
property.setRegistryId(id);
|
||||
property.setPersonPropertyId(propertyParam.getBindPropertyId());
|
||||
property.setBindPropertyCode(propertyParam.getProperty());
|
||||
propertyList.add(property);
|
||||
});
|
||||
} else {
|
||||
param.getPropertyIdList().forEach(propertyId -> {
|
||||
PersonRegistryProperties property = new PersonRegistryProperties();
|
||||
property.setId(this.uuidSerial.uuid());
|
||||
property.setRegistryId(id);
|
||||
property.setPersonPropertyId(propertyId);
|
||||
propertyList.add(property);
|
||||
});
|
||||
}
|
||||
this.personRegistryPropertiesMapper.batchInsert((List)propertyList);
|
||||
}
|
||||
|
||||
public void batchUpdatePersonRegistryProperty(AddPersonRegistryParam param) {
|
||||
this.personRegistryPropertiesMapper.delete(param.getId(), null);
|
||||
ArrayList propertyList = Lists.newArrayList();
|
||||
if (Objects.equals(RegistryTypeEnum.CERT_REGISTRY.getValue(), param.getType())) {
|
||||
param.getPropertyList().forEach(propertyParam -> {
|
||||
PersonRegistryProperties property = new PersonRegistryProperties();
|
||||
property.setId(this.uuidSerial.uuid());
|
||||
property.setRegistryId(param.getId());
|
||||
property.setPersonPropertyId(propertyParam.getBindPropertyId());
|
||||
property.setBindPropertyCode(propertyParam.getProperty());
|
||||
propertyList.add(property);
|
||||
});
|
||||
} else {
|
||||
param.getPropertyIdList().forEach(propertyId -> {
|
||||
PersonRegistryProperties property = new PersonRegistryProperties();
|
||||
property.setId(this.uuidSerial.uuid());
|
||||
property.setRegistryId(param.getId());
|
||||
property.setPersonPropertyId(propertyId);
|
||||
propertyList.add(property);
|
||||
});
|
||||
}
|
||||
this.personRegistryPropertiesMapper.batchInsert((List)propertyList);
|
||||
}
|
||||
|
||||
public void batchInsertPersonRegistryDevice(String id, AddPersonRegistryParam param, CloudwalkCallContext context, Boolean isBindAppDevice) throws ServiceException {
|
||||
if (!CollectionUtils.isEmpty((Collection)param.getDeviceCodeList())) {
|
||||
ArrayList deviceList = Lists.newArrayListWithCapacity((int)param.getDeviceCodeList().size());
|
||||
param.getDeviceCodeList().forEach(deviceCode -> {
|
||||
PersonRegistryDevice device = new PersonRegistryDevice();
|
||||
device.setId(this.uuidSerial.uuid());
|
||||
device.setRegistryId(id);
|
||||
device.setDeviceCode(deviceCode);
|
||||
deviceList.add(device);
|
||||
});
|
||||
this.personRegistryDeviceMapper.batchInsert((List)deviceList);
|
||||
if (isBindAppDevice.booleanValue()) {
|
||||
this.bindApplicationDevice(this.getApplicationId(param.getBusinessId()), this.getDeviceIdList(deviceList, param.getBusinessId(), context));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void batchUpdatePersonRegistryDevice(AddPersonRegistryParam param, CloudwalkCallContext context, Boolean isBindAppDevice) throws ServiceException {
|
||||
List dbDeviceList = this.personRegistryDeviceMapper.select(param.getId(), null);
|
||||
ArrayList deviceList = null;
|
||||
this.personRegistryDeviceMapper.delete(param.getId(), null);
|
||||
if (!CollectionUtils.isEmpty((Collection)param.getDeviceCodeList())) {
|
||||
deviceList = Lists.newArrayListWithCapacity((int)param.getDeviceCodeList().size());
|
||||
for (String deviceCode : param.getDeviceCodeList()) {
|
||||
PersonRegistryDevice device = new PersonRegistryDevice();
|
||||
device.setId(this.uuidSerial.uuid());
|
||||
device.setRegistryId(param.getId());
|
||||
device.setDeviceCode(deviceCode);
|
||||
deviceList.add(device);
|
||||
}
|
||||
this.personRegistryDeviceMapper.batchInsert((List)deviceList);
|
||||
}
|
||||
if (isBindAppDevice.booleanValue()) {
|
||||
this.unbindAppicationDevice(this.getApplicationId(param.getBusinessId()), this.getDeviceIdList(dbDeviceList, param.getBusinessId(), context));
|
||||
this.bindApplicationDevice(this.getApplicationId(param.getBusinessId()), this.getDeviceIdList(deviceList, param.getBusinessId(), context));
|
||||
}
|
||||
}
|
||||
|
||||
public void validateOrg(AddPersonRegistryParam param) throws ServiceException {
|
||||
List dbOrganizationList;
|
||||
if (StringUtils.isNotBlank((CharSequence)param.getOrganizationIds()) && (CollectionUtils.isEmpty((Collection)(dbOrganizationList = this.imgStoreOrganizationMapper.getOrgByIds(Arrays.asList(param.getOrganizationIds().split(",")), param.getBusinessId()))) || dbOrganizationList.size() != param.getOrganizationIds().split(",").length)) {
|
||||
this.logger.warn("注册默认组织不属于该租户,注册默认组织列表:[{}]", (Object)param.getOrganizationIds());
|
||||
throw new ServiceException("53014512", this.getMessage("53014512"));
|
||||
}
|
||||
}
|
||||
|
||||
public void validateLabel(AddPersonRegistryParam param) throws ServiceException {
|
||||
List dbLabelList;
|
||||
if (StringUtils.isNotBlank((CharSequence)param.getLabelIds()) && (CollectionUtils.isEmpty((Collection)(dbLabelList = this.imgStoreLabelMapper.selectByIds(param.getBusinessId(), Arrays.asList(param.getLabelIds().split(","))))) || dbLabelList.size() != param.getLabelIds().split(",").length)) {
|
||||
this.logger.warn("注册默认标签不属于该租户,注册默认标签列表:[{}]", (Object)param.getLabelIds());
|
||||
throw new ServiceException("53014513", this.getMessage("53014513"));
|
||||
}
|
||||
}
|
||||
|
||||
public void validateDevice(AddPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
if (!CollectionUtils.isEmpty((Collection)param.getDeviceCodeList())) {
|
||||
CoreDeviceQueryParam coreDeviceQueryParam = new CoreDeviceQueryParam();
|
||||
coreDeviceQueryParam.setBusinessId(param.getBusinessId());
|
||||
coreDeviceQueryParam.setDeviceCodes(param.getDeviceCodeList());
|
||||
CloudwalkResult deviceGetResult = this.atomicDeviceService.list(coreDeviceQueryParam, context);
|
||||
if (CollectionUtils.isEmpty((Collection)((Collection)deviceGetResult.getData())) || ((List)deviceGetResult.getData()).size() != param.getDeviceCodeList().size()) {
|
||||
this.logger.warn("设备不属于该租户,设备列表:[{}]", (Object)param.getDeviceCodeList());
|
||||
throw new ServiceException("53014514", this.getMessage("53014514"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public List<String> getDeviceIdList(List<PersonRegistryDevice> deviceList, String businessId, CloudwalkCallContext context) throws ServiceException {
|
||||
if (!CollectionUtils.isEmpty(deviceList)) {
|
||||
List deviceCodeList = Collections3.extractToList(deviceList, (String)"deviceCode");
|
||||
CoreDeviceQueryParam coreDeviceQueryParam = new CoreDeviceQueryParam();
|
||||
coreDeviceQueryParam.setBusinessId(businessId);
|
||||
coreDeviceQueryParam.setDeviceCodes(deviceCodeList);
|
||||
CloudwalkResult deviceGetResult = this.atomicDeviceService.list(coreDeviceQueryParam, context);
|
||||
if (deviceGetResult.isSuccess()) {
|
||||
return Collections3.extractToList((Collection)((Collection)deviceGetResult.getData()), (String)"id");
|
||||
}
|
||||
}
|
||||
return Lists.newArrayList();
|
||||
}
|
||||
|
||||
public void validateDevice(QueryPersonRegistryParam param, PersonRegistry personRegistry) throws ServiceException {
|
||||
if (StringUtils.isNotBlank((CharSequence)param.getDeviceCode())) {
|
||||
if (Objects.equals(personRegistry.getStatus(), StatusEnum.CLOSE.getValue())) {
|
||||
this.logger.warn("该设备未开启注册,租户ID:[{}],设备Code:[{}]", (Object)personRegistry.getBusinessId(), (Object)param.getDeviceCode());
|
||||
throw new ServiceException("53014518", this.getMessage("53014518"));
|
||||
}
|
||||
List dbPersonRegistryDeviceList = this.personRegistryDeviceMapper.select(personRegistry.getId(), Arrays.asList(param.getDeviceCode()));
|
||||
if (CollectionUtils.isEmpty((Collection)dbPersonRegistryDeviceList)) {
|
||||
this.logger.warn("该设备未注册,租户ID:[{}],设备Code:[{}]", (Object)personRegistry.getBusinessId(), (Object)param.getDeviceCode());
|
||||
throw new ServiceException("53014519", this.getMessage("53014519"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public PersonRegistryResult setOrg(PersonRegistry personRegistry, PersonRegistryResult result) {
|
||||
if (StringUtils.isNotBlank((CharSequence)personRegistry.getOrganizationIds())) {
|
||||
List dbOrgList = this.imgStoreOrganizationMapper.getOrgByIds(Arrays.asList(personRegistry.getOrganizationIds().split(",")), personRegistry.getBusinessId());
|
||||
ArrayList orgResultList = Lists.newArrayListWithCapacity((int)dbOrgList.size());
|
||||
dbOrgList.forEach(dbOrg -> {
|
||||
OrganizationResult orgResult = new OrganizationResult();
|
||||
orgResult.setId(dbOrg.getId());
|
||||
orgResult.setName(dbOrg.getName());
|
||||
orgResultList.add(orgResult);
|
||||
});
|
||||
result.setOrganizationList((List)orgResultList);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public PersonRegistryResult setLabel(PersonRegistry personRegistry, PersonRegistryResult result) {
|
||||
if (StringUtils.isNotBlank((CharSequence)personRegistry.getLabelIds())) {
|
||||
List dbLabelList = this.imgStoreLabelMapper.getLabelByIds(Arrays.asList(personRegistry.getLabelIds().split(",")), personRegistry.getBusinessId());
|
||||
ArrayList labelResultList = Lists.newArrayListWithCapacity((int)dbLabelList.size());
|
||||
dbLabelList.forEach(dbLabel -> {
|
||||
LabelResult labelResult = new LabelResult();
|
||||
labelResult.setId(dbLabel.getId());
|
||||
labelResult.setName(dbLabel.getName());
|
||||
labelResultList.add(labelResult);
|
||||
});
|
||||
result.setLabelList((List)labelResultList);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public String getApplicationId(String businessId) {
|
||||
ApplicationQueryParam queryParam = new ApplicationQueryParam();
|
||||
queryParam.setBusinessId(businessId);
|
||||
queryParam.setServiceCode(this.serviceCode);
|
||||
CloudwalkResult result = this.applicationFeignClient.query(queryParam);
|
||||
if (result.isSuccess() && !CollectionUtils.isEmpty((Collection)((Collection)result.getData()))) {
|
||||
return ((ApplicationResult)((List)result.getData()).get(0)).getId();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public Boolean bindApplicationDevice(String application, List<String> deviceIdList) throws ServiceException {
|
||||
AtomicInteger successCount = new AtomicInteger();
|
||||
if (!StringUtils.isBlank((CharSequence)application) && !CollectionUtils.isEmpty(deviceIdList)) {
|
||||
CoreAppDeviceAddParam param = null;
|
||||
for (String deviceId : deviceIdList) {
|
||||
param = new CoreAppDeviceAddParam();
|
||||
param.setApplicationId(application);
|
||||
param.setDeviceId(deviceId);
|
||||
CloudwalkResult<Boolean> result = this.deviceAppFeignClient.addAppDevice(param);
|
||||
if (!result.isSuccess()) continue;
|
||||
successCount.getAndIncrement();
|
||||
}
|
||||
return Objects.equals(successCount.get(), deviceIdList.size());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public Boolean unbindAppicationDevice(String application, List<String> deviceIdList) throws ServiceException {
|
||||
AtomicInteger successCount = new AtomicInteger();
|
||||
if (!StringUtils.isBlank((CharSequence)application) && !CollectionUtils.isEmpty(deviceIdList)) {
|
||||
CoreAppDeviceParam param = null;
|
||||
for (String deviceId : deviceIdList) {
|
||||
param = new CoreAppDeviceParam();
|
||||
param.setApplicationId(application);
|
||||
param.setDeviceId(deviceId);
|
||||
CloudwalkResult<Boolean> result = this.deviceAppFeignClient.deleteAppDevice(param);
|
||||
if (!result.isSuccess()) continue;
|
||||
successCount.getAndIncrement();
|
||||
}
|
||||
return Objects.equals(successCount.get(), deviceIdList.size());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
extends AbstractImagStoreService
|
||||
{
|
||||
@Resource
|
||||
private UUIDSerial uuidSerial;
|
||||
@Resource
|
||||
private AtomicDeviceService atomicDeviceService;
|
||||
@Resource
|
||||
private DeviceAppFeignClient deviceAppFeignClient;
|
||||
@Resource
|
||||
private ApplicationFeignClient applicationFeignClient;
|
||||
@Resource
|
||||
private PersonRegistryMapper personRegistryMapper;
|
||||
@Resource
|
||||
private ImgStoreOrganizationMapper imgStoreOrganizationMapper;
|
||||
@Resource
|
||||
private ImgStoreLabelMapper imgStoreLabelMapper;
|
||||
@Resource
|
||||
private PersonRegistryPropertiesMapper personRegistryPropertiesMapper;
|
||||
@Resource
|
||||
private PersonRegistryDeviceMapper personRegistryDeviceMapper;
|
||||
@Value("${cloudwalk.component-organization.kafka.service-code}")
|
||||
private String serviceCode;
|
||||
public PersonRegistry getByBusinessAndType(String businessId, Integer type) {
|
||||
PersonRegistryDTO queryPersonRegistry = new PersonRegistryDTO();
|
||||
queryPersonRegistry.setBusinessId(businessId);
|
||||
queryPersonRegistry.setType(type);
|
||||
List<PersonRegistry> personRegistryList = this.personRegistryMapper.selectByCondition(queryPersonRegistry);
|
||||
if (CollectionUtils.isEmpty(personRegistryList)) {
|
||||
return null;
|
||||
}
|
||||
return personRegistryList.get(0);
|
||||
}
|
||||
public CloudwalkResult<PersonRegistry> getResultByBusinessAndType(String businessId, Integer type) throws ServiceException {
|
||||
PersonRegistryDTO queryPersonRegistry = new PersonRegistryDTO();
|
||||
queryPersonRegistry.setBusinessId(businessId);
|
||||
queryPersonRegistry.setType(type);
|
||||
List<PersonRegistry> personRegistryList = this.personRegistryMapper.selectByCondition(queryPersonRegistry);
|
||||
if (CollectionUtils.isEmpty(personRegistryList)) {
|
||||
this.logger.warn("该租户不存在人员注册配置,租户ID:[{}]", businessId);
|
||||
throw new ServiceException("53014517", getMessage("53014517"));
|
||||
}
|
||||
return CloudwalkResult.success(personRegistryList.get(0));
|
||||
}
|
||||
public void insertPersonRegistry(String id, AddPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
PersonRegistry personRegistry = (PersonRegistry)BeanCopyUtils.copyProperties(param, PersonRegistry.class);
|
||||
personRegistry.setId(id);
|
||||
personRegistry.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
personRegistry.setCreateUserId(context.getUser().getCaller());
|
||||
personRegistry.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
personRegistry.setLastUpdateUserId(context.getUser().getCaller());
|
||||
int result = this.personRegistryMapper.insertSelective(personRegistry);
|
||||
if (result == 0) {
|
||||
this.logger.warn("新增人员注册配置失败,人员注册配置:[{}]", JSONObject.toJSONString(personRegistry));
|
||||
throw new ServiceException("53014515", getMessage("53014515"));
|
||||
}
|
||||
}
|
||||
public void updatePersonRegistry(AddPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
PersonRegistry personRegistry = (PersonRegistry)BeanCopyUtils.copyProperties(param, PersonRegistry.class);
|
||||
personRegistry.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
personRegistry.setLastUpdateUserId(context.getUser().getCaller());
|
||||
int result = this.personRegistryMapper.updateByPrimaryKeySelective(personRegistry);
|
||||
if (result == 0) {
|
||||
this.logger.warn("修改人员注册配置失败,人员注册配置:[{}]", JSONObject.toJSONString(personRegistry));
|
||||
throw new ServiceException("53014516", getMessage("53014516"));
|
||||
}
|
||||
}
|
||||
public void batchInsertPersonRegistryProperty(String id, AddPersonRegistryParam param) {
|
||||
List<PersonRegistryProperties> propertyList = Lists.newArrayList();
|
||||
if (Objects.equals(RegistryTypeEnum.CERT_REGISTRY.getValue(), param.getType())) {
|
||||
param.getPropertyList().forEach(propertyParam -> {
|
||||
PersonRegistryProperties property = new PersonRegistryProperties();
|
||||
property.setId(this.uuidSerial.uuid());
|
||||
property.setRegistryId(id);
|
||||
property.setPersonPropertyId(propertyParam.getBindPropertyId());
|
||||
property.setBindPropertyCode(propertyParam.getProperty());
|
||||
propertyList.add(property);
|
||||
});
|
||||
} else {
|
||||
param.getPropertyIdList().forEach(propertyId -> {
|
||||
PersonRegistryProperties property = new PersonRegistryProperties();
|
||||
property.setId(this.uuidSerial.uuid());
|
||||
property.setRegistryId(id);
|
||||
property.setPersonPropertyId(propertyId);
|
||||
propertyList.add(property);
|
||||
});
|
||||
}
|
||||
this.personRegistryPropertiesMapper.batchInsert(propertyList);
|
||||
}
|
||||
public void batchUpdatePersonRegistryProperty(AddPersonRegistryParam param) {
|
||||
this.personRegistryPropertiesMapper.delete(param.getId(), null);
|
||||
List<PersonRegistryProperties> propertyList = Lists.newArrayList();
|
||||
if (Objects.equals(RegistryTypeEnum.CERT_REGISTRY.getValue(), param.getType())) {
|
||||
param.getPropertyList().forEach(propertyParam -> {
|
||||
PersonRegistryProperties property = new PersonRegistryProperties();
|
||||
property.setId(this.uuidSerial.uuid());
|
||||
property.setRegistryId(param.getId());
|
||||
property.setPersonPropertyId(propertyParam.getBindPropertyId());
|
||||
property.setBindPropertyCode(propertyParam.getProperty());
|
||||
propertyList.add(property);
|
||||
});
|
||||
} else {
|
||||
param.getPropertyIdList().forEach(propertyId -> {
|
||||
PersonRegistryProperties property = new PersonRegistryProperties();
|
||||
property.setId(this.uuidSerial.uuid());
|
||||
property.setRegistryId(param.getId());
|
||||
property.setPersonPropertyId(propertyId);
|
||||
propertyList.add(property);
|
||||
});
|
||||
}
|
||||
this.personRegistryPropertiesMapper.batchInsert(propertyList);
|
||||
}
|
||||
public void batchInsertPersonRegistryDevice(String id, AddPersonRegistryParam param, CloudwalkCallContext context, Boolean isBindAppDevice) throws ServiceException {
|
||||
if (!CollectionUtils.isEmpty(param.getDeviceCodeList())) {
|
||||
List<PersonRegistryDevice> deviceList = Lists.newArrayListWithCapacity(param.getDeviceCodeList().size());
|
||||
param.getDeviceCodeList().forEach(deviceCode -> {
|
||||
PersonRegistryDevice device = new PersonRegistryDevice();
|
||||
device.setId(this.uuidSerial.uuid());
|
||||
device.setRegistryId(id);
|
||||
device.setDeviceCode(deviceCode);
|
||||
deviceList.add(device);
|
||||
});
|
||||
this.personRegistryDeviceMapper.batchInsert(deviceList);
|
||||
if (isBindAppDevice.booleanValue())
|
||||
{
|
||||
bindApplicationDevice(getApplicationId(param.getBusinessId()), getDeviceIdList(deviceList, param.getBusinessId(), context));
|
||||
}
|
||||
}
|
||||
}
|
||||
public void batchUpdatePersonRegistryDevice(AddPersonRegistryParam param, CloudwalkCallContext context, Boolean isBindAppDevice) throws ServiceException {
|
||||
List<PersonRegistryDevice> dbDeviceList = this.personRegistryDeviceMapper.select(param.getId(), null);
|
||||
List<PersonRegistryDevice> deviceList = null;
|
||||
this.personRegistryDeviceMapper.delete(param.getId(), null);
|
||||
if (!CollectionUtils.isEmpty(param.getDeviceCodeList())) {
|
||||
deviceList = Lists.newArrayListWithCapacity(param.getDeviceCodeList().size());
|
||||
for (String deviceCode : param.getDeviceCodeList()) {
|
||||
PersonRegistryDevice device = new PersonRegistryDevice();
|
||||
device.setId(this.uuidSerial.uuid());
|
||||
device.setRegistryId(param.getId());
|
||||
device.setDeviceCode(deviceCode);
|
||||
deviceList.add(device);
|
||||
}
|
||||
this.personRegistryDeviceMapper.batchInsert(deviceList);
|
||||
}
|
||||
if (isBindAppDevice.booleanValue()) {
|
||||
unbindAppicationDevice(getApplicationId(param.getBusinessId()), getDeviceIdList(dbDeviceList, param.getBusinessId(), context));
|
||||
bindApplicationDevice(getApplicationId(param.getBusinessId()), getDeviceIdList(deviceList, param.getBusinessId(), context));
|
||||
}
|
||||
}
|
||||
public void validateOrg(AddPersonRegistryParam param) throws ServiceException {
|
||||
if (StringUtils.isNotBlank(param.getOrganizationIds())) {
|
||||
List<Organization> dbOrganizationList = this.imgStoreOrganizationMapper.getOrgByIds(Arrays.asList(param.getOrganizationIds().split(",")), param.getBusinessId());
|
||||
if (CollectionUtils.isEmpty(dbOrganizationList) || dbOrganizationList.size() != (param.getOrganizationIds()
|
||||
.split(",")).length) {
|
||||
this.logger.warn("注册默认组织不属于该租户,注册默认组织列表:[{}]", param.getOrganizationIds());
|
||||
throw new ServiceException("53014512", getMessage("53014512"));
|
||||
}
|
||||
}
|
||||
}
|
||||
public void validateLabel(AddPersonRegistryParam param) throws ServiceException {
|
||||
if (StringUtils.isNotBlank(param.getLabelIds())) {
|
||||
List<Label> dbLabelList = this.imgStoreLabelMapper.selectByIds(param.getBusinessId(), Arrays.asList(param.getLabelIds().split(",")));
|
||||
if (CollectionUtils.isEmpty(dbLabelList) || dbLabelList.size() != (param.getLabelIds().split(",")).length) {
|
||||
this.logger.warn("注册默认标签不属于该租户,注册默认标签列表:[{}]", param.getLabelIds());
|
||||
throw new ServiceException("53014513", getMessage("53014513"));
|
||||
}
|
||||
}
|
||||
}
|
||||
public void validateDevice(AddPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
if (!CollectionUtils.isEmpty(param.getDeviceCodeList())) {
|
||||
CoreDeviceQueryParam coreDeviceQueryParam = new CoreDeviceQueryParam();
|
||||
coreDeviceQueryParam.setBusinessId(param.getBusinessId());
|
||||
coreDeviceQueryParam.setDeviceCodes(param.getDeviceCodeList());
|
||||
CloudwalkResult<List<AtomicDeviceGetResult>> deviceGetResult = this.atomicDeviceService.list(coreDeviceQueryParam, context);
|
||||
if (CollectionUtils.isEmpty((Collection)deviceGetResult.getData()) || ((List)deviceGetResult.getData()).size() != param
|
||||
.getDeviceCodeList().size()) {
|
||||
this.logger.warn("设备不属于该租户,设备列表:[{}]", param.getDeviceCodeList());
|
||||
throw new ServiceException("53014514", getMessage("53014514"));
|
||||
}
|
||||
}
|
||||
}
|
||||
public List<String> getDeviceIdList(List<PersonRegistryDevice> deviceList, String businessId, CloudwalkCallContext context) throws ServiceException {
|
||||
if (!CollectionUtils.isEmpty(deviceList)) {
|
||||
List<String> deviceCodeList = Collections3.extractToList(deviceList, "deviceCode");
|
||||
CoreDeviceQueryParam coreDeviceQueryParam = new CoreDeviceQueryParam();
|
||||
coreDeviceQueryParam.setBusinessId(businessId);
|
||||
coreDeviceQueryParam.setDeviceCodes(deviceCodeList);
|
||||
CloudwalkResult<List<AtomicDeviceGetResult>> deviceGetResult = this.atomicDeviceService.list(coreDeviceQueryParam, context);
|
||||
if (deviceGetResult.isSuccess()) {
|
||||
return Collections3.extractToList((Collection)deviceGetResult.getData(), "id");
|
||||
}
|
||||
}
|
||||
return Lists.newArrayList();
|
||||
}
|
||||
public void validateDevice(QueryPersonRegistryParam param, PersonRegistry personRegistry) throws ServiceException {
|
||||
if (StringUtils.isNotBlank(param.getDeviceCode())) {
|
||||
if (Objects.equals(personRegistry.getStatus(), StatusEnum.CLOSE.getValue())) {
|
||||
this.logger.warn("该设备未开启注册,租户ID:[{}],设备Code:[{}]", personRegistry.getBusinessId(), param.getDeviceCode());
|
||||
throw new ServiceException("53014518", getMessage("53014518"));
|
||||
}
|
||||
List<PersonRegistryDevice> dbPersonRegistryDeviceList = this.personRegistryDeviceMapper.select(personRegistry.getId(), Arrays.asList(new String[] { param.getDeviceCode() }));
|
||||
if (CollectionUtils.isEmpty(dbPersonRegistryDeviceList)) {
|
||||
this.logger.warn("该设备未注册,租户ID:[{}],设备Code:[{}]", personRegistry.getBusinessId(), param.getDeviceCode());
|
||||
throw new ServiceException("53014519", getMessage("53014519"));
|
||||
}
|
||||
}
|
||||
}
|
||||
public PersonRegistryResult setOrg(PersonRegistry personRegistry, PersonRegistryResult result) {
|
||||
if (StringUtils.isNotBlank(personRegistry.getOrganizationIds())) {
|
||||
List<Organization> dbOrgList = this.imgStoreOrganizationMapper.getOrgByIds(Arrays.asList(personRegistry.getOrganizationIds().split(",")), personRegistry.getBusinessId());
|
||||
List<OrganizationResult> orgResultList = Lists.newArrayListWithCapacity(dbOrgList.size());
|
||||
dbOrgList.forEach(dbOrg -> {
|
||||
OrganizationResult orgResult = new OrganizationResult();
|
||||
orgResult.setId(dbOrg.getId());
|
||||
orgResult.setName(dbOrg.getName());
|
||||
orgResultList.add(orgResult);
|
||||
});
|
||||
result.setOrganizationList(orgResultList);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
public PersonRegistryResult setLabel(PersonRegistry personRegistry, PersonRegistryResult result) {
|
||||
if (StringUtils.isNotBlank(personRegistry.getLabelIds())) {
|
||||
List<Label> dbLabelList = this.imgStoreLabelMapper.getLabelByIds(Arrays.asList(personRegistry.getLabelIds().split(",")), personRegistry.getBusinessId());
|
||||
List<LabelResult> labelResultList = Lists.newArrayListWithCapacity(dbLabelList.size());
|
||||
dbLabelList.forEach(dbLabel -> {
|
||||
LabelResult labelResult = new LabelResult();
|
||||
labelResult.setId(dbLabel.getId());
|
||||
labelResult.setName(dbLabel.getName());
|
||||
labelResultList.add(labelResult);
|
||||
});
|
||||
result.setLabelList(labelResultList);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
public String getApplicationId(String businessId) {
|
||||
ApplicationQueryParam queryParam = new ApplicationQueryParam();
|
||||
queryParam.setBusinessId(businessId);
|
||||
queryParam.setServiceCode(this.serviceCode);
|
||||
CloudwalkResult<List<ApplicationResult>> result = this.applicationFeignClient.query(queryParam);
|
||||
if (result.isSuccess() && !CollectionUtils.isEmpty((Collection)result.getData())) {
|
||||
return ((ApplicationResult)((List<ApplicationResult>)result.getData()).get(0)).getId();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
public Boolean bindApplicationDevice(String application, List<String> deviceIdList) throws ServiceException {
|
||||
AtomicInteger successCount = new AtomicInteger();
|
||||
if (!StringUtils.isBlank(application) && !CollectionUtils.isEmpty(deviceIdList)) {
|
||||
CoreAppDeviceAddParam param = null;
|
||||
for (String deviceId : deviceIdList) {
|
||||
param = new CoreAppDeviceAddParam();
|
||||
param.setApplicationId(application);
|
||||
param.setDeviceId(deviceId);
|
||||
CloudwalkResult<Boolean> result = this.deviceAppFeignClient.addAppDevice(param);
|
||||
if (result.isSuccess()) {
|
||||
successCount.getAndIncrement();
|
||||
}
|
||||
}
|
||||
return Boolean.valueOf(Objects.equals(Integer.valueOf(successCount.get()), Integer.valueOf(deviceIdList.size())));
|
||||
}
|
||||
return Boolean.valueOf(true);
|
||||
}
|
||||
public Boolean unbindAppicationDevice(String application, List<String> deviceIdList) throws ServiceException {
|
||||
AtomicInteger successCount = new AtomicInteger();
|
||||
if (!StringUtils.isBlank(application) && !CollectionUtils.isEmpty(deviceIdList)) {
|
||||
CoreAppDeviceParam param = null;
|
||||
for (String deviceId : deviceIdList) {
|
||||
param = new CoreAppDeviceParam();
|
||||
param.setApplicationId(application);
|
||||
param.setDeviceId(deviceId);
|
||||
CloudwalkResult<Boolean> result = this.deviceAppFeignClient.deleteAppDevice(param);
|
||||
if (result.isSuccess()) {
|
||||
successCount.getAndIncrement();
|
||||
}
|
||||
}
|
||||
return Boolean.valueOf(Objects.equals(Integer.valueOf(successCount.get()), Integer.valueOf(deviceIdList.size())));
|
||||
}
|
||||
return Boolean.valueOf(true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/CommonPersonRegistryService.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+577
@@ -0,0 +1,577 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.aggregate.application.param.ApplicationImageStoreQueryParam;
|
||||
import cn.cloudwalk.client.aggregate.application.result.ApplicationImageStoreQueryResult;
|
||||
import cn.cloudwalk.client.aggregate.application.service.ApplicationImageStoreService;
|
||||
import cn.cloudwalk.client.aggregate.common.enums.DelStatusEnum;
|
||||
import cn.cloudwalk.client.aggregate.group.param.AgImageFeatureQueryParam;
|
||||
import cn.cloudwalk.client.aggregate.group.result.AgImageFeatureResult;
|
||||
import cn.cloudwalk.client.aggregate.group.service.AgImageFeatureService;
|
||||
import cn.cloudwalk.client.organization.common.enums.DeviceAbilityEnum;
|
||||
import cn.cloudwalk.client.organization.common.enums.SyncStatusEnum;
|
||||
import cn.cloudwalk.client.organization.param.QueryZoneForm;
|
||||
import cn.cloudwalk.client.organization.result.ZoneResult;
|
||||
import cn.cloudwalk.client.organization.service.store.param.BatchPassRuleParam;
|
||||
import cn.cloudwalk.client.organization.service.store.param.DeviceImagePersonRefQuery;
|
||||
import cn.cloudwalk.client.organization.service.store.param.DeviceImageUpdateFeatureQuery;
|
||||
import cn.cloudwalk.client.organization.service.store.param.DeviceImageUpdatePersonQuery;
|
||||
import cn.cloudwalk.client.organization.service.store.param.PassRuleParam;
|
||||
import cn.cloudwalk.client.organization.service.store.result.BatchPassRuleResult;
|
||||
import cn.cloudwalk.client.organization.service.store.result.DeviceImagePersonRefResult;
|
||||
import cn.cloudwalk.client.organization.service.store.result.DeviceImageUpdateFeautreResult;
|
||||
import cn.cloudwalk.client.organization.service.store.result.DeviceImageUpdatePersonResult;
|
||||
import cn.cloudwalk.client.organization.service.store.result.PassRuleResult;
|
||||
import cn.cloudwalk.client.organization.service.store.service.CpDeviceImagePersonService;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkCallContext;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
import cn.cloudwalk.cloud.page.CloudwalkPageAble;
|
||||
import cn.cloudwalk.cloud.page.CloudwalkPageInfo;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.cloud.serial.UUIDSerial;
|
||||
import cn.cloudwalk.data.organization.dto.DevicePersonSyncLogDTO;
|
||||
import cn.cloudwalk.data.organization.dto.GroupPersonRefDTO;
|
||||
import cn.cloudwalk.data.organization.dto.QueryGroupPersonDTO;
|
||||
import cn.cloudwalk.data.organization.entity.DevicePerson;
|
||||
import cn.cloudwalk.data.organization.entity.DevicePersonSyncLog;
|
||||
import cn.cloudwalk.data.organization.entity.GroupPersonRef;
|
||||
import cn.cloudwalk.data.organization.entity.ImgStorePerson;
|
||||
import cn.cloudwalk.data.organization.mapper.DevicePersonMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.DevicePersonSyncLogMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.GroupPersonRefMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonLabelMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonOrganizationMapper;
|
||||
import cn.cloudwalk.device.sdk.protocol.entity.v2proto.http.result.UpdatePersonResult;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import cn.cloudwalk.service.organization.common.FileUtil;
|
||||
import cn.cloudwalk.service.organization.compare.NaturalOrderComparator;
|
||||
import cn.cloudwalk.service.organization.service.feign.ElevatorAppFeignClient;
|
||||
import cn.cloudwalk.service.organization.service.feign.ZoneFeignClient;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.github.pagehelper.Page;
|
||||
import com.github.pagehelper.page.PageMethod;
|
||||
import com.google.common.collect.Lists;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Resource;
|
||||
import org.apache.commons.collections4.CollectionUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Service;
|
||||
@Service
|
||||
public class CpDeviceImagePersonServiceImpl
|
||||
extends AbstractImagStoreService
|
||||
implements CpDeviceImagePersonService
|
||||
{
|
||||
private static final String SYNC_LOG_KEY = "lock_sync_log_";
|
||||
@Value("${cloudwalk.person.sync-log-expire-time:10}")
|
||||
private long syncLogExpireTime;
|
||||
@Resource
|
||||
private GroupPersonRefMapper groupPersonRefMapper;
|
||||
@Resource
|
||||
private ImgStorePersonMapper imgStorePersonMapper;
|
||||
@Autowired
|
||||
private AgImageFeatureService agImageFeatureService;
|
||||
@Value("${cloudwalk.component.file.urlPrefix}")
|
||||
private String fileUrlPrefix;
|
||||
@Value("${cloudwalk.component.imagePerson.imagebase64.enable:false}")
|
||||
private Boolean base64Enable;
|
||||
@Resource
|
||||
private ZoneFeignClient zoneFeignClient;
|
||||
@Resource
|
||||
private ElevatorAppFeignClient elevatorAppFeignClient;
|
||||
@Resource
|
||||
private DevicePersonSyncLogMapper devicePersonSyncLogMapper;
|
||||
@Resource
|
||||
private DevicePersonMapper devicePersonMapper;
|
||||
@Resource
|
||||
private UUIDSerial uuidSerial;
|
||||
@Autowired
|
||||
private StringRedisTemplate redisTemplate;
|
||||
@Resource
|
||||
private ImgStorePersonOrganizationMapper imgStorePersonOrganizationMapper;
|
||||
@Resource
|
||||
private ImgStorePersonLabelMapper imgStorePersonLabelMapper;
|
||||
@Resource
|
||||
private ApplicationImageStoreService appImageStoreService;
|
||||
public CloudwalkResult<List<DeviceImagePersonRefResult>> getImagePersonRefs(DeviceImagePersonRefQuery queryParam, CloudwalkCallContext context) throws ServiceException {
|
||||
List<DeviceImagePersonRefResult> deviceImagePersonRefResults = new ArrayList<>();
|
||||
if (StringUtils.isBlank(queryParam.getImageStoreId()) &&
|
||||
CollectionUtils.isEmpty(queryParam.getImageStoreIds())) {
|
||||
return CloudwalkResult.fail("53013500",
|
||||
getMessage("53013500"));
|
||||
}
|
||||
if (StringUtils.isNotBlank(queryParam.getImageStoreId())) {
|
||||
queryParam.setImageStoreIds(Lists.newArrayList(queryParam.getImageStoreId() ));
|
||||
}
|
||||
List<String> imageStoreIds = queryParam.getImageStoreIds();
|
||||
for (String imageId : imageStoreIds) {
|
||||
DeviceImagePersonRefResult deviceImagePersonRefResult = new DeviceImagePersonRefResult();
|
||||
deviceImagePersonRefResult.setImageStoreId(imageId);
|
||||
QueryGroupPersonDTO queryGroupPersonDTO = new QueryGroupPersonDTO();
|
||||
queryGroupPersonDTO.setImageStoreId(imageId);
|
||||
PageMethod.startPage(queryParam.getCurrentPage(), 1);
|
||||
PageMethod.orderBy("LAST_UPDATE_TIME DESC");
|
||||
Page<GroupPersonRef> groupPersonRefs = (Page<GroupPersonRef>)this.groupPersonRefMapper.query(queryGroupPersonDTO);
|
||||
if (CollectionUtils.isNotEmpty(groupPersonRefs.getResult())) {
|
||||
Long lastUpdateTime = ((GroupPersonRef)groupPersonRefs.getResult().get(0)).getLastUpdateTime();
|
||||
deviceImagePersonRefResult.setImageLastUpdateTime(lastUpdateTime);
|
||||
deviceImagePersonRefResults.add(deviceImagePersonRefResult);
|
||||
}
|
||||
} return CloudwalkResult.success(deviceImagePersonRefResults);
|
||||
}
|
||||
public CloudwalkResult<CloudwalkPageAble<DeviceImageUpdatePersonResult>> getDeviceImageUpdatePersonInfo(DeviceImageUpdatePersonQuery query, CloudwalkCallContext context) throws ServiceException {
|
||||
List<DeviceImageUpdatePersonResult> deviceImageUpdatePersonResults = new ArrayList<>();
|
||||
QueryGroupPersonDTO queryGroupPersonDTO = new QueryGroupPersonDTO();
|
||||
queryGroupPersonDTO.setImageStoreId(query.getImageStoreId());
|
||||
queryGroupPersonDTO.setLastUpdateTime(query.getLastUpdateTime());
|
||||
queryGroupPersonDTO.setSequenceId(String.valueOf(query.getSequenceId()));
|
||||
CloudwalkPageInfo page = new CloudwalkPageInfo(query.getCurrentPage(), query.getRowsOfPage());
|
||||
PageMethod.startPage(query.getCurrentPage(), query.getRowsOfPage());
|
||||
PageMethod.orderBy("LAST_UPDATE_TIME ASC,PERSON_ID ASC");
|
||||
Page<GroupPersonRef> groupPersonRefs = (Page<GroupPersonRef>)this.groupPersonRefMapper.query(queryGroupPersonDTO);
|
||||
List<GroupPersonRef> personRefsResult = groupPersonRefs.getResult();
|
||||
for (GroupPersonRef groupPersonRef : personRefsResult) {
|
||||
if (groupPersonRef.getPersonId() == null) {
|
||||
continue;
|
||||
}
|
||||
DeviceImageUpdatePersonResult deviceImageUpdatePersonResult = new DeviceImageUpdatePersonResult();
|
||||
deviceImageUpdatePersonResult.setPersonId(groupPersonRef.getPersonId());
|
||||
if (query.getSupportPersonValiddate() != null && DeviceAbilityEnum.SUPPORT_PERSON_VALIDDATE
|
||||
.getCode() == query.getSupportPersonValiddate().intValue()) {
|
||||
if (-1 == groupPersonRef.getStatus().shortValue()) {
|
||||
deviceImageUpdatePersonResult.setType(Integer.valueOf(DelStatusEnum.DELETED.getCode().shortValue()));
|
||||
} else {
|
||||
deviceImageUpdatePersonResult.setType(Integer.valueOf(DelStatusEnum.NORAML.getCode().shortValue()));
|
||||
}
|
||||
} else {
|
||||
deviceImageUpdatePersonResult.setType(Integer.valueOf(groupPersonRef.getIsDel().intValue()));
|
||||
}
|
||||
if (groupPersonRef.getIsDel() != null && DelStatusEnum.NORAML.getCode().shortValue() == groupPersonRef.getIsDel().shortValue()) {
|
||||
deviceImageUpdatePersonResult.setStatus(Integer.valueOf(1));
|
||||
} else {
|
||||
deviceImageUpdatePersonResult.setStatus(Integer.valueOf(0));
|
||||
}
|
||||
deviceImageUpdatePersonResult.setImageStoreId(groupPersonRef.getImageStoreId());
|
||||
deviceImageUpdatePersonResult.setTimestamp(groupPersonRef.getLastUpdateTime());
|
||||
deviceImageUpdatePersonResult.setSequenceId(Long.valueOf(groupPersonRef.getPersonId()));
|
||||
deviceImageUpdatePersonResult.setExpiryBeginDate(groupPersonRef.getExpiryBeginDate());
|
||||
deviceImageUpdatePersonResult.setExpiryEndDate(groupPersonRef.getExpiryEndDate());
|
||||
ImgStorePerson imgStorePerson = this.imgStorePersonMapper.selectByPrimaryKey(groupPersonRef.getPersonId());
|
||||
if (imgStorePerson != null) {
|
||||
deviceImageUpdatePersonResult.setImageStoreId(groupPersonRef.getImageStoreId());
|
||||
if (StringUtils.isNotBlank(imgStorePerson.getReserveInfo())) {
|
||||
JSONObject json = JSONObject.parseObject(imgStorePerson.getReserveInfo());
|
||||
if (null != json.get("icCardNo") && StringUtils.isNotBlank(imgStorePerson.getIcCardNo())) {
|
||||
json.put("icCardNo", imgStorePerson.getIcCardNo());
|
||||
}
|
||||
if (null != json.get("icCardType") && StringUtils.isNotBlank(imgStorePerson.getIcCardType())) {
|
||||
json.put("icCardType", imgStorePerson.getIcCardType());
|
||||
}
|
||||
deviceImageUpdatePersonResult.setReserveInfo(JSON.toJSONString(json));
|
||||
} else {
|
||||
JSONObject json = new JSONObject();
|
||||
if (StringUtils.isNotBlank(imgStorePerson.getIcCardNo())) {
|
||||
json.put("icCardNo", imgStorePerson.getIcCardNo());
|
||||
}
|
||||
if (StringUtils.isNotBlank(imgStorePerson.getIcCardType())) {
|
||||
json.put("icCardType", imgStorePerson.getIcCardType());
|
||||
}
|
||||
deviceImageUpdatePersonResult.setReserveInfo(JSON.toJSONString(json));
|
||||
}
|
||||
deviceImageUpdatePersonResult.setName(imgStorePerson.getName());
|
||||
deviceImageUpdatePersonResult.setMobileNumber(imgStorePerson.getPhone());
|
||||
if (imgStorePerson.getCreateTime() != null) {
|
||||
deviceImageUpdatePersonResult.setCreateDate(imgStorePerson.getCreateTime().toString());
|
||||
}
|
||||
List<DeviceImageUpdatePersonResult.FaceData> faceDatas = new ArrayList<>();
|
||||
if (StringUtils.isNotBlank(imgStorePerson.getComparePicture())) {
|
||||
DeviceImageUpdatePersonResult.FaceData personFaceData = new DeviceImageUpdatePersonResult.FaceData();
|
||||
personFaceData.setFaceId(imgStorePerson.getImageId());
|
||||
personFaceData.setPictureUrl(this.fileUrlPrefix + imgStorePerson.getComparePicture());
|
||||
faceDatas.add(personFaceData);
|
||||
}
|
||||
deviceImageUpdatePersonResult.setFaceData(faceDatas);
|
||||
if (StringUtils.isNotBlank(imgStorePerson.getShowPicture())) {
|
||||
DeviceImageUpdatePersonResult.ImageData imageData = new DeviceImageUpdatePersonResult.ImageData();
|
||||
try {
|
||||
imageData.setImageUrl(this.fileUrlPrefix + imgStorePerson.getShowPicture());
|
||||
if (this.base64Enable.booleanValue() && deviceImageUpdatePersonResult.getStatus().intValue() == 1) {
|
||||
imageData.setImageType(Integer.valueOf(0));
|
||||
imageData.setImage(FileUtil.url2base64(imageData.getImageUrl()));
|
||||
}
|
||||
deviceImageUpdatePersonResult.setShowImage(imageData);
|
||||
} catch (Exception e) {
|
||||
this.logger.warn("{} imageData url2BASE64 error {}", imageData.getImageUrl(), e.getMessage());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
deviceImageUpdatePersonResult.setStatus(Integer.valueOf(0));
|
||||
}
|
||||
deviceImageUpdatePersonResults.add(deviceImageUpdatePersonResult);
|
||||
}
|
||||
CloudwalkPageAble<DeviceImageUpdatePersonResult> resultCloudwalkPageAble = new CloudwalkPageAble(deviceImageUpdatePersonResults, page, groupPersonRefs.getTotal());
|
||||
return CloudwalkResult.success(resultCloudwalkPageAble);
|
||||
}
|
||||
private boolean elevatorGroup(String imageStoreId, CloudwalkCallContext context) {
|
||||
Boolean elevatorGroup = Boolean.valueOf(false);
|
||||
ApplicationImageStoreQueryParam queryParam = new ApplicationImageStoreQueryParam();
|
||||
queryParam.setImageStoreId(imageStoreId);
|
||||
CloudwalkResult<List<ApplicationImageStoreQueryResult>> appImageStoreResult = this.appImageStoreService.query(queryParam, context);
|
||||
if (appImageStoreResult.isSuccess() && !CollectionUtils.isEmpty((Collection)appImageStoreResult.getData()) && "派梯应用"
|
||||
.equals(((ApplicationImageStoreQueryResult)((List<ApplicationImageStoreQueryResult>)appImageStoreResult.getData()).get(0)).getApplicationName())) {
|
||||
elevatorGroup = Boolean.valueOf(true);
|
||||
}
|
||||
return elevatorGroup.booleanValue();
|
||||
}
|
||||
private Map<String, String> personPassRule(List<GroupPersonRefDTO> personRefsResult, CloudwalkCallContext context) {
|
||||
Map<String, String> personPassRuleMap = new HashMap<>();
|
||||
if (!CollectionUtils.isEmpty(personRefsResult)) {
|
||||
List<String> personIds = (List<String>)personRefsResult.stream().map(GroupPersonRef::getPersonId).collect(Collectors.toList());
|
||||
long t3 = System.currentTimeMillis();
|
||||
List<Map<String, String>> personOrgMapList = this.imgStorePersonOrganizationMapper.groupByPerson(personIds);
|
||||
long t4 = System.currentTimeMillis();
|
||||
this.logger.info("20113 getDeviceUpdatePersonInfo queryPersonOrg,spend time {} millis", Long.valueOf(t4 - t3));
|
||||
Map<String, String> personOrgMap = (Map<String, String>)personOrgMapList.stream().collect(Collectors.toMap(map -> (String)map.get("personId"), map -> (String)map.get("orgIds")));
|
||||
t3 = System.currentTimeMillis();
|
||||
List<Map<String, String>> personLabelMapList = this.imgStorePersonLabelMapper.groupByPerson(personIds);
|
||||
t4 = System.currentTimeMillis();
|
||||
this.logger.info("20113 getDeviceUpdatePersonInfo queryPersonLabel,spend time {} millis", Long.valueOf(t4 - t3));
|
||||
Map<String, String> personLabelMap = (Map<String, String>)personLabelMapList.stream().collect(Collectors.toMap(map -> (String)map.get("personId"), map -> (String)map.get("labelIds")));
|
||||
List<PassRuleParam> passRuleParamList = Lists.newArrayListWithCapacity(personIds.size());
|
||||
personIds.forEach(personId -> {
|
||||
List<String> orgIds = Optional.ofNullable(personOrgMap.get(personId)).map(v -> v).orElse(new ArrayList<>());
|
||||
List<String> labelIds = Optional.ofNullable(personLabelMap.get(personId)).map(v -> v).orElse(new ArrayList<>());
|
||||
PassRuleParam param = new PassRuleParam();
|
||||
param.setPersonId(personId);
|
||||
param.setIncludeOrganizations(orgIds);
|
||||
param.setIncludeLabels(labelIds);
|
||||
param.setBusinessId(context.getCompany().getCompanyId());
|
||||
passRuleParamList.add(param);
|
||||
});
|
||||
t3 = System.currentTimeMillis();
|
||||
BatchPassRuleParam batchParam = new BatchPassRuleParam();
|
||||
batchParam.setPersonList(passRuleParamList);
|
||||
CloudwalkResult<List<BatchPassRuleResult>> result = this.elevatorAppFeignClient.batchPassRule(batchParam);
|
||||
t4 = System.currentTimeMillis();
|
||||
this.logger.info("20113 getDeviceUpdatePersonInfo batchPassRule,spend time {} millis", Long.valueOf(t4 - t3));
|
||||
if (result.isSuccess() && CollectionUtils.isNotEmpty((Collection)result.getData())) {
|
||||
((List)result.getData()).forEach(passRule -> {
|
||||
List<String> zoneNameList = (List<String>)((List<String>)Optional.ofNullable(passRule.getZoneList()).orElse(new ArrayList<>())).stream().map(v -> v).collect(Collectors.toList());
|
||||
Collections.sort(zoneNameList, (Comparator<? super String>)new NaturalOrderComparator(true));
|
||||
String zoneNameStr = String.join(",", (Iterable)zoneNameList);
|
||||
personPassRuleMap.put(passRule.getPersonId(), zoneNameStr);
|
||||
});
|
||||
}
|
||||
}
|
||||
return personPassRuleMap;
|
||||
}
|
||||
public CloudwalkResult<CloudwalkPageAble<DeviceImageUpdatePersonResult>> getDeviceUpdatePersonInfo(DeviceImageUpdatePersonQuery query, CloudwalkCallContext context) throws ServiceException {
|
||||
List<DeviceImageUpdatePersonResult> deviceImageUpdatePersonResults = new ArrayList<>();
|
||||
QueryGroupPersonDTO queryGroupPersonDTO = new QueryGroupPersonDTO();
|
||||
queryGroupPersonDTO.setDeviceId(query.getDeviceId());
|
||||
queryGroupPersonDTO.setImageStoreId(query.getImageStoreId());
|
||||
queryGroupPersonDTO.setLastUpdateTime(query.getLastUpdateTime());
|
||||
queryGroupPersonDTO.setSequenceId(String.valueOf(query.getSequenceId()));
|
||||
queryGroupPersonDTO.setPageSize(Integer.valueOf(query.getRowsOfPage()));
|
||||
CloudwalkPageInfo page = new CloudwalkPageInfo(query.getCurrentPage(), query.getRowsOfPage());
|
||||
long t1 = System.currentTimeMillis();
|
||||
List<GroupPersonRefDTO> personRefsResult = this.groupPersonRefMapper.queryGroupPersonList(queryGroupPersonDTO);
|
||||
long t2 = System.currentTimeMillis();
|
||||
this.logger.info("20113 getDeviceUpdatePersonInfo queryGroupPerson,spend time {} millis", Long.valueOf(t2 - t1));
|
||||
boolean isElevatorGroup = elevatorGroup(query.getImageStoreId(), context);
|
||||
Map<String, String> personPassRuleMap = new HashMap<>();
|
||||
if (isElevatorGroup) {
|
||||
personPassRuleMap = personPassRule(personRefsResult, context);
|
||||
}
|
||||
Map<String, String> finalPersonPassRuleMap = personPassRuleMap;
|
||||
for (GroupPersonRefDTO groupPersonRef : personRefsResult) {
|
||||
if (StringUtils.isBlank(groupPersonRef.getPersonId())) {
|
||||
continue;
|
||||
}
|
||||
DeviceImageUpdatePersonResult deviceImageUpdatePersonResult = new DeviceImageUpdatePersonResult();
|
||||
deviceImageUpdatePersonResult.setPersonId(groupPersonRef.getPersonId());
|
||||
if (query.getSupportPersonValiddate() != null && DeviceAbilityEnum.SUPPORT_PERSON_VALIDDATE
|
||||
.getCode() == query.getSupportPersonValiddate().intValue()) {
|
||||
if (-1 == groupPersonRef.getStatus().shortValue()) {
|
||||
deviceImageUpdatePersonResult.setType(Integer.valueOf(DelStatusEnum.DELETED.getCode().shortValue()));
|
||||
} else {
|
||||
deviceImageUpdatePersonResult.setType(Integer.valueOf(DelStatusEnum.NORAML.getCode().shortValue()));
|
||||
}
|
||||
} else {
|
||||
deviceImageUpdatePersonResult.setType(Integer.valueOf(groupPersonRef.getIsDel().intValue()));
|
||||
}
|
||||
if (groupPersonRef.getIsDel() != null && DelStatusEnum.NORAML.getCode().shortValue() == groupPersonRef.getIsDel().shortValue()) {
|
||||
deviceImageUpdatePersonResult.setStatus(Integer.valueOf(1));
|
||||
} else {
|
||||
deviceImageUpdatePersonResult.setStatus(Integer.valueOf(0));
|
||||
}
|
||||
deviceImageUpdatePersonResult.setImageStoreId(groupPersonRef.getImageStoreId());
|
||||
deviceImageUpdatePersonResult.setTimestamp(groupPersonRef.getLastUpdateTime());
|
||||
deviceImageUpdatePersonResult.setSequenceId(Long.valueOf(groupPersonRef.getPersonId()));
|
||||
deviceImageUpdatePersonResult.setExpiryBeginDate(groupPersonRef.getExpiryBeginDate());
|
||||
deviceImageUpdatePersonResult.setExpiryEndDate(groupPersonRef.getExpiryEndDate());
|
||||
ImgStorePerson imgStorePerson = this.imgStorePersonMapper.selectByPrimaryKey(groupPersonRef.getPersonId());
|
||||
if (imgStorePerson != null) {
|
||||
deviceImageUpdatePersonResult.setImageStoreId(groupPersonRef.getImageStoreId());
|
||||
JSONObject json = new JSONObject();
|
||||
if (StringUtils.isNotBlank(imgStorePerson.getReserveInfo())) {
|
||||
json = JSONObject.parseObject(imgStorePerson.getReserveInfo());
|
||||
if (null != json.get("icCardNo") && StringUtils.isNotBlank(imgStorePerson.getIcCardNo())) {
|
||||
json.put("icCardNo", imgStorePerson.getIcCardNo());
|
||||
}
|
||||
if (null != json.get("icCardType") && StringUtils.isNotBlank(imgStorePerson.getIcCardType())) {
|
||||
json.put("icCardType", imgStorePerson.getIcCardType());
|
||||
}
|
||||
} else {
|
||||
if (StringUtils.isNotBlank(imgStorePerson.getIcCardNo())) {
|
||||
json.put("icCardNo", imgStorePerson.getIcCardNo());
|
||||
}
|
||||
if (StringUtils.isNotBlank(imgStorePerson.getIcCardType())) {
|
||||
json.put("icCardType", imgStorePerson.getIcCardType());
|
||||
}
|
||||
}
|
||||
json.put("passCrons", groupPersonRef.getValidDateCron());
|
||||
if (isElevatorGroup) {
|
||||
json.put("floors", getFloorInfo(groupPersonRef, finalPersonPassRuleMap));
|
||||
}
|
||||
if (StringUtils.isNotBlank(imgStorePerson.getDefaultFloor())) {
|
||||
QueryZoneForm queryZoneForm = new QueryZoneForm();
|
||||
queryZoneForm.setIds(Collections.singletonList(imgStorePerson.getDefaultFloor()));
|
||||
this.logger.info("楼层信息查询入参为{}", JSON.toJSONString(queryZoneForm));
|
||||
CloudwalkResult<List<ZoneResult>> zoneDetail = this.zoneFeignClient.findZonelist(queryZoneForm);
|
||||
this.logger.info("楼层信息{}", JSON.toJSONString(zoneDetail));
|
||||
if (!CollectionUtils.isEmpty((Collection)zoneDetail.getData())) {
|
||||
json.put("defaultFloor", ((ZoneResult)((List<ZoneResult>)zoneDetail.getData()).get(0)).getName());
|
||||
}
|
||||
}
|
||||
deviceImageUpdatePersonResult.setReserveInfo(JSON.toJSONString(json));
|
||||
deviceImageUpdatePersonResult.setName(imgStorePerson.getName());
|
||||
deviceImageUpdatePersonResult.setMobileNumber(imgStorePerson.getPhone());
|
||||
if (imgStorePerson.getCreateTime() != null) {
|
||||
deviceImageUpdatePersonResult.setCreateDate(imgStorePerson.getCreateTime().toString());
|
||||
}
|
||||
List<DeviceImageUpdatePersonResult.FaceData> faceDatas = new ArrayList<>();
|
||||
if (StringUtils.isNotBlank(imgStorePerson.getComparePicture())) {
|
||||
DeviceImageUpdatePersonResult.FaceData personFaceData = new DeviceImageUpdatePersonResult.FaceData();
|
||||
personFaceData.setFaceId(imgStorePerson.getImageId());
|
||||
personFaceData.setPictureUrl(this.fileUrlPrefix + imgStorePerson.getComparePicture());
|
||||
faceDatas.add(personFaceData);
|
||||
}
|
||||
deviceImageUpdatePersonResult.setFaceData(faceDatas);
|
||||
if (StringUtils.isNotBlank(imgStorePerson.getShowPicture())) {
|
||||
DeviceImageUpdatePersonResult.ImageData imageData = new DeviceImageUpdatePersonResult.ImageData();
|
||||
try {
|
||||
imageData.setImageUrl(this.fileUrlPrefix + imgStorePerson.getShowPicture());
|
||||
if (this.base64Enable.booleanValue() && deviceImageUpdatePersonResult.getStatus().intValue() == 1) {
|
||||
imageData.setImageType(Integer.valueOf(0));
|
||||
imageData.setImage(FileUtil.url2base64(imageData.getImageUrl()));
|
||||
}
|
||||
deviceImageUpdatePersonResult.setShowImage(imageData);
|
||||
} catch (Exception e) {
|
||||
this.logger.warn("{} imageData url2BASE64 error {}", imageData.getImageUrl(), e.getMessage());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
deviceImageUpdatePersonResult.setStatus(Integer.valueOf(0));
|
||||
}
|
||||
deviceImageUpdatePersonResults.add(deviceImageUpdatePersonResult);
|
||||
}
|
||||
CloudwalkPageAble<DeviceImageUpdatePersonResult> resultCloudwalkPageAble = new CloudwalkPageAble(deviceImageUpdatePersonResults, page, 0L);
|
||||
return CloudwalkResult.success(resultCloudwalkPageAble);
|
||||
}
|
||||
private String getFloorInfo(GroupPersonRefDTO groupPersonRef, Map<String, String> personPassRuleMap) {
|
||||
if (personPassRuleMap.containsKey(groupPersonRef.getPersonId())) {
|
||||
return personPassRuleMap.get(groupPersonRef.getPersonId());
|
||||
}
|
||||
return "";
|
||||
}
|
||||
public CloudwalkResult<CloudwalkPageAble<DeviceImageUpdateFeautreResult>> getDeviceImageUpdateFeatureInfo(DeviceImageUpdateFeatureQuery query, CloudwalkCallContext context) throws ServiceException {
|
||||
List<DeviceImageUpdateFeautreResult> deviceImageUpdateFeautreResults = new ArrayList<>();
|
||||
QueryGroupPersonDTO queryGroupPersonDTO = new QueryGroupPersonDTO();
|
||||
queryGroupPersonDTO.setImageStoreId(query.getImageStoreId());
|
||||
queryGroupPersonDTO.setLastUpdateTime(query.getLastUpdateTime());
|
||||
queryGroupPersonDTO.setSequenceId(String.valueOf(query.getSequenceId()));
|
||||
CloudwalkPageInfo page = new CloudwalkPageInfo(query.getCurrentPage(), query.getRowsOfPage());
|
||||
PageMethod.startPage(query.getCurrentPage(), query.getRowsOfPage());
|
||||
PageMethod.orderBy("LAST_UPDATE_TIME ASC,PERSON_ID ASC");
|
||||
Page<GroupPersonRef> groupPersonRefs = (Page<GroupPersonRef>)this.groupPersonRefMapper.query(queryGroupPersonDTO);
|
||||
List<GroupPersonRef> personRefsResult = groupPersonRefs.getResult();
|
||||
for (GroupPersonRef refVar : personRefsResult) {
|
||||
ImgStorePerson imgStorePerson = this.imgStorePersonMapper.selectByPrimaryKey(refVar.getPersonId());
|
||||
DeviceImageUpdateFeautreResult deviceImageUpdateFeautreResult = new DeviceImageUpdateFeautreResult();
|
||||
if (imgStorePerson == null) {
|
||||
continue;
|
||||
}
|
||||
if (refVar.getIsDel() != null && DelStatusEnum.NORAML.getCode().shortValue() == refVar.getIsDel().shortValue()) {
|
||||
AgImageFeatureQueryParam queryParam = new AgImageFeatureQueryParam();
|
||||
queryParam.setImageId(imgStorePerson.getImageId());
|
||||
queryParam.setGroupId(refVar.getImageStoreId());
|
||||
CloudwalkResult<AgImageFeatureResult> queryResult = this.agImageFeatureService.query(queryParam);
|
||||
if (queryResult.isSuccess() && queryResult.getData() != null) {
|
||||
AgImageFeatureResult agImageFeatureResult = (AgImageFeatureResult)queryResult.getData();
|
||||
deviceImageUpdateFeautreResult.setFaceId(agImageFeatureResult.getImageId());
|
||||
deviceImageUpdateFeautreResult.setType(Integer.valueOf(refVar.getIsDel().intValue()));
|
||||
deviceImageUpdateFeautreResult.setFeature(agImageFeatureResult.getFeature());
|
||||
deviceImageUpdateFeautreResult.setSequenceId(Long.valueOf(refVar.getPersonId()));
|
||||
deviceImageUpdateFeautreResult.setTimestamp(refVar.getLastUpdateTime());
|
||||
deviceImageUpdateFeautreResults.add(deviceImageUpdateFeautreResult);
|
||||
} continue;
|
||||
}
|
||||
deviceImageUpdateFeautreResult.setFaceId(imgStorePerson.getImageId());
|
||||
deviceImageUpdateFeautreResult.setType(Integer.valueOf(DelStatusEnum.DELETED.getCode().intValue()));
|
||||
deviceImageUpdateFeautreResult.setSequenceId(Long.valueOf(refVar.getPersonId()));
|
||||
deviceImageUpdateFeautreResult.setTimestamp(refVar.getLastUpdateTime());
|
||||
deviceImageUpdateFeautreResults.add(deviceImageUpdateFeautreResult);
|
||||
}
|
||||
CloudwalkPageAble<DeviceImageUpdateFeautreResult> resultCloudwalkPageAble = new CloudwalkPageAble(deviceImageUpdateFeautreResults, page, groupPersonRefs.getTotal());
|
||||
return CloudwalkResult.success(resultCloudwalkPageAble);
|
||||
}
|
||||
@Async("saveSyncLogExecutor")
|
||||
public void saveSyncLog(String deviceId, String groupId, List<UpdatePersonResult.PersonData> personData) {
|
||||
if (CollectionUtils.isEmpty(personData)) {
|
||||
this.logger.warn("设备[{}]图库[{}]人员更新数据为空", deviceId, groupId);
|
||||
return;
|
||||
}
|
||||
DevicePersonSyncLogDTO dto = new DevicePersonSyncLogDTO();
|
||||
dto.setDeviceId(deviceId);
|
||||
dto.setImageStoreId(groupId);
|
||||
List<DevicePersonSyncLog> syncLogs = null;
|
||||
for (UpdatePersonResult.PersonData personInfo : personData) {
|
||||
String personId = personInfo.getUserId();
|
||||
dto.setPersonId(personId);
|
||||
syncLogs = this.devicePersonSyncLogMapper.query(dto);
|
||||
this.logger.debug("根据设备[{}]图库[{}]人员[{}]查询同步记录:[{}]", new Object[] { deviceId, groupId, personId, JSON.toJSONString(syncLogs) });
|
||||
if (!CollectionUtils.isEmpty(syncLogs)) {
|
||||
updateSyncLog(syncLogs.get(0), personInfo);
|
||||
continue;
|
||||
}
|
||||
QueryGroupPersonDTO queryGroupPersonDTO = new QueryGroupPersonDTO();
|
||||
queryGroupPersonDTO.setImageStoreId(groupId);
|
||||
queryGroupPersonDTO.setPersonId(personId);
|
||||
List<GroupPersonRef> groupPersonRefList = this.groupPersonRefMapper.query(queryGroupPersonDTO);
|
||||
if (CollectionUtils.isEmpty(groupPersonRefList)) {
|
||||
this.logger.debug("根据图库Id[{}],人员Id[{}]查询不存在图库人员关联记录", groupId, personInfo.getUserId());
|
||||
continue;
|
||||
}
|
||||
if (lockSyncLog(deviceId, groupId, personId)) {
|
||||
insertSyncLog(deviceId, groupId, personId, personInfo, groupPersonRefList.get(0));
|
||||
unlockSyncLog(deviceId, groupId, personId); continue;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(1000L);
|
||||
syncLogs = this.devicePersonSyncLogMapper.query(dto);
|
||||
if (!CollectionUtils.isEmpty(syncLogs))
|
||||
{
|
||||
updateSyncLog(syncLogs.get(0), personInfo);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
this.logger.error("CpOrgDevieKitServiceImpl lock sync log sleep error:{}", e.getMessage());
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
private void updateSyncLog(DevicePersonSyncLog dbSyncLog, UpdatePersonResult.PersonData personInfo) {
|
||||
dbSyncLog.setStatus(Integer.valueOf(SyncStatusEnum.PULL.getValue()));
|
||||
dbSyncLog.setCode("");
|
||||
dbSyncLog.setErrorMessage("");
|
||||
dbSyncLog.setLastPullTime(Long.valueOf(System.currentTimeMillis()));
|
||||
dbSyncLog.setUpdateInfo("存在同步记录,更新同步状态:设备已拉取");
|
||||
dbSyncLog.setIsDel(personInfo.getType());
|
||||
if (!CollectionUtils.isEmpty(personInfo.getFaceData())) {
|
||||
dbSyncLog.setImageId(((UpdatePersonResult.PersonData.FaceData)personInfo.getFaceData().get(0)).getFaceId());
|
||||
} else {
|
||||
dbSyncLog.setErrorMessage("无识别照,设备无需上报");
|
||||
}
|
||||
this.devicePersonSyncLogMapper.updateStatusAndCountInc(dbSyncLog);
|
||||
this.logger.debug("更新同步记录[{}],设备已拉取,count[{}]", dbSyncLog.getId(), Integer.valueOf(dbSyncLog.getCount().intValue() + 1));
|
||||
this.logger.debug("更新同步记录[{}],[{}]", dbSyncLog.getId(), dbSyncLog);
|
||||
}
|
||||
private void insertSyncLog(String deviceId, String groupId, String personId, UpdatePersonResult.PersonData personInfo, GroupPersonRef groupPersonRef) {
|
||||
DevicePerson queryDevicePerson = new DevicePerson();
|
||||
queryDevicePerson.setDeviceId(deviceId);
|
||||
queryDevicePerson.setPersonId(personId);
|
||||
List<DevicePerson> dbDevicePersonList = this.devicePersonMapper.query(queryDevicePerson);
|
||||
DevicePerson dbDevicePerson = null;
|
||||
if (CollectionUtils.isEmpty(dbDevicePersonList)) {
|
||||
DevicePerson newDevicePerson = new DevicePerson();
|
||||
newDevicePerson.setId(this.uuidSerial.uuid());
|
||||
newDevicePerson.setDeviceId(deviceId);
|
||||
newDevicePerson.setPersonId(personId);
|
||||
newDevicePerson.setType(personInfo.getType());
|
||||
newDevicePerson.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
newDevicePerson.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
int res = this.devicePersonMapper.insertSelective(newDevicePerson);
|
||||
if (res > 0) {
|
||||
dbDevicePerson = newDevicePerson;
|
||||
}
|
||||
} else {
|
||||
dbDevicePerson = dbDevicePersonList.get(0);
|
||||
}
|
||||
DevicePersonSyncLog newSyncLog = new DevicePersonSyncLog();
|
||||
newSyncLog.setId(this.uuidSerial.uuid());
|
||||
newSyncLog.setDeviceId(deviceId);
|
||||
newSyncLog.setImageStoreId(groupId);
|
||||
newSyncLog.setPersonId(personId);
|
||||
newSyncLog.setGroupPersonRefId(groupPersonRef.getId());
|
||||
newSyncLog.setStatus(Integer.valueOf(SyncStatusEnum.PULL.getValue()));
|
||||
newSyncLog.setCount(Integer.valueOf(1));
|
||||
newSyncLog.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
newSyncLog.setLastUpdateTime(groupPersonRef.getLastUpdateTime());
|
||||
newSyncLog.setLastPullTime(Long.valueOf(System.currentTimeMillis()));
|
||||
if (!CollectionUtils.isEmpty(personInfo.getFaceData())) {
|
||||
newSyncLog.setImageId(((UpdatePersonResult.PersonData.FaceData)personInfo.getFaceData().get(0)).getFaceId());
|
||||
}
|
||||
newSyncLog.setUpdateInfo("生成同步记录,同步状态:设备已拉取");
|
||||
newSyncLog.setDevicePersonRefId((null != dbDevicePerson) ? dbDevicePerson.getId() : null);
|
||||
newSyncLog.setIsDel(personInfo.getType());
|
||||
if (CollectionUtils.isEmpty(personInfo.getFaceData()))
|
||||
{
|
||||
newSyncLog.setErrorMessage("无识别照,设备无需上报");
|
||||
}
|
||||
this.logger.debug("新增同步记录[{}],[{}]", newSyncLog.getId(), newSyncLog);
|
||||
try {
|
||||
this.devicePersonSyncLogMapper.insertSelective(newSyncLog);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("新增同步记录失败,报错:{}", e.getMessage());
|
||||
}
|
||||
this.logger.debug("新增同步记录[{}],设备已拉取,count[1]", newSyncLog.getId());
|
||||
}
|
||||
private synchronized boolean lockSyncLog(String deviceId, String imageStoreId, String personId) {
|
||||
String value = deviceId + "_" + imageStoreId + "_" + personId;
|
||||
String key = "lock_sync_log_" + value;
|
||||
if (this.redisTemplate.hasKey(key).booleanValue()) {
|
||||
return false;
|
||||
}
|
||||
this.redisTemplate.opsForValue().set(key, value, this.syncLogExpireTime, TimeUnit.SECONDS);
|
||||
return true;
|
||||
}
|
||||
private synchronized boolean unlockSyncLog(String deviceId, String imageStoreId, String personId) {
|
||||
String value = deviceId + "_" + imageStoreId + "_" + personId;
|
||||
String key = "lock_sync_log_" + value;
|
||||
if (this.redisTemplate.hasKey(key).booleanValue()) {
|
||||
this.redisTemplate.delete(key);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/CpDeviceImagePersonServiceImpl.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+465
-473
@@ -1,6 +1,5 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
// 业务服务
|
||||
|
||||
import cn.cloudwalk.client.aggregate.application.service.ApplicationImageStoreService;
|
||||
import cn.cloudwalk.client.aggregate.common.enums.DelStatusEnum;
|
||||
import cn.cloudwalk.client.aggregate.common.enums.GroupModelStatusEnum;
|
||||
@@ -25,6 +24,7 @@ import cn.cloudwalk.data.organization.dto.LabelCriteriesDTO;
|
||||
import cn.cloudwalk.data.organization.dto.OrgCriteriesDTO;
|
||||
import cn.cloudwalk.data.organization.dto.QueryGroupPersonDTO;
|
||||
import cn.cloudwalk.data.organization.entity.GroupPersonRef;
|
||||
import cn.cloudwalk.data.organization.entity.ImgStorePerson;
|
||||
import cn.cloudwalk.data.organization.entity.ImgStorePersonLabel;
|
||||
import cn.cloudwalk.data.organization.entity.ImgStorePersonOrganization;
|
||||
import cn.cloudwalk.data.organization.entity.IsImageStoreAssociated;
|
||||
@@ -35,13 +35,10 @@ import cn.cloudwalk.data.organization.mapper.ImgStorePersonMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonOrganizationMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.IsImageStoreAssociatedMapper;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import cn.cloudwalk.service.organization.service.CpImageStorePersonTxHandler;
|
||||
import cn.cloudwalk.service.organization.service.CpImageStoreSyncManager;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
@@ -60,476 +57,471 @@ import org.springframework.transaction.support.TransactionSynchronizationManager
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springside.modules.utils.Collections3;
|
||||
|
||||
@Service
|
||||
public class CpImageStorePersonManager
|
||||
extends AbstractImagStoreService {
|
||||
private static final String LAST_SYNC_IMAGE_KEY = "cp_image_syn_last_flag";
|
||||
@Autowired
|
||||
private AgImageStoreService agImageStoreService;
|
||||
@Autowired
|
||||
private AgImageStoreImageService agImageStoreImageService;
|
||||
@Autowired
|
||||
private IsImageStoreAssociatedMapper imageStoreAssociatedMapper;
|
||||
@Autowired
|
||||
private ImgStorePersonLabelMapper imgStorePersonLabelMapper;
|
||||
@Autowired
|
||||
private ImgStorePersonMapper personMapper;
|
||||
@Autowired
|
||||
private ImgStorePersonOrganizationMapper imgStorePersonOrganizationMapper;
|
||||
@Autowired
|
||||
private GroupPersonRefMapper groupPersonRefMapper;
|
||||
@Resource
|
||||
private DevicePersonSyncLogMapper devicePersonSyncLogMapper;
|
||||
@Autowired
|
||||
private CpImageStoreSyncManager cpImageStoreSyncManager;
|
||||
@Resource
|
||||
private CpImageStorePersonTxHandler cpImageStorePersonTxHandler;
|
||||
@Autowired
|
||||
private StringRedisTemplate redisTemplate;
|
||||
@Resource
|
||||
private CpImageStoreToolService cpImageStoreToolService;
|
||||
@Resource
|
||||
private ApplicationImageStoreService appImageStoreService;
|
||||
private CloudwalkCallContext context;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
this.context = this.getCloudwalkContext();
|
||||
}
|
||||
|
||||
public Set<String> getImageStoreIdsByObjId(String objId, Integer associatedAction) {
|
||||
HashSet<String> imageStoreIdSet = new HashSet<String>();
|
||||
GetsImageStoreAssociatedDTO associatedParam = new GetsImageStoreAssociatedDTO();
|
||||
associatedParam.setAssociatedObjectId(objId);
|
||||
associatedParam.setAssociatedAction(associatedAction);
|
||||
List associatedList = this.imageStoreAssociatedMapper.gets(associatedParam);
|
||||
if (CollectionUtils.isEmpty((Collection)associatedList)) {
|
||||
return imageStoreIdSet;
|
||||
}
|
||||
associatedList.parallelStream().forEach(associated -> imageStoreIdSet.add(associated.getImageStoreId()));
|
||||
return imageStoreIdSet;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor={Exception.class}, isolation=Isolation.READ_COMMITTED)
|
||||
public Map<String, GroupPersonRef> getGroupPersonRefByPersons(String imageStoreId, List<String> personIds) {
|
||||
HashMap<String, GroupPersonRef> personResultMap = new HashMap<String, GroupPersonRef>(500);
|
||||
personIds.stream().forEach(personId -> {
|
||||
GroupPersonRef groupPersonRef;
|
||||
List<String> associatedObjectIds = this.getAssociatedObjectIdsByPersonId((String)personId);
|
||||
GetsImageStoreAssociatedDTO associatedParam = new GetsImageStoreAssociatedDTO();
|
||||
associatedParam.setImageStoreId(imageStoreId);
|
||||
associatedParam.setAssociatedObjectIds(associatedObjectIds);
|
||||
List associatedList = this.imageStoreAssociatedMapper.gets(associatedParam);
|
||||
if (Collections3.isNotEmpty((Collection)associatedList) && (groupPersonRef = this.matchGroupPersonRef(imageStoreId, (String)personId, associatedList)) != null) {
|
||||
personResultMap.put((String)personId, groupPersonRef);
|
||||
}
|
||||
});
|
||||
return personResultMap;
|
||||
}
|
||||
|
||||
private List<String> getAssociatedObjectIdsByPersonId(String personId) {
|
||||
ArrayList<String> associatedObjectIds = new ArrayList<String>();
|
||||
ImgStorePersonOrganization personOrgParam = new ImgStorePersonOrganization();
|
||||
personOrgParam.setPersonId(personId);
|
||||
List personOrgResult = this.imgStorePersonOrganizationMapper.select(personOrgParam);
|
||||
if (!CollectionUtils.isEmpty((Collection)personOrgResult)) {
|
||||
associatedObjectIds.addAll(Collections3.extractToList((Collection)personOrgResult, (String)"orgId"));
|
||||
}
|
||||
ImgStorePersonLabel personLabelParam = new ImgStorePersonLabel();
|
||||
personLabelParam.setPersonId(personId);
|
||||
List personLabelResult = this.imgStorePersonLabelMapper.select(personLabelParam);
|
||||
if (!CollectionUtils.isEmpty((Collection)personLabelResult)) {
|
||||
associatedObjectIds.addAll(Collections3.extractToList((Collection)personLabelResult, (String)"labelId"));
|
||||
}
|
||||
associatedObjectIds.add(personId);
|
||||
return associatedObjectIds;
|
||||
}
|
||||
|
||||
private GroupPersonRef matchGroupPersonRef(String imageStoreId, String personId, List<IsImageStoreAssociated> associatedList) {
|
||||
String matchPattern = CpImageStoreMatchPatternEnum.UNITE.getCode();
|
||||
GetsImageStoreAssociatedDTO matchParam = new GetsImageStoreAssociatedDTO();
|
||||
matchParam.setImageStoreId(imageStoreId);
|
||||
matchParam.setAssociatedObjectIdType(Integer.valueOf(4));
|
||||
List matchResultList = this.imageStoreAssociatedMapper.gets(matchParam);
|
||||
if (matchResultList != null && matchResultList.size() > 0) {
|
||||
matchPattern = ((IsImageStoreAssociated)matchResultList.get(0)).getAssociatedObjectId();
|
||||
}
|
||||
GetsImageStoreAssociatedDTO imageStoreAssociatedDTO = new GetsImageStoreAssociatedDTO();
|
||||
imageStoreAssociatedDTO.setImageStoreId(imageStoreId);
|
||||
imageStoreAssociatedDTO.setAssociatedAction(Integer.valueOf(0));
|
||||
imageStoreAssociatedDTO.setAssociatedObjectIdType(Integer.valueOf(5));
|
||||
List imageStoreAssociatedList = this.imageStoreAssociatedMapper.gets(imageStoreAssociatedDTO);
|
||||
IsImageStoreAssociated imageStoreAssociated = CollectionUtils.isEmpty((Collection)imageStoreAssociatedList) ? new IsImageStoreAssociated() : (IsImageStoreAssociated)imageStoreAssociatedList.get(0);
|
||||
int includeLabelNum = 0;
|
||||
int includeOrganizationNum = 0;
|
||||
int includePersonNum = 0;
|
||||
int excludeLabelNum = 0;
|
||||
int excludePersonNum = 0;
|
||||
GroupPersonRef groupPersonRef = new GroupPersonRef();
|
||||
groupPersonRef.setImageStoreId(imageStoreId);
|
||||
groupPersonRef.setPersonId(personId);
|
||||
groupPersonRef.setStatus(Short.valueOf((short)0));
|
||||
groupPersonRef.setExpiryBeginDate(imageStoreAssociated.getExpiryBeginDate());
|
||||
groupPersonRef.setExpiryEndDate(imageStoreAssociated.getExpiryEndDate());
|
||||
groupPersonRef.setValidDateCron(imageStoreAssociated.getValidDateCron());
|
||||
groupPersonRef.setStatus(Short.valueOf(this.checkGroupPersonStatus(imageStoreAssociated.getExpiryBeginDate(), imageStoreAssociated.getExpiryEndDate())));
|
||||
for (IsImageStoreAssociated associated : associatedList) {
|
||||
if (0 == associated.getAssociatedAction()) {
|
||||
if (1 == associated.getAssociatedObjectIdType()) {
|
||||
++includeOrganizationNum;
|
||||
continue;
|
||||
}
|
||||
if (2 == associated.getAssociatedObjectIdType()) {
|
||||
++includeLabelNum;
|
||||
continue;
|
||||
}
|
||||
if (3 != associated.getAssociatedObjectIdType()) continue;
|
||||
++includePersonNum;
|
||||
groupPersonRef.setExpiryBeginDate(associated.getExpiryBeginDate());
|
||||
groupPersonRef.setExpiryEndDate(associated.getExpiryEndDate());
|
||||
groupPersonRef.setValidDateCron(associated.getValidDateCron());
|
||||
groupPersonRef.setStatus(Short.valueOf(this.checkGroupPersonStatus(associated.getExpiryBeginDate(), associated.getExpiryEndDate())));
|
||||
continue;
|
||||
}
|
||||
if (1 != associated.getAssociatedAction()) continue;
|
||||
if (2 == associated.getAssociatedObjectIdType()) {
|
||||
++excludeLabelNum;
|
||||
continue;
|
||||
}
|
||||
if (3 != associated.getAssociatedObjectIdType()) continue;
|
||||
++excludePersonNum;
|
||||
}
|
||||
boolean match = false;
|
||||
if (CpImageStoreMatchPatternEnum.UNITE.getCode().equals(matchPattern)) {
|
||||
if (includeLabelNum > 0 && includeOrganizationNum > 0) {
|
||||
match = true;
|
||||
}
|
||||
} else if (includeLabelNum > 0 || includeOrganizationNum > 0) {
|
||||
match = true;
|
||||
}
|
||||
if (excludeLabelNum > 0) {
|
||||
match = false;
|
||||
}
|
||||
if (includePersonNum > 0) {
|
||||
match = true;
|
||||
}
|
||||
if (excludePersonNum > 0) {
|
||||
match = false;
|
||||
}
|
||||
if (match) {
|
||||
return groupPersonRef;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Map<String, GroupPersonRef> getImageStoreIdsByPerson(String personId) {
|
||||
HashMap<String, GroupPersonRef> personResultMap = new HashMap<String, GroupPersonRef>(500);
|
||||
List<String> associatedObjectIds = this.getAssociatedObjectIdsByPersonId(personId);
|
||||
GetsImageStoreAssociatedDTO associatedParam = new GetsImageStoreAssociatedDTO();
|
||||
associatedParam.setAssociatedObjectIds(associatedObjectIds);
|
||||
List associatedList = this.imageStoreAssociatedMapper.gets(associatedParam);
|
||||
if (CollectionUtils.isEmpty((Collection)associatedList)) {
|
||||
return personResultMap;
|
||||
}
|
||||
Map<String, List<IsImageStoreAssociated>> imageStoreAssociatedMap = (java.util.Map<java.lang.String,java.util.List<cn.cloudwalk.data.organization.entity.IsImageStoreAssociated>>) associatedList.stream().collect(Collectors.groupingBy(IsImageStoreAssociated::getImageStoreId));
|
||||
imageStoreAssociatedMap.keySet().forEach(key -> {
|
||||
GroupPersonRef groupPersonRef = this.matchGroupPersonRef((String)key, personId, (List)imageStoreAssociatedMap.get(key));
|
||||
if (groupPersonRef != null) {
|
||||
personResultMap.put((String)key, groupPersonRef);
|
||||
}
|
||||
});
|
||||
return personResultMap;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor={Exception.class}, isolation=Isolation.READ_COMMITTED)
|
||||
public Map<String, GroupPersonRef> getCurrentAssociatedPersonIds(String imageStoreId) {
|
||||
IsImageStoreAssociated finalIncludeImageStoreAssociated;
|
||||
HashSet addPersonIds;
|
||||
GetsImageStoreAssociatedDTO getsImageStoreAssociatedDTO = new GetsImageStoreAssociatedDTO();
|
||||
getsImageStoreAssociatedDTO.setImageStoreId(imageStoreId);
|
||||
List<IsImageStoreAssociated> associatedList = this.imageStoreAssociatedMapper.gets(getsImageStoreAssociatedDTO);
|
||||
String matchPattern = null;
|
||||
ArrayList<String> includeLabelIds = new ArrayList<String>();
|
||||
ArrayList<String> includeOrganizationIds = new ArrayList<String>();
|
||||
ArrayList<String> includePersonIds = new ArrayList<String>();
|
||||
HashMap<String, AssociatedResult> includePersonMap = new HashMap<String, AssociatedResult>();
|
||||
ArrayList<String> excludeLabelIds = new ArrayList<String>();
|
||||
ArrayList<String> excludePersonIds = new ArrayList<String>();
|
||||
IsImageStoreAssociated includeImageStoreAssociated = null;
|
||||
for (IsImageStoreAssociated associated : associatedList) {
|
||||
if (4 == associated.getAssociatedObjectIdType()) {
|
||||
matchPattern = associated.getAssociatedObjectId();
|
||||
continue;
|
||||
}
|
||||
if (0 == associated.getAssociatedAction()) {
|
||||
if (1 == associated.getAssociatedObjectIdType()) {
|
||||
includeOrganizationIds.add(associated.getAssociatedObjectId());
|
||||
continue;
|
||||
}
|
||||
if (2 == associated.getAssociatedObjectIdType()) {
|
||||
includeLabelIds.add(associated.getAssociatedObjectId());
|
||||
continue;
|
||||
}
|
||||
if (3 == associated.getAssociatedObjectIdType()) {
|
||||
includePersonIds.add(associated.getAssociatedObjectId());
|
||||
AssociatedResult associatedResult = new AssociatedResult();
|
||||
BeanCopyUtils.copyProperties((Object)associated, (Object)associatedResult);
|
||||
associatedResult.setObjectId(associated.getAssociatedObjectId());
|
||||
includePersonMap.put(associated.getAssociatedObjectId(), associatedResult);
|
||||
continue;
|
||||
}
|
||||
if (5 != associated.getAssociatedObjectIdType()) continue;
|
||||
includeImageStoreAssociated = associated;
|
||||
continue;
|
||||
}
|
||||
if (1 != associated.getAssociatedAction()) continue;
|
||||
if (2 == associated.getAssociatedObjectIdType()) {
|
||||
excludeLabelIds.add(associated.getAssociatedObjectId());
|
||||
continue;
|
||||
}
|
||||
if (3 != associated.getAssociatedObjectIdType()) continue;
|
||||
excludePersonIds.add(associated.getAssociatedObjectId());
|
||||
}
|
||||
LabelCriteriesDTO criteries = new LabelCriteriesDTO();
|
||||
HashMap<String, GroupPersonRef> personResultMap = new HashMap<String, GroupPersonRef>(500);
|
||||
Set addLabelPersonIds = null;
|
||||
Set addOrgPersonIds = null;
|
||||
if (!CollectionUtils.isEmpty(includeLabelIds)) {
|
||||
criteries.setLabelList(includeLabelIds);
|
||||
addLabelPersonIds = this.imgStorePersonLabelMapper.getPersonIdsByLabelAndCriteries(criteries);
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(includeOrganizationIds)) {
|
||||
OrgCriteriesDTO orgCriteries = new OrgCriteriesDTO();
|
||||
orgCriteries.setOrgIds(includeOrganizationIds);
|
||||
addOrgPersonIds = this.imgStorePersonOrganizationMapper.getPersonIdsByOrgIdsAndCriteries(orgCriteries);
|
||||
}
|
||||
if (CpImageStoreMatchPatternEnum.UNITE.getCode().equals(matchPattern)) {
|
||||
if (addLabelPersonIds != null && addOrgPersonIds != null) {
|
||||
addPersonIds = new HashSet(500);
|
||||
addPersonIds.addAll(addLabelPersonIds);
|
||||
addPersonIds.retainAll(addOrgPersonIds);
|
||||
finalIncludeImageStoreAssociated = includeImageStoreAssociated;
|
||||
addPersonIds.forEach(personId -> {
|
||||
GroupPersonRef groupPersonRef = new GroupPersonRef();
|
||||
groupPersonRef.setImageStoreId(imageStoreId);
|
||||
groupPersonRef.setPersonId(personId);
|
||||
groupPersonRef.setExpiryBeginDate((Long)Optional.ofNullable(finalIncludeImageStoreAssociated).map(associated -> associated.getExpiryBeginDate()).orElse(null));
|
||||
groupPersonRef.setExpiryEndDate((Long)Optional.ofNullable(finalIncludeImageStoreAssociated).map(associated -> associated.getExpiryEndDate()).orElse(null));
|
||||
groupPersonRef.setValidDateCron((String)Optional.ofNullable(finalIncludeImageStoreAssociated).map(associated -> associated.getValidDateCron()).orElse(null));
|
||||
groupPersonRef.setStatus(Short.valueOf(this.checkGroupPersonStatus(groupPersonRef.getExpiryBeginDate(), groupPersonRef.getExpiryEndDate())));
|
||||
personResultMap.put((String)personId, groupPersonRef);
|
||||
});
|
||||
}
|
||||
} else {
|
||||
addPersonIds = new HashSet(500);
|
||||
if (addLabelPersonIds != null) {
|
||||
addPersonIds.addAll(addLabelPersonIds);
|
||||
}
|
||||
if (addOrgPersonIds != null) {
|
||||
addPersonIds.addAll(addOrgPersonIds);
|
||||
}
|
||||
finalIncludeImageStoreAssociated = includeImageStoreAssociated;
|
||||
addPersonIds.forEach(personId -> {
|
||||
GroupPersonRef groupPersonRef = new GroupPersonRef();
|
||||
groupPersonRef.setImageStoreId(imageStoreId);
|
||||
groupPersonRef.setPersonId(personId);
|
||||
groupPersonRef.setExpiryBeginDate((Long)Optional.ofNullable(finalIncludeImageStoreAssociated).map(associated -> associated.getExpiryBeginDate()).orElse(null));
|
||||
groupPersonRef.setExpiryEndDate((Long)Optional.ofNullable(finalIncludeImageStoreAssociated).map(associated -> associated.getExpiryEndDate()).orElse(null));
|
||||
groupPersonRef.setValidDateCron((String)Optional.ofNullable(finalIncludeImageStoreAssociated).map(associated -> associated.getValidDateCron()).orElse(null));
|
||||
groupPersonRef.setStatus(Short.valueOf(this.checkGroupPersonStatus(groupPersonRef.getExpiryBeginDate(), groupPersonRef.getExpiryEndDate())));
|
||||
personResultMap.put((String)personId, groupPersonRef);
|
||||
});
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(excludeLabelIds)) {
|
||||
criteries = new LabelCriteriesDTO();
|
||||
criteries.setLabelList(excludeLabelIds);
|
||||
Set removePersonIds = this.imgStorePersonLabelMapper.getPersonIdsByLabelAndCriteries(criteries);
|
||||
removePersonIds.forEach(personResultMap::remove);
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(includePersonIds)) {
|
||||
ImgStorePersonQueryDto record = new ImgStorePersonQueryDto();
|
||||
record.setIds(includePersonIds);
|
||||
record.setIsDel(Short.valueOf((short)0));
|
||||
List gets = this.personMapper.gets(record);
|
||||
if (gets != null && gets.size() > 0) {
|
||||
gets.forEach(imgStorePerson -> {
|
||||
AssociatedResult associatedResult = (AssociatedResult)includePersonMap.get(imgStorePerson.getId());
|
||||
GroupPersonRef groupPersonRef = new GroupPersonRef();
|
||||
groupPersonRef.setImageStoreId(imageStoreId);
|
||||
groupPersonRef.setPersonId(associatedResult.getObjectId());
|
||||
groupPersonRef.setExpiryBeginDate(associatedResult.getExpiryBeginDate());
|
||||
groupPersonRef.setExpiryEndDate(associatedResult.getExpiryEndDate());
|
||||
groupPersonRef.setValidDateCron(associatedResult.getValidDateCron());
|
||||
groupPersonRef.setStatus(Short.valueOf(this.checkGroupPersonStatus(associatedResult.getExpiryBeginDate(), associatedResult.getExpiryEndDate())));
|
||||
personResultMap.put(imgStorePerson.getId(), groupPersonRef);
|
||||
});
|
||||
}
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(excludePersonIds)) {
|
||||
excludePersonIds.forEach(personResultMap::remove);
|
||||
}
|
||||
if (!TransactionSynchronizationManager.isActualTransactionActive()) {
|
||||
this.logger.error("getCurrentAssociatedPersonIds接口 事务未生效");
|
||||
}
|
||||
return personResultMap;
|
||||
}
|
||||
|
||||
Map<String, GroupPersonRef> getOldAssociatedPersonIds(String imageStoreId, List<String> personIds) {
|
||||
QueryGroupPersonDTO queryGroupPersonDTO = new QueryGroupPersonDTO();
|
||||
queryGroupPersonDTO.setImageStoreId(imageStoreId);
|
||||
if (Collections3.isNotEmpty(personIds)) {
|
||||
queryGroupPersonDTO.setPersonIds(personIds);
|
||||
}
|
||||
List oldPersonList = this.groupPersonRefMapper.query(queryGroupPersonDTO);
|
||||
HashMap<String, GroupPersonRef> oldPersonResultMap = new HashMap<String, GroupPersonRef>(500);
|
||||
oldPersonList.forEach(groupPersonRef -> oldPersonResultMap.put(groupPersonRef.getPersonId(), (GroupPersonRef)groupPersonRef));
|
||||
return oldPersonResultMap;
|
||||
}
|
||||
|
||||
public void handleGroupPersonChange() throws ServiceException {
|
||||
this.logger.info("开始图库图片同步:[{}]", (Object)System.currentTimeMillis());
|
||||
Long lastSynTime = 0L;
|
||||
String lastImageId = "0";
|
||||
String lastImageStoreId = null;
|
||||
ImgStorePersonQueryDto imgStorePersonQuery = null;
|
||||
GroupPersonRef groupPersonRef = null;
|
||||
AgImageStoreImageResult lastResult = null;
|
||||
while (true) {
|
||||
if (this.redisTemplate.hasKey(LAST_SYNC_IMAGE_KEY).booleanValue()) {
|
||||
String lastFlagValue = (String)this.redisTemplate.opsForValue().get((Object)LAST_SYNC_IMAGE_KEY);
|
||||
lastSynTime = Long.valueOf(lastFlagValue.split(",")[0]);
|
||||
lastImageId = lastFlagValue.split(",")[1];
|
||||
this.logger.info("获取缓存数据,key={},value={}", (Object)LAST_SYNC_IMAGE_KEY, (Object)lastFlagValue);
|
||||
}
|
||||
AgImageStoreImageSyncParam imageQuery = new AgImageStoreImageSyncParam();
|
||||
imageQuery.setLastSynTime(lastSynTime);
|
||||
imageQuery.setLastImageId(lastImageId);
|
||||
imageQuery.setImageStoreId(lastImageStoreId);
|
||||
CloudwalkResult imageQueryResult = this.agImageStoreImageService.sync(imageQuery);
|
||||
if (!imageQueryResult.isSuccess()) {
|
||||
this.logger.error("图库图片同步失败,result:{}", (Object)JSONObject.toJSONString((Object)imageQueryResult));
|
||||
throw new ServiceException(imageQueryResult.getCode(), imageQueryResult.getMessage());
|
||||
}
|
||||
List<AgImageStoreImageResult> resultList = (List)imageQueryResult.getData();
|
||||
if (CollectionUtils.isEmpty((Collection)resultList)) break;
|
||||
for (AgImageStoreImageResult result : resultList) {
|
||||
try {
|
||||
boolean needChangeStatus;
|
||||
imgStorePersonQuery = new ImgStorePersonQueryDto();
|
||||
imgStorePersonQuery.setImageId(result.getImageId());
|
||||
List getsResult = this.personMapper.gets(imgStorePersonQuery);
|
||||
if (CollectionUtils.isEmpty((Collection)getsResult)) {
|
||||
this.logger.warn("图库图片同步失败,根据imageId:[{}]获取不到人员信息", (Object)result.getImageId());
|
||||
continue;
|
||||
}
|
||||
groupPersonRef = new GroupPersonRef();
|
||||
groupPersonRef.setImageStoreId(result.getImageStoreId());
|
||||
List groupPersonRefList = this.groupPersonRefMapper.selectByCondition(groupPersonRef, Collections3.extractToList((Collection)getsResult, (String)"id"));
|
||||
if (CollectionUtils.isEmpty((Collection)groupPersonRefList)) {
|
||||
this.logger.warn("图库图片同步失败,根据imageStoreId:[{}],personId:[{}]获取不到图库人员列表信息", (Object)result.getImageStoreId(), (Object)Collections3.extractToString((Collection)getsResult, (String)"id", (String)","));
|
||||
continue;
|
||||
}
|
||||
groupPersonRef.setGender(result.getGender());
|
||||
groupPersonRef.setAge(result.getAge());
|
||||
groupPersonRef.setGroupTime(result.getGroupTime());
|
||||
boolean bl = needChangeStatus = DelStatusEnum.DELETED.getCode().shortValue() == result.getIsDel().shortValue() && (GroupModelStatusEnum.MODEL_ING.getCode().shortValue() == result.getStatus().shortValue() || GroupModelStatusEnum.MODEL_COMPLETED.getCode().shortValue() == result.getStatus().shortValue());
|
||||
if (needChangeStatus) {
|
||||
groupPersonRef.setGroupStatus(GroupModelStatusEnum.MODEL_WAIT.getCode());
|
||||
} else {
|
||||
groupPersonRef.setGroupStatus(result.getStatus());
|
||||
}
|
||||
groupPersonRef.setErrorMessage(result.getErrorMessage());
|
||||
this.groupPersonRefMapper.updateImageDataByIds(groupPersonRef, Collections3.extractToList((Collection)groupPersonRefList, (String)"id"));
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("handleGroupPersonChange exception,imageStoreId:[{}],imageId:[{}]", new Object[]{result.getImageStoreId(), result.getImageId(), e});
|
||||
}
|
||||
}
|
||||
lastResult = (AgImageStoreImageResult)resultList.get(resultList.size() - 1);
|
||||
if (null == lastResult) continue;
|
||||
if (null == lastResult.getLastUpdateTime()) {
|
||||
lastResult.setLastUpdateTime(lastSynTime);
|
||||
this.logger.warn("最后更新时间为空,imageStoreId:[{}],imageId:[{}]", (Object)lastResult.getImageStoreId(), (Object)lastResult.getImageId());
|
||||
}
|
||||
this.redisTemplate.opsForValue().set(LAST_SYNC_IMAGE_KEY, (Object)(lastResult.getLastUpdateTime() + "," + lastResult.getImageId()));
|
||||
this.logger.info("设置缓存数据,key={},value={}", (Object)LAST_SYNC_IMAGE_KEY, (Object)(lastResult.getLastUpdateTime() + "," + lastResult.getImageId()));
|
||||
}
|
||||
this.logger.warn("没有需要同步的图库图片");
|
||||
this.logger.info("结束图库图片同步:{}", (Object)System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public void handleGroupPersonChange2() throws ServiceException {
|
||||
this.logger.info("开始图库图片同步:[{}]", (Object)System.currentTimeMillis());
|
||||
Long syncTime = System.currentTimeMillis() - 600000L;
|
||||
List syncList = this.groupPersonRefMapper.waitSyncList(syncTime);
|
||||
if (CollectionUtils.isEmpty((Collection)syncList)) {
|
||||
this.logger.warn("没有需要同步的图库图片");
|
||||
return;
|
||||
}
|
||||
Map<String, List<GroupPersonRefDTO>> groupSyncList = (java.util.Map<java.lang.String,java.util.List<cn.cloudwalk.data.organization.dto.GroupPersonRefDTO>>) syncList.stream().collect(Collectors.groupingBy(GroupPersonRef::getImageStoreId));
|
||||
for (Map.Entry<String, List<GroupPersonRefDTO>> entry : groupSyncList.entrySet()) {
|
||||
String imageStoreId = entry.getKey();
|
||||
this.updateGroupPerson(imageStoreId, entry.getValue());
|
||||
}
|
||||
this.logger.info("结束图库图片同步:{}", (Object)System.currentTimeMillis());
|
||||
}
|
||||
|
||||
private void updateGroupPerson(String imageStoreId, List<GroupPersonRefDTO> list) {
|
||||
CpSearchFaceParam param = new CpSearchFaceParam();
|
||||
param.setImageStoreId(imageStoreId);
|
||||
param.setImageIds(String.join((CharSequence)",", Collections3.extractToList(list, (String)"imageId")));
|
||||
List<SearchFaceResult> resultList = null;
|
||||
if (list.size() > 1) {
|
||||
CloudwalkResult batchSearchFaceResult = this.cpImageStoreToolService.batchSearchFace(param);
|
||||
if (null == batchSearchFaceResult || !batchSearchFaceResult.isSuccess()) {
|
||||
return;
|
||||
}
|
||||
resultList = ((BatchSearchFaceResult)batchSearchFaceResult.getData()).getItems();
|
||||
} else {
|
||||
CloudwalkResult searchFaceResult = this.cpImageStoreToolService.searchFace(param);
|
||||
if (null == searchFaceResult || !searchFaceResult.isSuccess()) {
|
||||
return;
|
||||
}
|
||||
resultList = Arrays.asList((SearchFaceResult)searchFaceResult.getData());
|
||||
}
|
||||
if (null == resultList) {
|
||||
return;
|
||||
}
|
||||
ImgStorePersonQueryDto imgStorePersonQuery = null;
|
||||
GroupPersonRef groupPersonRef = null;
|
||||
for (SearchFaceResult result : resultList) {
|
||||
if (StringUtils.isEmpty((Object)result.getUserId())) {
|
||||
this.logger.warn("图库图片同步失败,imageId为空:[{}]", (Object)result.getUserId());
|
||||
continue;
|
||||
}
|
||||
imgStorePersonQuery = new ImgStorePersonQueryDto();
|
||||
imgStorePersonQuery.setImageId(result.getUserId());
|
||||
List getsResult = this.personMapper.gets(imgStorePersonQuery);
|
||||
if (CollectionUtils.isEmpty((Collection)getsResult)) {
|
||||
this.logger.warn("图库图片同步失败,根据imageId:[{}]获取不到人员信息", (Object)result.getUserId());
|
||||
continue;
|
||||
}
|
||||
groupPersonRef = new GroupPersonRef();
|
||||
groupPersonRef.setImageStoreId(imageStoreId);
|
||||
List groupPersonRefList = this.groupPersonRefMapper.selectByCondition(groupPersonRef, Collections3.extractToList((Collection)getsResult, (String)"id"));
|
||||
if (CollectionUtils.isEmpty((Collection)groupPersonRefList)) {
|
||||
this.logger.warn("图库图片同步失败,根据imageStoreId:[{}],personId:[{}]获取不到图库人员列表信息", (Object)imageStoreId, (Object)Collections3.extractToString((Collection)getsResult, (String)"id", (String)","));
|
||||
continue;
|
||||
}
|
||||
groupPersonRef.setGroupStatus(GroupModelStatusEnum.MODEL_WAIT.getCode());
|
||||
if (result.getResult() == 0) {
|
||||
groupPersonRef.setGroupStatus(GroupModelStatusEnum.MODEL_COMPLETED.getCode());
|
||||
}
|
||||
groupPersonRef.setGroupTime(result.getTime());
|
||||
groupPersonRef.setErrorMessage(result.getInfo());
|
||||
if (!StringUtils.isEmpty((Object)result.getQualityScore())) {
|
||||
List<String> qualityScoreList = Arrays.asList(result.getQualityScore().split(","));
|
||||
groupPersonRef.setAge(Integer.valueOf(new BigDecimal(qualityScoreList.get(10)).setScale(0, 3).intValue()));
|
||||
groupPersonRef.setGender(Short.valueOf(new BigDecimal(qualityScoreList.get(11)).shortValue()));
|
||||
}
|
||||
this.groupPersonRefMapper.updateImageDataByIds(groupPersonRef, Collections3.extractToList((Collection)groupPersonRefList, (String)"id"));
|
||||
}
|
||||
}
|
||||
extends AbstractImagStoreService
|
||||
{
|
||||
private static final String LAST_SYNC_IMAGE_KEY = "cp_image_syn_last_flag";
|
||||
@Autowired
|
||||
private AgImageStoreService agImageStoreService;
|
||||
@Autowired
|
||||
private AgImageStoreImageService agImageStoreImageService;
|
||||
@Autowired
|
||||
private IsImageStoreAssociatedMapper imageStoreAssociatedMapper;
|
||||
@Autowired
|
||||
private ImgStorePersonLabelMapper imgStorePersonLabelMapper;
|
||||
@Autowired
|
||||
private ImgStorePersonMapper personMapper;
|
||||
@Autowired
|
||||
private ImgStorePersonOrganizationMapper imgStorePersonOrganizationMapper;
|
||||
@Autowired
|
||||
private GroupPersonRefMapper groupPersonRefMapper;
|
||||
@Resource
|
||||
private DevicePersonSyncLogMapper devicePersonSyncLogMapper;
|
||||
@Autowired
|
||||
private CpImageStoreSyncManager cpImageStoreSyncManager;
|
||||
@Resource
|
||||
private CpImageStorePersonTxHandler cpImageStorePersonTxHandler;
|
||||
@Autowired
|
||||
private StringRedisTemplate redisTemplate;
|
||||
@Resource
|
||||
private CpImageStoreToolService cpImageStoreToolService;
|
||||
@Resource
|
||||
private ApplicationImageStoreService appImageStoreService;
|
||||
private CloudwalkCallContext context;
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
this.context = getCloudwalkContext();
|
||||
}
|
||||
public Set<String> getImageStoreIdsByObjId(String objId, Integer associatedAction) {
|
||||
Set<String> imageStoreIdSet = new HashSet<>();
|
||||
GetsImageStoreAssociatedDTO associatedParam = new GetsImageStoreAssociatedDTO();
|
||||
associatedParam.setAssociatedObjectId(objId);
|
||||
associatedParam.setAssociatedAction(associatedAction);
|
||||
List<IsImageStoreAssociated> associatedList = this.imageStoreAssociatedMapper.gets(associatedParam);
|
||||
if (CollectionUtils.isEmpty(associatedList)) {
|
||||
return imageStoreIdSet;
|
||||
}
|
||||
associatedList.parallelStream().forEach(associated -> imageStoreIdSet.add(associated.getImageStoreId()));
|
||||
return imageStoreIdSet;
|
||||
}
|
||||
@Transactional(rollbackFor = {Exception.class}, isolation = Isolation.READ_COMMITTED)
|
||||
public Map<String, GroupPersonRef> getGroupPersonRefByPersons(String imageStoreId, List<String> personIds) {
|
||||
Map<String, GroupPersonRef> personResultMap = new HashMap<>(500);
|
||||
personIds.stream().forEach(personId -> {
|
||||
List<String> associatedObjectIds = getAssociatedObjectIdsByPersonId(personId);
|
||||
GetsImageStoreAssociatedDTO associatedParam = new GetsImageStoreAssociatedDTO();
|
||||
associatedParam.setImageStoreId(imageStoreId);
|
||||
associatedParam.setAssociatedObjectIds(associatedObjectIds);
|
||||
List<IsImageStoreAssociated> associatedList = this.imageStoreAssociatedMapper.gets(associatedParam);
|
||||
if (Collections3.isNotEmpty(associatedList)) {
|
||||
GroupPersonRef groupPersonRef = matchGroupPersonRef(imageStoreId, personId, associatedList);
|
||||
if (groupPersonRef != null) {
|
||||
personResultMap.put(personId, groupPersonRef);
|
||||
}
|
||||
}
|
||||
});
|
||||
return personResultMap;
|
||||
}
|
||||
private List<String> getAssociatedObjectIdsByPersonId(String personId) {
|
||||
List<String> associatedObjectIds = new ArrayList<>();
|
||||
ImgStorePersonOrganization personOrgParam = new ImgStorePersonOrganization();
|
||||
personOrgParam.setPersonId(personId);
|
||||
List<ImgStorePersonOrganization> personOrgResult = this.imgStorePersonOrganizationMapper.select(personOrgParam);
|
||||
if (!CollectionUtils.isEmpty(personOrgResult)) {
|
||||
associatedObjectIds.addAll(Collections3.extractToList(personOrgResult, "orgId"));
|
||||
}
|
||||
ImgStorePersonLabel personLabelParam = new ImgStorePersonLabel();
|
||||
personLabelParam.setPersonId(personId);
|
||||
List<ImgStorePersonLabel> personLabelResult = this.imgStorePersonLabelMapper.select(personLabelParam);
|
||||
if (!CollectionUtils.isEmpty(personLabelResult)) {
|
||||
associatedObjectIds.addAll(Collections3.extractToList(personLabelResult, "labelId"));
|
||||
}
|
||||
associatedObjectIds.add(personId);
|
||||
return associatedObjectIds;
|
||||
}
|
||||
private GroupPersonRef matchGroupPersonRef(String imageStoreId, String personId, List<IsImageStoreAssociated> associatedList) {
|
||||
String matchPattern = CpImageStoreMatchPatternEnum.UNITE.getCode();
|
||||
GetsImageStoreAssociatedDTO matchParam = new GetsImageStoreAssociatedDTO();
|
||||
matchParam.setImageStoreId(imageStoreId);
|
||||
matchParam.setAssociatedObjectIdType(Integer.valueOf(4));
|
||||
List<IsImageStoreAssociated> matchResultList = this.imageStoreAssociatedMapper.gets(matchParam);
|
||||
if (matchResultList != null && matchResultList.size() > 0) {
|
||||
matchPattern = ((IsImageStoreAssociated)matchResultList.get(0)).getAssociatedObjectId();
|
||||
}
|
||||
GetsImageStoreAssociatedDTO imageStoreAssociatedDTO = new GetsImageStoreAssociatedDTO();
|
||||
imageStoreAssociatedDTO.setImageStoreId(imageStoreId);
|
||||
imageStoreAssociatedDTO.setAssociatedAction(Integer.valueOf(0));
|
||||
imageStoreAssociatedDTO.setAssociatedObjectIdType(Integer.valueOf(5));
|
||||
List<IsImageStoreAssociated> imageStoreAssociatedList = this.imageStoreAssociatedMapper.gets(imageStoreAssociatedDTO);
|
||||
IsImageStoreAssociated imageStoreAssociated = CollectionUtils.isEmpty(imageStoreAssociatedList) ? new IsImageStoreAssociated() : imageStoreAssociatedList.get(0);
|
||||
int includeLabelNum = 0;
|
||||
int includeOrganizationNum = 0;
|
||||
int includePersonNum = 0;
|
||||
int excludeLabelNum = 0;
|
||||
int excludePersonNum = 0;
|
||||
GroupPersonRef groupPersonRef = new GroupPersonRef();
|
||||
groupPersonRef.setImageStoreId(imageStoreId);
|
||||
groupPersonRef.setPersonId(personId);
|
||||
groupPersonRef.setStatus(Short.valueOf((short)0));
|
||||
groupPersonRef.setExpiryBeginDate(imageStoreAssociated.getExpiryBeginDate());
|
||||
groupPersonRef.setExpiryEndDate(imageStoreAssociated.getExpiryEndDate());
|
||||
groupPersonRef.setValidDateCron(imageStoreAssociated.getValidDateCron());
|
||||
groupPersonRef.setStatus(Short.valueOf(checkGroupPersonStatus(imageStoreAssociated.getExpiryBeginDate(), imageStoreAssociated
|
||||
.getExpiryEndDate())));
|
||||
for (IsImageStoreAssociated associated : associatedList) {
|
||||
if (0 == associated.getAssociatedAction().intValue()) {
|
||||
if (1 == associated.getAssociatedObjectIdType().intValue()) {
|
||||
includeOrganizationNum++; continue;
|
||||
} if (2 == associated
|
||||
.getAssociatedObjectIdType().intValue()) {
|
||||
includeLabelNum++; continue;
|
||||
} if (3 == associated
|
||||
.getAssociatedObjectIdType().intValue()) {
|
||||
includePersonNum++;
|
||||
groupPersonRef.setExpiryBeginDate(associated.getExpiryBeginDate());
|
||||
groupPersonRef.setExpiryEndDate(associated.getExpiryEndDate());
|
||||
groupPersonRef.setValidDateCron(associated.getValidDateCron());
|
||||
groupPersonRef.setStatus(Short.valueOf(checkGroupPersonStatus(associated.getExpiryBeginDate(), associated
|
||||
.getExpiryEndDate())));
|
||||
} continue;
|
||||
} if (1 == associated.getAssociatedAction().intValue()) {
|
||||
if (2 == associated.getAssociatedObjectIdType().intValue()) {
|
||||
excludeLabelNum++; continue;
|
||||
} if (3 == associated
|
||||
.getAssociatedObjectIdType().intValue()) {
|
||||
excludePersonNum++;
|
||||
}
|
||||
}
|
||||
}
|
||||
boolean match = false;
|
||||
if (CpImageStoreMatchPatternEnum.UNITE.getCode().equals(matchPattern)) {
|
||||
if (includeLabelNum > 0 && includeOrganizationNum > 0) {
|
||||
match = true;
|
||||
}
|
||||
}
|
||||
else if (includeLabelNum > 0 || includeOrganizationNum > 0) {
|
||||
match = true;
|
||||
}
|
||||
if (excludeLabelNum > 0) {
|
||||
match = false;
|
||||
}
|
||||
if (includePersonNum > 0) {
|
||||
match = true;
|
||||
}
|
||||
if (excludePersonNum > 0) {
|
||||
match = false;
|
||||
}
|
||||
if (match) {
|
||||
return groupPersonRef;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public Map<String, GroupPersonRef> getImageStoreIdsByPerson(String personId) {
|
||||
Map<String, GroupPersonRef> personResultMap = new HashMap<>(500);
|
||||
List<String> associatedObjectIds = getAssociatedObjectIdsByPersonId(personId);
|
||||
GetsImageStoreAssociatedDTO associatedParam = new GetsImageStoreAssociatedDTO();
|
||||
associatedParam.setAssociatedObjectIds(associatedObjectIds);
|
||||
List<IsImageStoreAssociated> associatedList = this.imageStoreAssociatedMapper.gets(associatedParam);
|
||||
if (CollectionUtils.isEmpty(associatedList)) {
|
||||
return personResultMap;
|
||||
}
|
||||
Map<String, List<IsImageStoreAssociated>> imageStoreAssociatedMap = (Map<String, List<IsImageStoreAssociated>>)associatedList.stream().collect(Collectors.groupingBy(IsImageStoreAssociated::getImageStoreId));
|
||||
imageStoreAssociatedMap.keySet().forEach(key -> {
|
||||
GroupPersonRef groupPersonRef = matchGroupPersonRef(key, personId, (List<IsImageStoreAssociated>)imageStoreAssociatedMap.get(key));
|
||||
if (groupPersonRef != null) {
|
||||
personResultMap.put(key, groupPersonRef);
|
||||
}
|
||||
});
|
||||
return personResultMap;
|
||||
}
|
||||
@Transactional(rollbackFor = {Exception.class}, isolation = Isolation.READ_COMMITTED)
|
||||
public Map<String, GroupPersonRef> getCurrentAssociatedPersonIds(String imageStoreId) {
|
||||
GetsImageStoreAssociatedDTO getsImageStoreAssociatedDTO = new GetsImageStoreAssociatedDTO();
|
||||
getsImageStoreAssociatedDTO.setImageStoreId(imageStoreId);
|
||||
List<IsImageStoreAssociated> associatedList = this.imageStoreAssociatedMapper.gets(getsImageStoreAssociatedDTO);
|
||||
String matchPattern = null;
|
||||
List<String> includeLabelIds = new ArrayList<>();
|
||||
List<String> includeOrganizationIds = new ArrayList<>();
|
||||
List<String> includePersonIds = new ArrayList<>();
|
||||
Map<String, AssociatedResult> includePersonMap = new HashMap<>();
|
||||
List<String> excludeLabelIds = new ArrayList<>();
|
||||
List<String> excludePersonIds = new ArrayList<>();
|
||||
IsImageStoreAssociated includeImageStoreAssociated = null;
|
||||
for (IsImageStoreAssociated associated : associatedList) {
|
||||
if (4 == associated.getAssociatedObjectIdType().intValue()) {
|
||||
matchPattern = associated.getAssociatedObjectId(); continue;
|
||||
}
|
||||
if (0 == associated.getAssociatedAction().intValue()) {
|
||||
if (1 == associated.getAssociatedObjectIdType().intValue()) {
|
||||
includeOrganizationIds.add(associated.getAssociatedObjectId()); continue;
|
||||
} if (2 == associated
|
||||
.getAssociatedObjectIdType().intValue()) {
|
||||
includeLabelIds.add(associated.getAssociatedObjectId()); continue;
|
||||
} if (3 == associated
|
||||
.getAssociatedObjectIdType().intValue()) {
|
||||
includePersonIds.add(associated.getAssociatedObjectId());
|
||||
AssociatedResult associatedResult = new AssociatedResult();
|
||||
BeanCopyUtils.copyProperties(associated, associatedResult);
|
||||
associatedResult.setObjectId(associated.getAssociatedObjectId());
|
||||
includePersonMap.put(associated.getAssociatedObjectId(), associatedResult); continue;
|
||||
} if (5 == associated.getAssociatedObjectIdType().intValue())
|
||||
{
|
||||
includeImageStoreAssociated = associated; } continue;
|
||||
}
|
||||
if (1 == associated.getAssociatedAction().intValue()) {
|
||||
if (2 == associated.getAssociatedObjectIdType().intValue()) {
|
||||
excludeLabelIds.add(associated.getAssociatedObjectId()); continue;
|
||||
} if (3 == associated
|
||||
.getAssociatedObjectIdType().intValue()) {
|
||||
excludePersonIds.add(associated.getAssociatedObjectId());
|
||||
}
|
||||
}
|
||||
}
|
||||
LabelCriteriesDTO criteries = new LabelCriteriesDTO();
|
||||
Map<String, GroupPersonRef> personResultMap = new HashMap<>(500);
|
||||
Set<String> addLabelPersonIds = null;
|
||||
Set<String> addOrgPersonIds = null;
|
||||
if (!CollectionUtils.isEmpty(includeLabelIds)) {
|
||||
criteries.setLabelList(includeLabelIds);
|
||||
addLabelPersonIds = this.imgStorePersonLabelMapper.getPersonIdsByLabelAndCriteries(criteries);
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(includeOrganizationIds)) {
|
||||
OrgCriteriesDTO orgCriteries = new OrgCriteriesDTO();
|
||||
orgCriteries.setOrgIds(includeOrganizationIds);
|
||||
addOrgPersonIds = this.imgStorePersonOrganizationMapper.getPersonIdsByOrgIdsAndCriteries(orgCriteries);
|
||||
}
|
||||
if (CpImageStoreMatchPatternEnum.UNITE.getCode().equals(matchPattern)) {
|
||||
if (addLabelPersonIds != null && addOrgPersonIds != null) {
|
||||
Set<String> addPersonIds = new HashSet<>(500);
|
||||
addPersonIds.addAll(addLabelPersonIds);
|
||||
addPersonIds.retainAll(addOrgPersonIds);
|
||||
IsImageStoreAssociated finalIncludeImageStoreAssociated = includeImageStoreAssociated;
|
||||
addPersonIds.forEach(personId -> {
|
||||
GroupPersonRef groupPersonRef = new GroupPersonRef();
|
||||
groupPersonRef.setImageStoreId(imageStoreId);
|
||||
groupPersonRef.setPersonId(personId);
|
||||
groupPersonRef.setExpiryBeginDate(Optional.ofNullable(finalIncludeImageStoreAssociated).map(IsImageStoreAssociated::getExpiryBeginDate).orElse(null));
|
||||
groupPersonRef.setExpiryEndDate(Optional.ofNullable(finalIncludeImageStoreAssociated).map(IsImageStoreAssociated::getExpiryEndDate).orElse(null));
|
||||
groupPersonRef.setValidDateCron(Optional.ofNullable(finalIncludeImageStoreAssociated).map(IsImageStoreAssociated::getValidDateCron).orElse(null));
|
||||
groupPersonRef.setStatus(Short.valueOf(checkGroupPersonStatus(groupPersonRef.getExpiryBeginDate(), groupPersonRef.getExpiryEndDate())));
|
||||
personResultMap.put(personId, groupPersonRef);
|
||||
});
|
||||
}
|
||||
} else {
|
||||
Set<String> addPersonIds = new HashSet<>(500);
|
||||
if (addLabelPersonIds != null) {
|
||||
addPersonIds.addAll(addLabelPersonIds);
|
||||
}
|
||||
if (addOrgPersonIds != null) {
|
||||
addPersonIds.addAll(addOrgPersonIds);
|
||||
}
|
||||
IsImageStoreAssociated finalIncludeImageStoreAssociated = includeImageStoreAssociated;
|
||||
addPersonIds.forEach(personId -> {
|
||||
GroupPersonRef groupPersonRef = new GroupPersonRef();
|
||||
groupPersonRef.setImageStoreId(imageStoreId);
|
||||
groupPersonRef.setPersonId(personId);
|
||||
groupPersonRef.setExpiryBeginDate(Optional.ofNullable(finalIncludeImageStoreAssociated).map(IsImageStoreAssociated::getExpiryBeginDate).orElse(null));
|
||||
groupPersonRef.setExpiryEndDate(Optional.ofNullable(finalIncludeImageStoreAssociated).map(IsImageStoreAssociated::getExpiryEndDate).orElse(null));
|
||||
groupPersonRef.setValidDateCron(Optional.ofNullable(finalIncludeImageStoreAssociated).map(IsImageStoreAssociated::getValidDateCron).orElse(null));
|
||||
groupPersonRef.setStatus(Short.valueOf(checkGroupPersonStatus(groupPersonRef.getExpiryBeginDate(), groupPersonRef.getExpiryEndDate())));
|
||||
personResultMap.put(personId, groupPersonRef);
|
||||
});
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(excludeLabelIds)) {
|
||||
criteries = new LabelCriteriesDTO();
|
||||
criteries.setLabelList(excludeLabelIds);
|
||||
Set<String> removePersonIds = this.imgStorePersonLabelMapper.getPersonIdsByLabelAndCriteries(criteries);
|
||||
removePersonIds.forEach(personResultMap::remove);
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(includePersonIds)) {
|
||||
ImgStorePersonQueryDto record = new ImgStorePersonQueryDto();
|
||||
record.setIds(includePersonIds);
|
||||
record.setIsDel(Short.valueOf((short)0));
|
||||
List<ImgStorePerson> gets = this.personMapper.gets(record);
|
||||
if (gets != null && gets.size() > 0) {
|
||||
gets.forEach(imgStorePerson -> {
|
||||
AssociatedResult associatedResult = (AssociatedResult)includePersonMap.get(imgStorePerson.getId());
|
||||
GroupPersonRef groupPersonRef = new GroupPersonRef();
|
||||
groupPersonRef.setImageStoreId(imageStoreId);
|
||||
groupPersonRef.setPersonId(associatedResult.getObjectId());
|
||||
groupPersonRef.setExpiryBeginDate(associatedResult.getExpiryBeginDate());
|
||||
groupPersonRef.setExpiryEndDate(associatedResult.getExpiryEndDate());
|
||||
groupPersonRef.setValidDateCron(associatedResult.getValidDateCron());
|
||||
groupPersonRef.setStatus(Short.valueOf(checkGroupPersonStatus(associatedResult.getExpiryBeginDate(), associatedResult.getExpiryEndDate())));
|
||||
personResultMap.put(imgStorePerson.getId(), groupPersonRef);
|
||||
});
|
||||
}
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(excludePersonIds)) {
|
||||
excludePersonIds.forEach(personResultMap::remove);
|
||||
}
|
||||
if (!TransactionSynchronizationManager.isActualTransactionActive()) {
|
||||
this.logger.error("getCurrentAssociatedPersonIds接口 事务未生效");
|
||||
}
|
||||
return personResultMap;
|
||||
}
|
||||
Map<String, GroupPersonRef> getOldAssociatedPersonIds(String imageStoreId, List<String> personIds) {
|
||||
QueryGroupPersonDTO queryGroupPersonDTO = new QueryGroupPersonDTO();
|
||||
queryGroupPersonDTO.setImageStoreId(imageStoreId);
|
||||
if (Collections3.isNotEmpty(personIds)) {
|
||||
queryGroupPersonDTO.setPersonIds(personIds);
|
||||
}
|
||||
List<GroupPersonRef> oldPersonList = this.groupPersonRefMapper.query(queryGroupPersonDTO);
|
||||
Map<String, GroupPersonRef> oldPersonResultMap = new HashMap<>(500);
|
||||
oldPersonList.forEach(groupPersonRef -> (GroupPersonRef)oldPersonResultMap.put(groupPersonRef.getPersonId(), groupPersonRef));
|
||||
return oldPersonResultMap;
|
||||
}
|
||||
public void handleGroupPersonChange() throws ServiceException {
|
||||
this.logger.info("开始图库图片同步:[{}]", Long.valueOf(System.currentTimeMillis()));
|
||||
Long lastSynTime = Long.valueOf(0L);
|
||||
String lastImageId = "0";
|
||||
String lastImageStoreId = null;
|
||||
ImgStorePersonQueryDto imgStorePersonQuery = null;
|
||||
GroupPersonRef groupPersonRef = null;
|
||||
AgImageStoreImageResult lastResult = null;
|
||||
while (true) {
|
||||
if (this.redisTemplate.hasKey("cp_image_syn_last_flag").booleanValue()) {
|
||||
String lastFlagValue = (String)this.redisTemplate.opsForValue().get("cp_image_syn_last_flag");
|
||||
lastSynTime = Long.valueOf(lastFlagValue.split(",")[0]);
|
||||
lastImageId = lastFlagValue.split(",")[1];
|
||||
this.logger.info("获取缓存数据,key={},value={}", "cp_image_syn_last_flag", lastFlagValue);
|
||||
}
|
||||
AgImageStoreImageSyncParam imageQuery = new AgImageStoreImageSyncParam();
|
||||
imageQuery.setLastSynTime(lastSynTime);
|
||||
imageQuery.setLastImageId(lastImageId);
|
||||
imageQuery.setImageStoreId(lastImageStoreId);
|
||||
CloudwalkResult<List<AgImageStoreImageResult>> imageQueryResult = this.agImageStoreImageService.sync(imageQuery);
|
||||
if (!imageQueryResult.isSuccess()) {
|
||||
this.logger.error("图库图片同步失败,result:{}", JSONObject.toJSONString(imageQueryResult));
|
||||
throw new ServiceException(imageQueryResult.getCode(), imageQueryResult.getMessage());
|
||||
}
|
||||
List<AgImageStoreImageResult> resultList = (List<AgImageStoreImageResult>)imageQueryResult.getData();
|
||||
if (CollectionUtils.isEmpty(resultList)) {
|
||||
this.logger.warn("没有需要同步的图库图片");
|
||||
break;
|
||||
}
|
||||
for (AgImageStoreImageResult result : resultList) {
|
||||
try {
|
||||
imgStorePersonQuery = new ImgStorePersonQueryDto();
|
||||
imgStorePersonQuery.setImageId(result.getImageId());
|
||||
List<ImgStorePerson> getsResult = this.personMapper.gets(imgStorePersonQuery);
|
||||
if (CollectionUtils.isEmpty(getsResult)) {
|
||||
this.logger.warn("图库图片同步失败,根据imageId:[{}]获取不到人员信息", result.getImageId());
|
||||
continue;
|
||||
}
|
||||
groupPersonRef = new GroupPersonRef();
|
||||
groupPersonRef.setImageStoreId(result.getImageStoreId());
|
||||
List<GroupPersonRef> groupPersonRefList = this.groupPersonRefMapper.selectByCondition(groupPersonRef, Collections3.extractToList(getsResult, "id"));
|
||||
if (CollectionUtils.isEmpty(groupPersonRefList)) {
|
||||
this.logger.warn("图库图片同步失败,根据imageStoreId:[{}],personId:[{}]获取不到图库人员列表信息", result.getImageStoreId(), Collections3.extractToString(getsResult, "id", ","));
|
||||
continue;
|
||||
}
|
||||
groupPersonRef.setGender(result.getGender());
|
||||
groupPersonRef.setAge(result.getAge());
|
||||
groupPersonRef.setGroupTime(result.getGroupTime());
|
||||
boolean needChangeStatus = (DelStatusEnum.DELETED.getCode().shortValue() == result.getIsDel().shortValue() && (GroupModelStatusEnum.MODEL_ING.getCode().shortValue() == result.getStatus().shortValue() || GroupModelStatusEnum.MODEL_COMPLETED.getCode().shortValue() == result.getStatus().shortValue()));
|
||||
if (needChangeStatus) {
|
||||
groupPersonRef.setGroupStatus(GroupModelStatusEnum.MODEL_WAIT.getCode());
|
||||
} else {
|
||||
groupPersonRef.setGroupStatus(result.getStatus());
|
||||
}
|
||||
groupPersonRef.setErrorMessage(result.getErrorMessage());
|
||||
this.groupPersonRefMapper.updateImageDataByIds(groupPersonRef, Collections3.extractToList(groupPersonRefList, "id"));
|
||||
} catch (Exception e) {
|
||||
this.logger.error("handleGroupPersonChange exception,imageStoreId:[{}],imageId:[{}]", new Object[] { result
|
||||
.getImageStoreId(), result.getImageId(), e });
|
||||
}
|
||||
}
|
||||
lastResult = resultList.get(resultList.size() - 1);
|
||||
if (null != lastResult) {
|
||||
if (null == lastResult.getLastUpdateTime()) {
|
||||
lastResult.setLastUpdateTime(lastSynTime);
|
||||
this.logger.warn("最后更新时间为空,imageStoreId:[{}],imageId:[{}]", lastResult.getImageStoreId(), lastResult
|
||||
.getImageId());
|
||||
}
|
||||
this.redisTemplate.opsForValue()
|
||||
.set("cp_image_syn_last_flag", lastResult.getLastUpdateTime() + "," + lastResult.getImageId());
|
||||
this.logger.info("设置缓存数据,key={},value={}", "cp_image_syn_last_flag", lastResult.getLastUpdateTime() + "," + lastResult.getImageId());
|
||||
}
|
||||
}
|
||||
this.logger.info("结束图库图片同步:{}", Long.valueOf(System.currentTimeMillis()));
|
||||
}
|
||||
public void handleGroupPersonChange2() throws ServiceException {
|
||||
this.logger.info("开始图库图片同步:[{}]", Long.valueOf(System.currentTimeMillis()));
|
||||
Long syncTime = Long.valueOf(System.currentTimeMillis() - 600000L);
|
||||
List<GroupPersonRefDTO> syncList = this.groupPersonRefMapper.waitSyncList(syncTime);
|
||||
if (CollectionUtils.isEmpty(syncList)) {
|
||||
this.logger.warn("没有需要同步的图库图片");
|
||||
return;
|
||||
}
|
||||
Map<String, List<GroupPersonRefDTO>> groupSyncList = (Map<String, List<GroupPersonRefDTO>>)syncList.stream().collect(Collectors.groupingBy(GroupPersonRef::getImageStoreId));
|
||||
for (Map.Entry<String, List<GroupPersonRefDTO>> entry : groupSyncList.entrySet()) {
|
||||
String imageStoreId = entry.getKey();
|
||||
updateGroupPerson(imageStoreId, entry.getValue());
|
||||
}
|
||||
this.logger.info("结束图库图片同步:{}", Long.valueOf(System.currentTimeMillis()));
|
||||
}
|
||||
private void updateGroupPerson(String imageStoreId, List<GroupPersonRefDTO> list) {
|
||||
CpSearchFaceParam param = new CpSearchFaceParam();
|
||||
param.setImageStoreId(imageStoreId);
|
||||
param.setImageIds(String.join(",", Collections3.extractToList(list, "imageId")));
|
||||
List<SearchFaceResult> resultList = null;
|
||||
if (list.size() > 1) {
|
||||
CloudwalkResult<BatchSearchFaceResult> batchSearchFaceResult = this.cpImageStoreToolService.batchSearchFace(param);
|
||||
if (null == batchSearchFaceResult || !batchSearchFaceResult.isSuccess()) {
|
||||
return;
|
||||
}
|
||||
resultList = ((BatchSearchFaceResult)batchSearchFaceResult.getData()).getItems();
|
||||
} else {
|
||||
CloudwalkResult<SearchFaceResult> searchFaceResult = this.cpImageStoreToolService.searchFace(param);
|
||||
if (null == searchFaceResult || !searchFaceResult.isSuccess()) {
|
||||
return;
|
||||
}
|
||||
resultList = Arrays.asList(new SearchFaceResult[] { (SearchFaceResult)searchFaceResult.getData() });
|
||||
}
|
||||
if (null == resultList) {
|
||||
return;
|
||||
}
|
||||
ImgStorePersonQueryDto imgStorePersonQuery = null;
|
||||
GroupPersonRef groupPersonRef = null;
|
||||
for (SearchFaceResult result : resultList) {
|
||||
if (StringUtils.isEmpty(result.getUserId())) {
|
||||
this.logger.warn("图库图片同步失败,imageId为空:[{}]", result.getUserId());
|
||||
continue;
|
||||
}
|
||||
imgStorePersonQuery = new ImgStorePersonQueryDto();
|
||||
imgStorePersonQuery.setImageId(result.getUserId());
|
||||
List<ImgStorePerson> getsResult = this.personMapper.gets(imgStorePersonQuery);
|
||||
if (CollectionUtils.isEmpty(getsResult)) {
|
||||
this.logger.warn("图库图片同步失败,根据imageId:[{}]获取不到人员信息", result.getUserId());
|
||||
continue;
|
||||
}
|
||||
groupPersonRef = new GroupPersonRef();
|
||||
groupPersonRef.setImageStoreId(imageStoreId);
|
||||
List<GroupPersonRef> groupPersonRefList = this.groupPersonRefMapper.selectByCondition(groupPersonRef, Collections3.extractToList(getsResult, "id"));
|
||||
if (CollectionUtils.isEmpty(groupPersonRefList)) {
|
||||
this.logger.warn("图库图片同步失败,根据imageStoreId:[{}],personId:[{}]获取不到图库人员列表信息", imageStoreId, Collections3.extractToString(getsResult, "id", ","));
|
||||
continue;
|
||||
}
|
||||
groupPersonRef.setGroupStatus(GroupModelStatusEnum.MODEL_WAIT.getCode());
|
||||
if (result.getResult().intValue() == 0) {
|
||||
groupPersonRef.setGroupStatus(GroupModelStatusEnum.MODEL_COMPLETED.getCode());
|
||||
}
|
||||
groupPersonRef.setGroupTime(result.getTime());
|
||||
groupPersonRef.setErrorMessage(result.getInfo());
|
||||
if (!StringUtils.isEmpty(result.getQualityScore())) {
|
||||
List<String> qualityScoreList = Arrays.asList(result.getQualityScore().split(","));
|
||||
groupPersonRef.setAge(Integer.valueOf((new BigDecimal(qualityScoreList.get(10))).setScale(0, 3).intValue()));
|
||||
groupPersonRef.setGender(Short.valueOf((new BigDecimal(qualityScoreList.get(11))).shortValue()));
|
||||
}
|
||||
this.groupPersonRefMapper.updateImageDataByIds(groupPersonRef, Collections3.extractToList(groupPersonRefList, "id"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/CpImageStorePersonManager.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+746
-734
File diff suppressed because it is too large
Load Diff
+467
-467
@@ -1,6 +1,5 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
// 业务服务
|
||||
|
||||
import cn.cloudwalk.client.aggregate.application.service.ApplicationImageStoreService;
|
||||
import cn.cloudwalk.client.aggregate.common.enums.DelStatusEnum;
|
||||
import cn.cloudwalk.client.aggregate.common.enums.SyncStatusEnum;
|
||||
@@ -17,9 +16,6 @@ import cn.cloudwalk.data.organization.entity.ImgStorePerson;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonMapper;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import cn.cloudwalk.service.organization.common.JsonUtils;
|
||||
import cn.cloudwalk.service.organization.service.CpImageStorePersonManager;
|
||||
import cn.cloudwalk.service.organization.service.CpImageStorePersonTxHandler;
|
||||
import cn.cloudwalk.service.organization.service.CpImageStorePersonValidateManager;
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.google.common.collect.Lists;
|
||||
@@ -31,482 +27,486 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import org.springframework.data.redis.core.RedisCallback;
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.Resource;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.data.redis.connection.RedisConnection;
|
||||
import org.springframework.data.redis.connection.ReturnType;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.core.script.DefaultRedisScript;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springside.modules.utils.Collections3;
|
||||
|
||||
@Service
|
||||
public class CpImageStorePersonSynManager
|
||||
extends AbstractImagStoreService {
|
||||
public static final String TASK_IS_ALL = "isAll";
|
||||
public static final String TASK_JSON_ADD_KEY = "addPersonIds";
|
||||
public static final String TASK_JSON_MOD_KEY = "modPersonIds";
|
||||
public static final String TASK_JSON_DEL_KEY = "delPersonIds";
|
||||
private static final String WAIT_SYN_TASK_KEY = "group_person_wait_syn_task:";
|
||||
private static final String SYN_QUEUE_HEAD_DATA = "group_person_syn_queue_head_data:";
|
||||
@Value(value="${server.instance-id:null}")
|
||||
private String serverInstanceId;
|
||||
@Value(value="${group-person.syn.config.lock-handle-syn-task-second:150}")
|
||||
private String lockHandleSynTaskSecond;
|
||||
@Value(value="${group-person.syn.config.task_is_all.threshold:200}")
|
||||
private int taskIsAllThreshold;
|
||||
@Autowired
|
||||
@Qualifier(value="groupPersonSynExecutor")
|
||||
private ThreadPoolTaskExecutor taskExecutor;
|
||||
@Autowired
|
||||
private StringRedisTemplate redisTemplate;
|
||||
@Autowired
|
||||
private DefaultRedisScript<String> addWaitSynTaskRedisScript;
|
||||
@Autowired
|
||||
private DefaultRedisScript<String> lockHandleSynTaskRedisScript;
|
||||
@Autowired
|
||||
private DefaultRedisScript<String> lockHeadSynTaskRedisScript;
|
||||
@Autowired
|
||||
private DefaultRedisScript<String> handleSuccessSynTaskRedisScript;
|
||||
@Autowired
|
||||
private DefaultRedisScript<String> handleFailSynTaskRedisScript;
|
||||
@Autowired
|
||||
private DefaultRedisScript<String> refreshHandleSynTaskRedisScript;
|
||||
@Resource
|
||||
private CpImageStorePersonManager cpImageStorePersonManager;
|
||||
@Resource
|
||||
private CpImageStorePersonTxHandler cpImageStorePersonTxHandler;
|
||||
@Resource
|
||||
private CpImageStorePersonValidateManager cpImageStorePersonValidateManager;
|
||||
@Resource
|
||||
private ImgStorePersonMapper imgStorePersonMapper;
|
||||
@Autowired
|
||||
private AgImageStoreService agImageStoreService;
|
||||
@Resource
|
||||
private ApplicationImageStoreService appImageStoreService;
|
||||
private CloudwalkCallContext context;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
this.context = this.getCloudwalkContext();
|
||||
}
|
||||
|
||||
public void addGroupPersonSynTask(List<String> imageStoreIdList, String jsonData) {
|
||||
this.logger.info("CpImageStorePersonSynManager addGroupPersonSynTask params : {},{}", imageStoreIdList, (Object)jsonData);
|
||||
for (String imageStoreId : imageStoreIdList) {
|
||||
Long addWaitSynTaskRes = this.addWaitSynTask(imageStoreId, jsonData);
|
||||
if (0 == addWaitSynTaskRes.intValue()) {
|
||||
this.logger.info("CpImageStorePersonSynManager addGroupPersonSynTask addWaitSynTaskRes : 新增图库【{}】任务", (Object)imageStoreId);
|
||||
} else {
|
||||
this.logger.info("CpImageStorePersonSynManager addGroupPersonSynTask addWaitSynTaskRes : 图库【{}】已存在全量任务", (Object)imageStoreId);
|
||||
}
|
||||
this.handleGroupPersonSynTask(imageStoreId);
|
||||
}
|
||||
}
|
||||
|
||||
public void addGroupPersonSynTask(String imageStoreId, String personId, boolean isAdd) {
|
||||
GroupPersonSynData groupPersonSynData = new GroupPersonSynData();
|
||||
if (isAdd) {
|
||||
groupPersonSynData.setAddPersonIds((List)Lists.newArrayList((Object[])new String[]{personId}));
|
||||
} else {
|
||||
groupPersonSynData.setDelPersonIds((List)Lists.newArrayList((Object[])new String[]{personId}));
|
||||
}
|
||||
String jsonData = JsonUtils.toJson(groupPersonSynData);
|
||||
this.addWaitSynTask(imageStoreId, jsonData);
|
||||
}
|
||||
|
||||
public void addGroupPersonSynTask(List<String> imageStoreIds, List<String> personIds, boolean isAdd) {
|
||||
if (Collections3.isNotEmpty(imageStoreIds) && Collections3.isNotEmpty(personIds)) {
|
||||
String jsonData;
|
||||
if (personIds.size() >= this.taskIsAllThreshold) {
|
||||
jsonData = TASK_IS_ALL;
|
||||
} else {
|
||||
GroupPersonSynData groupPersonSynData = new GroupPersonSynData();
|
||||
if (isAdd) {
|
||||
groupPersonSynData.setAddPersonIds(personIds);
|
||||
} else {
|
||||
groupPersonSynData.setDelPersonIds(personIds);
|
||||
}
|
||||
jsonData = JsonUtils.toJson(groupPersonSynData);
|
||||
}
|
||||
this.addGroupPersonSynTask(new ArrayList<String>(imageStoreIds), jsonData);
|
||||
}
|
||||
}
|
||||
|
||||
public List<String> addGroupPersonSynTask(String personId) {
|
||||
Map<String, GroupPersonRef> imageStoreIdsMap;
|
||||
ArrayList imageStoreIds;
|
||||
this.logger.info("addGroupPersonSynTask - 新增图库待同步任务(新增人员注册照) personId:{}", (Object)personId);
|
||||
ArrayList imageIdResultList = Lists.newArrayList();
|
||||
if (StringUtils.isNotBlank((CharSequence)personId) && Collections3.isNotEmpty((Collection)(imageStoreIds = Lists.newArrayList((imageStoreIdsMap = this.cpImageStorePersonManager.getImageStoreIdsByPerson(personId)).keySet())))) {
|
||||
GroupPersonSynData groupPersonSynData = new GroupPersonSynData();
|
||||
groupPersonSynData.setAddPersonIds((List)Lists.newArrayList((Object[])new String[]{personId}));
|
||||
String jsonData = JsonUtils.toJson(groupPersonSynData);
|
||||
for (String imageStoreId : (List<java.lang.String>) imageStoreIds) {
|
||||
this.addWaitSynTask(imageStoreId, jsonData);
|
||||
}
|
||||
imageIdResultList.addAll(imageStoreIds);
|
||||
}
|
||||
return imageIdResultList;
|
||||
}
|
||||
|
||||
public List<String> addGroupPersonSynTask(String personId, String oldImageId, List<String> oldImageStoreIds) {
|
||||
this.logger.info("addGroupPersonSynTask - 新增图库待同步任务(更新人员注册照) personId:{};oldImageId: {};oldImageStoreIds: {}", new Object[]{personId, oldImageId, oldImageStoreIds});
|
||||
ArrayList imageIdResultList = Lists.newArrayList();
|
||||
if (StringUtils.isNotBlank((CharSequence)personId)) {
|
||||
Map<String, GroupPersonRef> imageStoreIdsMap = this.cpImageStorePersonManager.getImageStoreIdsByPerson(personId);
|
||||
ArrayList imageStoreIds = Lists.newArrayList(imageStoreIdsMap.keySet());
|
||||
if (Collections3.isNotEmpty((Collection)imageStoreIds)) {
|
||||
GroupPersonSynData groupPersonSynData = new GroupPersonSynData();
|
||||
groupPersonSynData.setPersonId(personId);
|
||||
groupPersonSynData.setOldImageId(oldImageId);
|
||||
String jsonData = JsonUtils.toJson(groupPersonSynData);
|
||||
for (String imageStoreId : (List<java.lang.String>) imageStoreIds) {
|
||||
this.addWaitSynTask(imageStoreId, jsonData);
|
||||
}
|
||||
imageIdResultList.addAll(imageStoreIds);
|
||||
}
|
||||
HashSet imageStoreIdsBefore = Sets.newHashSet(oldImageStoreIds);
|
||||
HashSet imageStoreIdsAfter = Sets.newHashSet((Iterable)imageStoreIds);
|
||||
imageStoreIdsBefore.removeAll(imageStoreIdsAfter);
|
||||
ArrayList imageStoreIdsNeedDelete = Lists.newArrayList((Iterable)imageStoreIdsBefore);
|
||||
this.logger.info("addGroupPersonSynTask - 新增图库待同步任务(更新人员注册照) imageStoreIdsAfter:{};imageStoreIdsNeedDelete: {}", (Object)imageStoreIds, (Object)imageStoreIdsNeedDelete);
|
||||
if (Collections3.isNotEmpty((Collection)imageStoreIdsNeedDelete)) {
|
||||
GroupPersonSynData groupPersonSynData = new GroupPersonSynData();
|
||||
groupPersonSynData.setDelPersonIds((List)Lists.newArrayList((Object[])new String[]{personId}));
|
||||
String jsonData = JsonUtils.toJson(groupPersonSynData);
|
||||
for (String imageStoreId : (List<java.lang.String>) imageStoreIdsNeedDelete) {
|
||||
this.addWaitSynTask(imageStoreId, jsonData);
|
||||
}
|
||||
imageIdResultList.addAll(imageStoreIdsNeedDelete);
|
||||
}
|
||||
}
|
||||
return imageIdResultList;
|
||||
}
|
||||
|
||||
public List<String> addGroupPersonSynTask(String objId, List<String> personIds, boolean isAdd) {
|
||||
ArrayList imageStoreIdResultList = Lists.newArrayList();
|
||||
if (Collections3.isNotEmpty(personIds)) {
|
||||
String jsonData;
|
||||
GroupPersonSynData groupPersonSynData;
|
||||
Set<String> includeList = this.cpImageStorePersonManager.getImageStoreIdsByObjId(objId, 0);
|
||||
Set<String> excludeList = this.cpImageStorePersonManager.getImageStoreIdsByObjId(objId, 1);
|
||||
includeList.removeAll(excludeList);
|
||||
if (Collections3.isNotEmpty(includeList)) {
|
||||
groupPersonSynData = new GroupPersonSynData();
|
||||
if (isAdd) {
|
||||
groupPersonSynData.setAddPersonIds(personIds);
|
||||
} else {
|
||||
groupPersonSynData.setDelPersonIds(personIds);
|
||||
}
|
||||
jsonData = JsonUtils.toJson(groupPersonSynData);
|
||||
includeList.parallelStream().forEach(imageStoreId -> this.addWaitSynTask((String)imageStoreId, jsonData));
|
||||
imageStoreIdResultList.addAll(includeList);
|
||||
}
|
||||
if (Collections3.isNotEmpty(excludeList)) {
|
||||
groupPersonSynData = new GroupPersonSynData();
|
||||
if (isAdd) {
|
||||
groupPersonSynData.setDelPersonIds(personIds);
|
||||
} else {
|
||||
groupPersonSynData.setAddPersonIds(personIds);
|
||||
}
|
||||
jsonData = JsonUtils.toJson(groupPersonSynData);
|
||||
excludeList.parallelStream().forEach(imageStoreId -> this.addWaitSynTask((String)imageStoreId, jsonData));
|
||||
imageStoreIdResultList.addAll(excludeList);
|
||||
}
|
||||
}
|
||||
return imageStoreIdResultList;
|
||||
}
|
||||
|
||||
public void handleGroupPersonSynTask(String imageStoreId) {
|
||||
Long lockHandleSynTaskRes = this.lockHandleSynTask(imageStoreId);
|
||||
if (0 == lockHandleSynTaskRes.intValue()) {
|
||||
this.taskExecutor.submit(() -> {
|
||||
try {
|
||||
this.logger.info("CpImageStorePersonSynManager handleGroupPersonSynTask lockHandleSynTaskRes : 加锁消费图库{}成功", (Object)imageStoreId);
|
||||
String synQueueHeadDataKey = SYN_QUEUE_HEAD_DATA + imageStoreId;
|
||||
if (this.redisTemplate.hasKey(synQueueHeadDataKey).booleanValue()) {
|
||||
this.logger.warn("CpImageStorePersonSynManager handleGroupPersonSynTask synQueueHeadDataKey : 已存在同步任务队首数据{}", (Object)synQueueHeadDataKey);
|
||||
this.groupPersonSyn(imageStoreId, synQueueHeadDataKey);
|
||||
} else {
|
||||
Long lockHeadSynTaskRes = this.lockHeadSynTask(imageStoreId);
|
||||
if (0 == lockHeadSynTaskRes.intValue()) {
|
||||
this.groupPersonSyn(imageStoreId, synQueueHeadDataKey);
|
||||
} else {
|
||||
this.logger.info("CpImageStorePersonSynManager handleGroupPersonSynTask lockHeadSynTaskRes : 图库{}待同步队列已空", (Object)imageStoreId);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("CpImageStorePersonSynManager handleGroupPersonSynTask taskExecutor : {0}", e);
|
||||
this.handleFailSynTask(imageStoreId);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
this.logger.info("CpImageStorePersonSynManager handleGroupPersonSynTask lockHandleSynTaskRes : 已存在服务节点消费图库{}", (Object)imageStoreId);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* WARNING - Removed try catching itself - possible behaviour change.
|
||||
*/
|
||||
private void groupPersonSyn(String imageStoreId, String synQueueHeadDataKey) {
|
||||
try {
|
||||
String synQueueHeadData = (String)this.redisTemplate.opsForValue().get((Object)synQueueHeadDataKey);
|
||||
this.logger.info("CpImageStorePersonSynManager groupPersonSyn params : {},{}", (Object)imageStoreId, (Object)synQueueHeadData);
|
||||
AgImageStoreResult waitSyncImageStore = this.getImageStoreById(imageStoreId);
|
||||
if (waitSyncImageStore != null) {
|
||||
if (TASK_IS_ALL.equals(synQueueHeadData)) {
|
||||
this.handleImageStoreFullSyn(waitSyncImageStore);
|
||||
} else {
|
||||
this.handleImageStoreIncrementSyn(waitSyncImageStore, synQueueHeadData);
|
||||
}
|
||||
}
|
||||
this.handleSuccessSynTask(imageStoreId);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("CpImageStorePersonSynManager groupPersonSyn Exception :", e);
|
||||
this.handleFailSynTask(imageStoreId);
|
||||
}
|
||||
finally {
|
||||
this.handleGroupPersonSynTask(imageStoreId);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleImageStoreFullSyn(AgImageStoreResult waitSyncImageStore) throws Exception {
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreFullSyn处理待同步图库start");
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreFullSyn params : {}", (Object)waitSyncImageStore.getId());
|
||||
AgImageStoreEditParam updateParam = new AgImageStoreEditParam();
|
||||
updateParam.setId(waitSyncImageStore.getId());
|
||||
updateParam.setName(waitSyncImageStore.getName());
|
||||
updateParam.setStatus(SyncStatusEnum.SYNC_ING.getCode());
|
||||
CloudwalkResult updateResult = this.agImageStoreService.edit(updateParam, this.context);
|
||||
if (!updateResult.isSuccess()) {
|
||||
this.logger.warn("CpImageStorePersonSynManager handleImageStoreFullSyn error,updateResult:[{}]", (Object)JsonUtils.toJson(updateResult));
|
||||
throw new Exception("cwos更新图库信息失败");
|
||||
}
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreFullSyn 整理待处理图库人员数据start");
|
||||
Map<String, GroupPersonRef> associatedPersonResultsAfterUpdate = this.cpImageStorePersonManager.getCurrentAssociatedPersonIds(waitSyncImageStore.getId());
|
||||
HashSet associatedPersonIdsAfterUpdate = Sets.newHashSet(associatedPersonResultsAfterUpdate.keySet());
|
||||
List associatedPersonExpiryDateAfterUpdate = CollectionUtil.isNotEmpty((Collection)associatedPersonIdsAfterUpdate) ? this.imgStorePersonMapper.selectExpiryDateByIds((List)Lists.newArrayList((Iterable)associatedPersonIdsAfterUpdate)) : Lists.newArrayList();
|
||||
Map<String, ImgStorePerson> associatedPersonExpiryDateAfterUpdateMap = (java.util.Map<java.lang.String,cn.cloudwalk.data.organization.entity.ImgStorePerson>) associatedPersonExpiryDateAfterUpdate.stream().collect(Collectors.toMap(ImgStorePerson::getId, o -> o));
|
||||
Map<String, GroupPersonRef> associatedPersonResultsBeforeUpdate = this.cpImageStorePersonManager.getOldAssociatedPersonIds(waitSyncImageStore.getId(), null);
|
||||
HashSet associatedPersonIdsBeforeUpdate = Sets.newHashSet(associatedPersonResultsBeforeUpdate.keySet());
|
||||
HashSet personIdsNeedDelete = new HashSet(associatedPersonIdsBeforeUpdate);
|
||||
personIdsNeedDelete.removeAll(associatedPersonIdsAfterUpdate);
|
||||
ArrayList refNeedAdd = Lists.newArrayList();
|
||||
ArrayList refNeedUpdate = Lists.newArrayList();
|
||||
ArrayList refNeedDelete = Lists.newArrayList();
|
||||
associatedPersonIdsAfterUpdate.forEach(personId -> {
|
||||
ImgStorePerson personExpiryDate;
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreFullSyn 遍历获取图库中有效人员");
|
||||
GroupPersonRef refAfterUpdate = (GroupPersonRef)associatedPersonResultsAfterUpdate.get(personId);
|
||||
if (associatedPersonExpiryDateAfterUpdateMap.containsKey(refAfterUpdate.getPersonId()) && ((personExpiryDate = (ImgStorePerson)associatedPersonExpiryDateAfterUpdateMap.get(refAfterUpdate.getPersonId())).getExpiryBeginDate() != null || personExpiryDate.getExpiryEndDate() != null)) {
|
||||
refAfterUpdate.setExpiryBeginDate(personExpiryDate.getExpiryBeginDate());
|
||||
refAfterUpdate.setExpiryEndDate(personExpiryDate.getExpiryEndDate());
|
||||
refAfterUpdate.setStatus(Short.valueOf(this.checkGroupPersonStatus(personExpiryDate.getExpiryBeginDate(), personExpiryDate.getExpiryEndDate())));
|
||||
}
|
||||
if (associatedPersonResultsBeforeUpdate.containsKey(personId)) {
|
||||
GroupPersonRef refBeforeUpdate = (GroupPersonRef)associatedPersonResultsBeforeUpdate.get(personId);
|
||||
if (!refBeforeUpdate.compare(refAfterUpdate)) {
|
||||
refBeforeUpdate.setOldExpiryBeginDate(refBeforeUpdate.getExpiryBeginDate());
|
||||
refBeforeUpdate.setOldExpiryEndDate(refBeforeUpdate.getExpiryEndDate());
|
||||
refBeforeUpdate.setOldValidDateCron(refBeforeUpdate.getValidDateCron());
|
||||
refBeforeUpdate.setExpiryBeginDate(refAfterUpdate.getExpiryBeginDate());
|
||||
refBeforeUpdate.setExpiryEndDate(refAfterUpdate.getExpiryEndDate());
|
||||
refBeforeUpdate.setValidDateCron(refAfterUpdate.getValidDateCron());
|
||||
refBeforeUpdate.setStatus(refAfterUpdate.getStatus());
|
||||
refNeedUpdate.add(refBeforeUpdate);
|
||||
}
|
||||
} else {
|
||||
refNeedAdd.add(refAfterUpdate);
|
||||
}
|
||||
});
|
||||
personIdsNeedDelete.forEach(personId -> {
|
||||
GroupPersonRef refBeforeUpdate = (GroupPersonRef)associatedPersonResultsBeforeUpdate.get(personId);
|
||||
if (refBeforeUpdate.getStatus() != -1) {
|
||||
refNeedDelete.add(refBeforeUpdate);
|
||||
}
|
||||
});
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreFullSyn 整理待处理图库人员数据end");
|
||||
List<SyncPersonDTO> syncPersonList = this.cpImageStorePersonTxHandler.handleImageStoreChange(waitSyncImageStore, refNeedAdd, refNeedUpdate, refNeedDelete);
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreFullSyn 添加有效期任务,并判断下发");
|
||||
this.cpImageStorePersonValidateManager.addValidateData(syncPersonList);
|
||||
updateParam.setStatus(SyncStatusEnum.SYNC_COMPLETED.getCode());
|
||||
try {
|
||||
updateResult = this.agImageStoreService.edit(updateParam, this.context);
|
||||
if (!updateResult.isSuccess()) {
|
||||
this.logger.warn("CpImageStorePersonSynManager handleImageStoreFullSyn error,updateResult:[{}]", (Object)JSONObject.toJSONString((Object)updateResult));
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("CpImageStorePersonSynManager handleImageStoreFullSyn exception,imageStoreId:[{}]", (Object)waitSyncImageStore.getId(), (Object)e);
|
||||
}
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreFullSyn处理待同步图库end");
|
||||
}
|
||||
|
||||
private void handleImageStoreIncrementSyn(AgImageStoreResult waitSyncImageStore, String jsonData) throws Exception {
|
||||
Map<String, GroupPersonRef> associatedPersonResultsAfterUpdate;
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreIncrementSyn增量处理待同步图库start: {};{}", (Object)waitSyncImageStore.getId(), (Object)jsonData);
|
||||
ArrayList refNeedAdd = Lists.newArrayList();
|
||||
ArrayList refNeedUpdate = Lists.newArrayList();
|
||||
ArrayList refNeedDelete = Lists.newArrayList();
|
||||
GroupPersonSynData synData = JsonUtils.toObj(jsonData, GroupPersonSynData.class);
|
||||
if (synData == null) {
|
||||
this.logger.error("CpImageStorePersonSynManager handleImageStoreIncrementSyn 同步数据为null");
|
||||
return;
|
||||
}
|
||||
if (Collections3.isNotEmpty((Collection)synData.getAddPersonIds())) {
|
||||
associatedPersonResultsAfterUpdate = this.cpImageStorePersonManager.getGroupPersonRefByPersons(waitSyncImageStore.getId(), synData.getAddPersonIds());
|
||||
List associatedPersonExpiryDateAfterUpdate = this.imgStorePersonMapper.selectExpiryDateByIds(synData.getAddPersonIds());
|
||||
Map<String, ImgStorePerson> associatedPersonExpiryDateAfterUpdateMap = (java.util.Map<java.lang.String,cn.cloudwalk.data.organization.entity.ImgStorePerson>) associatedPersonExpiryDateAfterUpdate.stream().collect(Collectors.toMap(ImgStorePerson::getId, o -> o));
|
||||
Map<String, GroupPersonRef> associatedPersonResultsBeforeUpdate = this.cpImageStorePersonManager.getOldAssociatedPersonIds(waitSyncImageStore.getId(), synData.getAddPersonIds());
|
||||
synData.getAddPersonIds().forEach(personId -> {
|
||||
if (associatedPersonResultsAfterUpdate.containsKey(personId)) {
|
||||
ImgStorePerson personExpiryDate;
|
||||
GroupPersonRef refAfterUpdate = (GroupPersonRef)associatedPersonResultsAfterUpdate.get(personId);
|
||||
if (associatedPersonExpiryDateAfterUpdateMap.containsKey(refAfterUpdate.getPersonId()) && ((personExpiryDate = (ImgStorePerson)associatedPersonExpiryDateAfterUpdateMap.get(refAfterUpdate.getPersonId())).getExpiryBeginDate() != null || personExpiryDate.getExpiryEndDate() != null)) {
|
||||
refAfterUpdate.setExpiryBeginDate(personExpiryDate.getExpiryBeginDate());
|
||||
refAfterUpdate.setExpiryEndDate(personExpiryDate.getExpiryEndDate());
|
||||
refAfterUpdate.setStatus(Short.valueOf(this.checkGroupPersonStatus(personExpiryDate.getExpiryBeginDate(), personExpiryDate.getExpiryEndDate())));
|
||||
}
|
||||
if (associatedPersonResultsBeforeUpdate.containsKey(personId)) {
|
||||
GroupPersonRef refBeforeUpdate = (GroupPersonRef)associatedPersonResultsBeforeUpdate.get(personId);
|
||||
if (!refBeforeUpdate.compare(refAfterUpdate)) {
|
||||
refBeforeUpdate.setOldExpiryBeginDate(refBeforeUpdate.getExpiryBeginDate());
|
||||
refBeforeUpdate.setOldExpiryEndDate(refBeforeUpdate.getExpiryEndDate());
|
||||
refBeforeUpdate.setOldValidDateCron(refBeforeUpdate.getValidDateCron());
|
||||
refBeforeUpdate.setExpiryBeginDate(refAfterUpdate.getExpiryBeginDate());
|
||||
refBeforeUpdate.setExpiryEndDate(refAfterUpdate.getExpiryEndDate());
|
||||
refBeforeUpdate.setValidDateCron(refAfterUpdate.getValidDateCron());
|
||||
refBeforeUpdate.setStatus(refAfterUpdate.getStatus());
|
||||
refNeedUpdate.add(refBeforeUpdate);
|
||||
}
|
||||
} else {
|
||||
refNeedAdd.add(refAfterUpdate);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if (Collections3.isNotEmpty((Collection)synData.getDelPersonIds())) {
|
||||
associatedPersonResultsAfterUpdate = this.cpImageStorePersonManager.getGroupPersonRefByPersons(waitSyncImageStore.getId(), synData.getDelPersonIds());
|
||||
Map<String, GroupPersonRef> associatedPersonResultsBeforeUpdate = this.cpImageStorePersonManager.getOldAssociatedPersonIds(waitSyncImageStore.getId(), synData.getDelPersonIds());
|
||||
synData.getDelPersonIds().forEach(personId -> {
|
||||
if (!associatedPersonResultsAfterUpdate.containsKey(personId) && associatedPersonResultsBeforeUpdate.containsKey(personId)) {
|
||||
GroupPersonRef refBeforeUpdate = (GroupPersonRef)associatedPersonResultsBeforeUpdate.get(personId);
|
||||
refNeedDelete.add(refBeforeUpdate);
|
||||
} else if (associatedPersonResultsBeforeUpdate.containsKey(personId)) {
|
||||
ImgStorePerson person = this.imgStorePersonMapper.selectByPrimaryKey(personId);
|
||||
if (DelStatusEnum.DELETED.getCode().shortValue() == person.getIsDel().shortValue()) {
|
||||
GroupPersonRef refBeforeUpdate = (GroupPersonRef)associatedPersonResultsBeforeUpdate.get(personId);
|
||||
refNeedDelete.add(refBeforeUpdate);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreIncrementSyn 整理待处理图库人员数据end");
|
||||
ArrayList syncPersonList = Lists.newArrayList();
|
||||
if (StringUtils.isNotBlank((CharSequence)synData.getPersonId())) {
|
||||
ImgStorePerson personExpiryDate;
|
||||
List associatedPersonExpiryDateAfterUpdate;
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreIncrementSyn 单人员更新注册照:{},{}", (Object)synData.getPersonId(), (Object)synData.getOldImageId());
|
||||
Map<String, GroupPersonRef> associatedPersonResultsAfterUpdate2 = this.cpImageStorePersonManager.getGroupPersonRefByPersons(waitSyncImageStore.getId(), Lists.newArrayList(synData.getPersonId()));
|
||||
Map<String, GroupPersonRef> associatedPersonResultsBeforeUpdate = this.cpImageStorePersonManager.getOldAssociatedPersonIds(waitSyncImageStore.getId(), Lists.newArrayList(synData.getPersonId()));
|
||||
GroupPersonRef refAfterUpdate = associatedPersonResultsAfterUpdate2.get(synData.getPersonId());
|
||||
if (refAfterUpdate != null && CollectionUtil.isNotEmpty((Collection)(associatedPersonExpiryDateAfterUpdate = this.imgStorePersonMapper.selectExpiryDateByIds((List)Lists.newArrayList(synData.getPersonId())))) && ((personExpiryDate = (ImgStorePerson)associatedPersonExpiryDateAfterUpdate.get(0)).getExpiryBeginDate() != null || personExpiryDate.getExpiryEndDate() != null)) {
|
||||
refAfterUpdate.setExpiryBeginDate(personExpiryDate.getExpiryBeginDate());
|
||||
refAfterUpdate.setExpiryEndDate(personExpiryDate.getExpiryEndDate());
|
||||
refAfterUpdate.setStatus(Short.valueOf(this.checkGroupPersonStatus(personExpiryDate.getExpiryBeginDate(), personExpiryDate.getExpiryEndDate())));
|
||||
}
|
||||
GroupPersonRef refBeforeUpdate = associatedPersonResultsBeforeUpdate.get(synData.getPersonId());
|
||||
if (refAfterUpdate != null && refBeforeUpdate != null) {
|
||||
refBeforeUpdate.setExpiryBeginDate(refAfterUpdate.getExpiryBeginDate());
|
||||
refBeforeUpdate.setExpiryEndDate(refAfterUpdate.getExpiryEndDate());
|
||||
refBeforeUpdate.setOldExpiryBeginDate(refBeforeUpdate.getExpiryBeginDate());
|
||||
refBeforeUpdate.setOldExpiryEndDate(refBeforeUpdate.getExpiryEndDate());
|
||||
refBeforeUpdate.setStatus(refAfterUpdate.getStatus());
|
||||
syncPersonList.add(this.cpImageStorePersonTxHandler.handleImageStorePersonUpdate(refBeforeUpdate, synData.getOldImageId()));
|
||||
} else if (refAfterUpdate == null && refBeforeUpdate != null) {
|
||||
refNeedDelete.add(refBeforeUpdate);
|
||||
} else if (refAfterUpdate != null) {
|
||||
refNeedAdd.add(refAfterUpdate);
|
||||
} else {
|
||||
this.logger.warn("CpImageStorePersonSynManager handleImageStoreIncrementSyn 更新前后数据丢失");
|
||||
}
|
||||
}
|
||||
syncPersonList.addAll(this.cpImageStorePersonTxHandler.handleImageStoreChange(waitSyncImageStore, refNeedAdd, refNeedUpdate, refNeedDelete));
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreIncrementSyn 添加有效期任务,并判断下发");
|
||||
this.cpImageStorePersonValidateManager.addValidateData(syncPersonList);
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreIncrementSyn 增量处理待同步图库end");
|
||||
}
|
||||
|
||||
private AgImageStoreResult getImageStoreById(String imageStoreId) throws Exception {
|
||||
AgImageStoreQueryParam imageStoreQueryParamChange = new AgImageStoreQueryParam();
|
||||
imageStoreQueryParamChange.setId(imageStoreId);
|
||||
imageStoreQueryParamChange.setType(Short.valueOf((short)1));
|
||||
CloudwalkResult waitSyncImageStoreChangeResult = this.agImageStoreService.query(imageStoreQueryParamChange);
|
||||
if (!waitSyncImageStoreChangeResult.isSuccess()) {
|
||||
this.logger.warn("CpImageStorePersonSynManager handleImageStoreFullSyn query is_del change list fail,result:{}", (Object)JSONObject.toJSONString((Object)waitSyncImageStoreChangeResult));
|
||||
throw new Exception("cwos查询图库信息失败");
|
||||
}
|
||||
if (Collections3.isEmpty((Collection)((Collection)waitSyncImageStoreChangeResult.getData()))) {
|
||||
return null;
|
||||
}
|
||||
return (AgImageStoreResult)((List)waitSyncImageStoreChangeResult.getData()).get(0);
|
||||
}
|
||||
|
||||
public Long addWaitSynTask(String imageStoreId, String jsonData) {
|
||||
this.logger.info("addWaitSynTask - 图库待同步任务队列队尾新增任务 imageStoreId:{}; jsonData: {}", (Object)imageStoreId, (Object)jsonData);
|
||||
return (Long)this.redisTemplate.execute((RedisCallback) connection -> (Long)connection.eval(this.addWaitSynTaskRedisScript.getScriptAsString().getBytes(), ReturnType.INTEGER, 0, (byte[][])new byte[][]{imageStoreId.getBytes(), jsonData.getBytes()}));
|
||||
}
|
||||
|
||||
public Long lockHandleSynTask(String imageStoreId) {
|
||||
return (Long)this.redisTemplate.execute((RedisCallback) connection -> (Long)connection.eval(this.lockHandleSynTaskRedisScript.getScriptAsString().getBytes(), ReturnType.INTEGER, 0, (byte[][])new byte[][]{imageStoreId.getBytes(), this.serverInstanceId.getBytes(), this.lockHandleSynTaskSecond.getBytes()}));
|
||||
}
|
||||
|
||||
public Long lockHeadSynTask(String imageStoreId) {
|
||||
return (Long)this.redisTemplate.execute((RedisCallback) connection -> (Long)connection.eval(this.lockHeadSynTaskRedisScript.getScriptAsString().getBytes(), ReturnType.INTEGER, 1, (byte[][])new byte[][]{imageStoreId.getBytes(), imageStoreId.getBytes(), this.serverInstanceId.getBytes(), String.valueOf(this.taskIsAllThreshold).getBytes()}));
|
||||
}
|
||||
|
||||
public Long handleSuccessSynTask(String imageStoreId) {
|
||||
return (Long)this.redisTemplate.execute((RedisCallback) connection -> (Long)connection.eval(this.handleSuccessSynTaskRedisScript.getScriptAsString().getBytes(), ReturnType.INTEGER, 0, (byte[][])new byte[][]{imageStoreId.getBytes(), this.serverInstanceId.getBytes()}));
|
||||
}
|
||||
|
||||
public Long handleFailSynTask(String imageStoreId) {
|
||||
return (Long)this.redisTemplate.execute((RedisCallback) connection -> (Long)connection.eval(this.handleFailSynTaskRedisScript.getScriptAsString().getBytes(), ReturnType.INTEGER, 0, (byte[][])new byte[][]{imageStoreId.getBytes(), this.serverInstanceId.getBytes()}));
|
||||
}
|
||||
|
||||
public void refreshHandleSynTaskLockExpireTime() {
|
||||
byte[] res = (byte[])this.redisTemplate.execute((RedisCallback) connection -> (byte[])connection.eval(this.refreshHandleSynTaskRedisScript.getScriptAsString().getBytes(), ReturnType.VALUE, 0, (byte[][])new byte[][]{this.serverInstanceId.getBytes(), this.lockHandleSynTaskSecond.getBytes()}));
|
||||
this.logger.info("CpImageStorePersonSynManager refreshHandleSynTaskLockExpireTime : {}", (Object)new String(res));
|
||||
}
|
||||
|
||||
public void checkHandleSynTaskException() {
|
||||
Set<String> synQueueHeadDataKeys = this.redisTemplate.keys("group_person_syn_queue_head_data:*");
|
||||
synQueueHeadDataKeys.forEach(synQueueHeadDataKey -> {
|
||||
String imageStoreId = synQueueHeadDataKey.replaceFirst(SYN_QUEUE_HEAD_DATA, "");
|
||||
Set<String> lockKeys = this.redisTemplate.keys(imageStoreId + ":*");
|
||||
if (Collections3.isEmpty((Collection)lockKeys)) {
|
||||
this.logger.info("CpImageStorePersonSynManager checkHandleSynTaskException 消费加锁");
|
||||
this.handleFailSynTask(imageStoreId);
|
||||
this.handleGroupPersonSynTask(imageStoreId);
|
||||
}
|
||||
});
|
||||
Set<String> waitSynTaskKeys = this.redisTemplate.keys("group_person_wait_syn_task:*");
|
||||
waitSynTaskKeys.forEach(waitSynTaskKey -> {
|
||||
String imageStoreId = waitSynTaskKey.replaceFirst(WAIT_SYN_TASK_KEY, "");
|
||||
Set<String> lockKeys = this.redisTemplate.keys(imageStoreId + ":*");
|
||||
if (Collections3.isEmpty((Collection)lockKeys)) {
|
||||
this.logger.info("CpImageStorePersonSynManager checkHandleSynTaskException 未消费");
|
||||
this.handleFailSynTask(imageStoreId);
|
||||
this.handleGroupPersonSynTask(imageStoreId);
|
||||
}
|
||||
});
|
||||
}
|
||||
extends AbstractImagStoreService
|
||||
{
|
||||
public static final String TASK_IS_ALL = "isAll";
|
||||
public static final String TASK_JSON_ADD_KEY = "addPersonIds";
|
||||
public static final String TASK_JSON_MOD_KEY = "modPersonIds";
|
||||
public static final String TASK_JSON_DEL_KEY = "delPersonIds";
|
||||
private static final String WAIT_SYN_TASK_KEY = "group_person_wait_syn_task:";
|
||||
private static final String SYN_QUEUE_HEAD_DATA = "group_person_syn_queue_head_data:";
|
||||
@Value("${server.instance-id:null}")
|
||||
private String serverInstanceId;
|
||||
@Value("${group-person.syn.config.lock-handle-syn-task-second:150}")
|
||||
private String lockHandleSynTaskSecond;
|
||||
@Value("${group-person.syn.config.task_is_all.threshold:200}")
|
||||
private int taskIsAllThreshold;
|
||||
@Autowired
|
||||
@Qualifier("groupPersonSynExecutor")
|
||||
private ThreadPoolTaskExecutor taskExecutor;
|
||||
@Autowired
|
||||
private StringRedisTemplate redisTemplate;
|
||||
@Autowired
|
||||
private DefaultRedisScript<String> addWaitSynTaskRedisScript;
|
||||
@Autowired
|
||||
private DefaultRedisScript<String> lockHandleSynTaskRedisScript;
|
||||
@Autowired
|
||||
private DefaultRedisScript<String> lockHeadSynTaskRedisScript;
|
||||
@Autowired
|
||||
private DefaultRedisScript<String> handleSuccessSynTaskRedisScript;
|
||||
@Autowired
|
||||
private DefaultRedisScript<String> handleFailSynTaskRedisScript;
|
||||
@Autowired
|
||||
private DefaultRedisScript<String> refreshHandleSynTaskRedisScript;
|
||||
@Resource
|
||||
private CpImageStorePersonManager cpImageStorePersonManager;
|
||||
@Resource
|
||||
private CpImageStorePersonTxHandler cpImageStorePersonTxHandler;
|
||||
@Resource
|
||||
private CpImageStorePersonValidateManager cpImageStorePersonValidateManager;
|
||||
@Resource
|
||||
private ImgStorePersonMapper imgStorePersonMapper;
|
||||
@Autowired
|
||||
private AgImageStoreService agImageStoreService;
|
||||
@Resource
|
||||
private ApplicationImageStoreService appImageStoreService;
|
||||
private CloudwalkCallContext context;
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
this.context = getCloudwalkContext();
|
||||
}
|
||||
public void addGroupPersonSynTask(List<String> imageStoreIdList, String jsonData) {
|
||||
this.logger.info("CpImageStorePersonSynManager addGroupPersonSynTask params : {},{}", imageStoreIdList, jsonData);
|
||||
for (String imageStoreId : imageStoreIdList) {
|
||||
Long addWaitSynTaskRes = addWaitSynTask(imageStoreId, jsonData);
|
||||
if (0 == addWaitSynTaskRes.intValue()) {
|
||||
this.logger.info("CpImageStorePersonSynManager addGroupPersonSynTask addWaitSynTaskRes : 新增图库【{}】任务", imageStoreId);
|
||||
} else {
|
||||
this.logger.info("CpImageStorePersonSynManager addGroupPersonSynTask addWaitSynTaskRes : 图库【{}】已存在全量任务", imageStoreId);
|
||||
}
|
||||
handleGroupPersonSynTask(imageStoreId);
|
||||
}
|
||||
}
|
||||
public void addGroupPersonSynTask(String imageStoreId, String personId, boolean isAdd) {
|
||||
GroupPersonSynData groupPersonSynData = new GroupPersonSynData();
|
||||
if (isAdd) {
|
||||
groupPersonSynData.setAddPersonIds(Lists.newArrayList((Object[])new String[] { personId }));
|
||||
} else {
|
||||
groupPersonSynData.setDelPersonIds(Lists.newArrayList((Object[])new String[] { personId }));
|
||||
}
|
||||
String jsonData = JsonUtils.toJson(groupPersonSynData);
|
||||
addWaitSynTask(imageStoreId, jsonData);
|
||||
}
|
||||
public void addGroupPersonSynTask(List<String> imageStoreIds, List<String> personIds, boolean isAdd) {
|
||||
if (Collections3.isNotEmpty(imageStoreIds) && Collections3.isNotEmpty(personIds)) {
|
||||
String jsonData;
|
||||
if (personIds.size() >= this.taskIsAllThreshold) {
|
||||
jsonData = "isAll";
|
||||
} else {
|
||||
GroupPersonSynData groupPersonSynData = new GroupPersonSynData();
|
||||
if (isAdd) {
|
||||
groupPersonSynData.setAddPersonIds(personIds);
|
||||
} else {
|
||||
groupPersonSynData.setDelPersonIds(personIds);
|
||||
}
|
||||
jsonData = JsonUtils.toJson(groupPersonSynData);
|
||||
}
|
||||
addGroupPersonSynTask(new ArrayList<>(imageStoreIds), jsonData);
|
||||
}
|
||||
}
|
||||
public List<String> addGroupPersonSynTask(String personId) {
|
||||
this.logger.info("addGroupPersonSynTask - 新增图库待同步任务(新增人员注册照) personId:{}", personId);
|
||||
List<String> imageIdResultList = Lists.newArrayList();
|
||||
if (StringUtils.isNotBlank(personId)) {
|
||||
Map<String, GroupPersonRef> imageStoreIdsMap = this.cpImageStorePersonManager.getImageStoreIdsByPerson(personId);
|
||||
List<String> imageStoreIds = Lists.newArrayList(imageStoreIdsMap.keySet());
|
||||
if (Collections3.isNotEmpty(imageStoreIds)) {
|
||||
GroupPersonSynData groupPersonSynData = new GroupPersonSynData();
|
||||
groupPersonSynData.setAddPersonIds(Lists.newArrayList((Object[])new String[] { personId }));
|
||||
String jsonData = JsonUtils.toJson(groupPersonSynData);
|
||||
for (String imageStoreId : imageStoreIds) {
|
||||
addWaitSynTask(imageStoreId, jsonData);
|
||||
}
|
||||
imageIdResultList.addAll(imageStoreIds);
|
||||
}
|
||||
}
|
||||
return imageIdResultList;
|
||||
}
|
||||
public List<String> addGroupPersonSynTask(String personId, String oldImageId, List<String> oldImageStoreIds) {
|
||||
this.logger.info("addGroupPersonSynTask - 新增图库待同步任务(更新人员注册照) personId:{};oldImageId: {};oldImageStoreIds: {}", new Object[] { personId, oldImageId, oldImageStoreIds });
|
||||
List<String> imageIdResultList = Lists.newArrayList();
|
||||
if (StringUtils.isNotBlank(personId)) {
|
||||
Map<String, GroupPersonRef> imageStoreIdsMap = this.cpImageStorePersonManager.getImageStoreIdsByPerson(personId);
|
||||
List<String> imageStoreIds = Lists.newArrayList(imageStoreIdsMap.keySet());
|
||||
if (Collections3.isNotEmpty(imageStoreIds)) {
|
||||
GroupPersonSynData groupPersonSynData = new GroupPersonSynData();
|
||||
groupPersonSynData.setPersonId(personId);
|
||||
groupPersonSynData.setOldImageId(oldImageId);
|
||||
String jsonData = JsonUtils.toJson(groupPersonSynData);
|
||||
for (String imageStoreId : imageStoreIds) {
|
||||
addWaitSynTask(imageStoreId, jsonData);
|
||||
}
|
||||
imageIdResultList.addAll(imageStoreIds);
|
||||
}
|
||||
Set<String> imageStoreIdsBefore = Sets.newHashSet(oldImageStoreIds);
|
||||
Set<String> imageStoreIdsAfter = Sets.newHashSet(imageStoreIds);
|
||||
imageStoreIdsBefore.removeAll(imageStoreIdsAfter);
|
||||
List<String> imageStoreIdsNeedDelete = Lists.newArrayList(imageStoreIdsBefore);
|
||||
this.logger.info("addGroupPersonSynTask - 新增图库待同步任务(更新人员注册照) imageStoreIdsAfter:{};imageStoreIdsNeedDelete: {}", imageStoreIds, imageStoreIdsNeedDelete);
|
||||
if (Collections3.isNotEmpty(imageStoreIdsNeedDelete)) {
|
||||
GroupPersonSynData groupPersonSynData = new GroupPersonSynData();
|
||||
groupPersonSynData.setDelPersonIds(Lists.newArrayList((Object[])new String[] { personId }));
|
||||
String jsonData = JsonUtils.toJson(groupPersonSynData);
|
||||
for (String imageStoreId : imageStoreIdsNeedDelete) {
|
||||
addWaitSynTask(imageStoreId, jsonData);
|
||||
}
|
||||
imageIdResultList.addAll(imageStoreIdsNeedDelete);
|
||||
}
|
||||
}
|
||||
return imageIdResultList;
|
||||
}
|
||||
public List<String> addGroupPersonSynTask(String objId, List<String> personIds, boolean isAdd) {
|
||||
List<String> imageStoreIdResultList = Lists.newArrayList();
|
||||
if (Collections3.isNotEmpty(personIds)) {
|
||||
Set<String> includeList = this.cpImageStorePersonManager.getImageStoreIdsByObjId(objId,
|
||||
Integer.valueOf(0));
|
||||
Set<String> excludeList = this.cpImageStorePersonManager.getImageStoreIdsByObjId(objId,
|
||||
Integer.valueOf(1));
|
||||
includeList.removeAll(excludeList);
|
||||
if (Collections3.isNotEmpty(includeList)) {
|
||||
GroupPersonSynData groupPersonSynData = new GroupPersonSynData();
|
||||
if (isAdd) {
|
||||
groupPersonSynData.setAddPersonIds(personIds);
|
||||
} else {
|
||||
groupPersonSynData.setDelPersonIds(personIds);
|
||||
}
|
||||
String jsonData = JsonUtils.toJson(groupPersonSynData);
|
||||
includeList.parallelStream().forEach(imageStoreId -> addWaitSynTask(imageStoreId, jsonData));
|
||||
imageStoreIdResultList.addAll(includeList);
|
||||
}
|
||||
if (Collections3.isNotEmpty(excludeList)) {
|
||||
GroupPersonSynData groupPersonSynData = new GroupPersonSynData();
|
||||
if (isAdd) {
|
||||
groupPersonSynData.setDelPersonIds(personIds);
|
||||
} else {
|
||||
groupPersonSynData.setAddPersonIds(personIds);
|
||||
}
|
||||
String jsonData = JsonUtils.toJson(groupPersonSynData);
|
||||
excludeList.parallelStream().forEach(imageStoreId -> addWaitSynTask(imageStoreId, jsonData));
|
||||
imageStoreIdResultList.addAll(excludeList);
|
||||
}
|
||||
}
|
||||
return imageStoreIdResultList;
|
||||
}
|
||||
public void handleGroupPersonSynTask(String imageStoreId) {
|
||||
Long lockHandleSynTaskRes = lockHandleSynTask(imageStoreId);
|
||||
if (0 == lockHandleSynTaskRes.intValue()) {
|
||||
this.taskExecutor.submit(() -> {
|
||||
try {
|
||||
this.logger.info("CpImageStorePersonSynManager handleGroupPersonSynTask lockHandleSynTaskRes : 加锁消费图库{}成功", imageStoreId);
|
||||
String synQueueHeadDataKey = "group_person_syn_queue_head_data:" + imageStoreId;
|
||||
if (this.redisTemplate.hasKey(synQueueHeadDataKey).booleanValue()) {
|
||||
this.logger.warn("CpImageStorePersonSynManager handleGroupPersonSynTask synQueueHeadDataKey : 已存在同步任务队首数据{}", synQueueHeadDataKey);
|
||||
groupPersonSyn(imageStoreId, synQueueHeadDataKey);
|
||||
} else {
|
||||
Long lockHeadSynTaskRes = lockHeadSynTask(imageStoreId);
|
||||
if (0 == lockHeadSynTaskRes.intValue()) {
|
||||
groupPersonSyn(imageStoreId, synQueueHeadDataKey);
|
||||
} else {
|
||||
this.logger.info("CpImageStorePersonSynManager handleGroupPersonSynTask lockHeadSynTaskRes : 图库{}待同步队列已空", imageStoreId);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
this.logger.error("CpImageStorePersonSynManager handleGroupPersonSynTask taskExecutor : {0}", e);
|
||||
handleFailSynTask(imageStoreId);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
this.logger.info("CpImageStorePersonSynManager handleGroupPersonSynTask lockHandleSynTaskRes : 已存在服务节点消费图库{}", imageStoreId);
|
||||
}
|
||||
}
|
||||
private void groupPersonSyn(String imageStoreId, String synQueueHeadDataKey) {
|
||||
try {
|
||||
String synQueueHeadData = (String)this.redisTemplate.opsForValue().get(synQueueHeadDataKey);
|
||||
this.logger.info("CpImageStorePersonSynManager groupPersonSyn params : {},{}", imageStoreId, synQueueHeadData);
|
||||
AgImageStoreResult waitSyncImageStore = getImageStoreById(imageStoreId);
|
||||
if (waitSyncImageStore != null) {
|
||||
if ("isAll".equals(synQueueHeadData)) {
|
||||
handleImageStoreFullSyn(waitSyncImageStore);
|
||||
} else {
|
||||
handleImageStoreIncrementSyn(waitSyncImageStore, synQueueHeadData);
|
||||
}
|
||||
}
|
||||
handleSuccessSynTask(imageStoreId);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("CpImageStorePersonSynManager groupPersonSyn Exception :", e);
|
||||
handleFailSynTask(imageStoreId);
|
||||
} finally {
|
||||
handleGroupPersonSynTask(imageStoreId);
|
||||
}
|
||||
}
|
||||
private void handleImageStoreFullSyn(AgImageStoreResult waitSyncImageStore) throws Exception {
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreFullSyn处理待同步图库start");
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreFullSyn params : {}", waitSyncImageStore.getId());
|
||||
AgImageStoreEditParam updateParam = new AgImageStoreEditParam();
|
||||
updateParam.setId(waitSyncImageStore.getId());
|
||||
updateParam.setName(waitSyncImageStore.getName());
|
||||
updateParam.setStatus(SyncStatusEnum.SYNC_ING.getCode());
|
||||
try {
|
||||
List<ImgStorePerson> associatedPersonExpiryDateAfterUpdate;
|
||||
CloudwalkResult<Boolean> updateResult = this.agImageStoreService.edit(updateParam, this.context);
|
||||
if (!updateResult.isSuccess()) {
|
||||
this.logger.warn("CpImageStorePersonSynManager handleImageStoreFullSyn error,updateResult:[{}]", JsonUtils.toJson(updateResult));
|
||||
throw new Exception("cwos更新图库信息失败");
|
||||
}
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreFullSyn 整理待处理图库人员数据start");
|
||||
Map<String, GroupPersonRef> associatedPersonResultsAfterUpdate = this.cpImageStorePersonManager.getCurrentAssociatedPersonIds(waitSyncImageStore
|
||||
.getId());
|
||||
Set<String> associatedPersonIdsAfterUpdate = Sets.newHashSet(associatedPersonResultsAfterUpdate.keySet());
|
||||
if (CollectionUtil.isNotEmpty(associatedPersonIdsAfterUpdate)) {
|
||||
associatedPersonExpiryDateAfterUpdate = this.imgStorePersonMapper.selectExpiryDateByIds(Lists.newArrayList(associatedPersonIdsAfterUpdate));
|
||||
} else {
|
||||
associatedPersonExpiryDateAfterUpdate = Lists.newArrayList();
|
||||
}
|
||||
Map<String, ImgStorePerson> associatedPersonExpiryDateAfterUpdateMap = (Map<String, ImgStorePerson>)associatedPersonExpiryDateAfterUpdate.stream().collect(Collectors.toMap(ImgStorePerson::getId, o -> o));
|
||||
Map<String, GroupPersonRef> associatedPersonResultsBeforeUpdate = this.cpImageStorePersonManager.getOldAssociatedPersonIds(waitSyncImageStore.getId(), null);
|
||||
Set<String> associatedPersonIdsBeforeUpdate = Sets.newHashSet(associatedPersonResultsBeforeUpdate.keySet());
|
||||
Set<String> personIdsNeedDelete = new HashSet<>(associatedPersonIdsBeforeUpdate);
|
||||
personIdsNeedDelete.removeAll(associatedPersonIdsAfterUpdate);
|
||||
List<GroupPersonRef> refNeedAdd = Lists.newArrayList();
|
||||
List<GroupPersonRef> refNeedUpdate = Lists.newArrayList();
|
||||
List<GroupPersonRef> refNeedDelete = Lists.newArrayList();
|
||||
associatedPersonIdsAfterUpdate.forEach(personId -> {
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreFullSyn 遍历获取图库中有效人员");
|
||||
GroupPersonRef refAfterUpdate = (GroupPersonRef)associatedPersonResultsAfterUpdate.get(personId);
|
||||
if (associatedPersonExpiryDateAfterUpdateMap.containsKey(refAfterUpdate.getPersonId())) {
|
||||
ImgStorePerson personExpiryDate = (ImgStorePerson)associatedPersonExpiryDateAfterUpdateMap.get(refAfterUpdate.getPersonId());
|
||||
if (personExpiryDate.getExpiryBeginDate() != null || personExpiryDate.getExpiryEndDate() != null) {
|
||||
refAfterUpdate.setExpiryBeginDate(personExpiryDate.getExpiryBeginDate());
|
||||
refAfterUpdate.setExpiryEndDate(personExpiryDate.getExpiryEndDate());
|
||||
refAfterUpdate.setStatus(Short.valueOf(checkGroupPersonStatus(personExpiryDate.getExpiryBeginDate(), personExpiryDate.getExpiryEndDate())));
|
||||
}
|
||||
}
|
||||
if (associatedPersonResultsBeforeUpdate.containsKey(personId)) {
|
||||
GroupPersonRef refBeforeUpdate = (GroupPersonRef)associatedPersonResultsBeforeUpdate.get(personId);
|
||||
if (!refBeforeUpdate.compare(refAfterUpdate)) {
|
||||
refBeforeUpdate.setOldExpiryBeginDate(refBeforeUpdate.getExpiryBeginDate());
|
||||
refBeforeUpdate.setOldExpiryEndDate(refBeforeUpdate.getExpiryEndDate());
|
||||
refBeforeUpdate.setOldValidDateCron(refBeforeUpdate.getValidDateCron());
|
||||
refBeforeUpdate.setExpiryBeginDate(refAfterUpdate.getExpiryBeginDate());
|
||||
refBeforeUpdate.setExpiryEndDate(refAfterUpdate.getExpiryEndDate());
|
||||
refBeforeUpdate.setValidDateCron(refAfterUpdate.getValidDateCron());
|
||||
refBeforeUpdate.setStatus(refAfterUpdate.getStatus());
|
||||
refNeedUpdate.add(refBeforeUpdate);
|
||||
}
|
||||
} else {
|
||||
refNeedAdd.add(refAfterUpdate);
|
||||
}
|
||||
});
|
||||
personIdsNeedDelete.forEach(personId -> {
|
||||
GroupPersonRef refBeforeUpdate = (GroupPersonRef)associatedPersonResultsBeforeUpdate.get(personId);
|
||||
if (refBeforeUpdate.getStatus().shortValue() != -1) {
|
||||
refNeedDelete.add(refBeforeUpdate);
|
||||
}
|
||||
});
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreFullSyn 整理待处理图库人员数据end");
|
||||
List<SyncPersonDTO> syncPersonList = this.cpImageStorePersonTxHandler.handleImageStoreChange(waitSyncImageStore, refNeedAdd, refNeedUpdate, refNeedDelete);
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreFullSyn 添加有效期任务,并判断下发");
|
||||
this.cpImageStorePersonValidateManager.addValidateData(syncPersonList);
|
||||
updateParam.setStatus(SyncStatusEnum.SYNC_COMPLETED.getCode());
|
||||
} catch (Exception e) {
|
||||
throw e;
|
||||
}
|
||||
try {
|
||||
CloudwalkResult<Boolean> updateResult = this.agImageStoreService.edit(updateParam, this.context);
|
||||
if (!updateResult.isSuccess()) {
|
||||
this.logger.warn("CpImageStorePersonSynManager handleImageStoreFullSyn error,updateResult:[{}]", JSONObject.toJSONString(updateResult));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
this.logger.error("CpImageStorePersonSynManager handleImageStoreFullSyn exception,imageStoreId:[{}]", waitSyncImageStore.getId(), e);
|
||||
}
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreFullSyn处理待同步图库end");
|
||||
}
|
||||
private void handleImageStoreIncrementSyn(AgImageStoreResult waitSyncImageStore, String jsonData) throws Exception {
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreIncrementSyn增量处理待同步图库start: {};{}", waitSyncImageStore.getId(), jsonData);
|
||||
List<GroupPersonRef> refNeedAdd = Lists.newArrayList();
|
||||
List<GroupPersonRef> refNeedUpdate = Lists.newArrayList();
|
||||
List<GroupPersonRef> refNeedDelete = Lists.newArrayList();
|
||||
GroupPersonSynData synData = (GroupPersonSynData)JsonUtils.toObj(jsonData, GroupPersonSynData.class);
|
||||
if (synData == null) {
|
||||
this.logger.error("CpImageStorePersonSynManager handleImageStoreIncrementSyn 同步数据为null");
|
||||
return;
|
||||
}
|
||||
if (Collections3.isNotEmpty(synData.getAddPersonIds())) {
|
||||
Map<String, GroupPersonRef> associatedPersonResultsAfterUpdate = this.cpImageStorePersonManager.getGroupPersonRefByPersons(waitSyncImageStore.getId(), synData.getAddPersonIds());
|
||||
List<ImgStorePerson> associatedPersonExpiryDateAfterUpdate = this.imgStorePersonMapper.selectExpiryDateByIds(synData.getAddPersonIds());
|
||||
Map<String, ImgStorePerson> associatedPersonExpiryDateAfterUpdateMap = (Map<String, ImgStorePerson>)associatedPersonExpiryDateAfterUpdate.stream().collect(Collectors.toMap(ImgStorePerson::getId, o -> o));
|
||||
Map<String, GroupPersonRef> associatedPersonResultsBeforeUpdate = this.cpImageStorePersonManager.getOldAssociatedPersonIds(waitSyncImageStore.getId(), synData.getAddPersonIds());
|
||||
synData.getAddPersonIds().forEach(personId -> {
|
||||
if (associatedPersonResultsAfterUpdate.containsKey(personId)) {
|
||||
GroupPersonRef refAfterUpdate = (GroupPersonRef)associatedPersonResultsAfterUpdate.get(personId);
|
||||
if (associatedPersonExpiryDateAfterUpdateMap.containsKey(refAfterUpdate.getPersonId())) {
|
||||
ImgStorePerson personExpiryDate = (ImgStorePerson)associatedPersonExpiryDateAfterUpdateMap.get(refAfterUpdate.getPersonId());
|
||||
if (personExpiryDate.getExpiryBeginDate() != null || personExpiryDate.getExpiryEndDate() != null) {
|
||||
refAfterUpdate.setExpiryBeginDate(personExpiryDate.getExpiryBeginDate());
|
||||
refAfterUpdate.setExpiryEndDate(personExpiryDate.getExpiryEndDate());
|
||||
refAfterUpdate.setStatus(Short.valueOf(checkGroupPersonStatus(personExpiryDate.getExpiryBeginDate(), personExpiryDate.getExpiryEndDate())));
|
||||
}
|
||||
}
|
||||
if (associatedPersonResultsBeforeUpdate.containsKey(personId)) {
|
||||
GroupPersonRef refBeforeUpdate = (GroupPersonRef)associatedPersonResultsBeforeUpdate.get(personId);
|
||||
if (!refBeforeUpdate.compare(refAfterUpdate)) {
|
||||
refBeforeUpdate.setOldExpiryBeginDate(refBeforeUpdate.getExpiryBeginDate());
|
||||
refBeforeUpdate.setOldExpiryEndDate(refBeforeUpdate.getExpiryEndDate());
|
||||
refBeforeUpdate.setOldValidDateCron(refBeforeUpdate.getValidDateCron());
|
||||
refBeforeUpdate.setExpiryBeginDate(refAfterUpdate.getExpiryBeginDate());
|
||||
refBeforeUpdate.setExpiryEndDate(refAfterUpdate.getExpiryEndDate());
|
||||
refBeforeUpdate.setValidDateCron(refAfterUpdate.getValidDateCron());
|
||||
refBeforeUpdate.setStatus(refAfterUpdate.getStatus());
|
||||
refNeedUpdate.add(refBeforeUpdate);
|
||||
}
|
||||
} else {
|
||||
refNeedAdd.add(refAfterUpdate);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if (Collections3.isNotEmpty(synData.getDelPersonIds())) {
|
||||
Map<String, GroupPersonRef> associatedPersonResultsAfterUpdate = this.cpImageStorePersonManager.getGroupPersonRefByPersons(waitSyncImageStore.getId(), synData.getDelPersonIds());
|
||||
Map<String, GroupPersonRef> associatedPersonResultsBeforeUpdate = this.cpImageStorePersonManager.getOldAssociatedPersonIds(waitSyncImageStore.getId(), synData.getDelPersonIds());
|
||||
synData.getDelPersonIds().forEach(personId -> {
|
||||
if (!associatedPersonResultsAfterUpdate.containsKey(personId) && associatedPersonResultsBeforeUpdate.containsKey(personId)) {
|
||||
GroupPersonRef refBeforeUpdate = (GroupPersonRef)associatedPersonResultsBeforeUpdate.get(personId);
|
||||
refNeedDelete.add(refBeforeUpdate);
|
||||
} else if (associatedPersonResultsBeforeUpdate.containsKey(personId)) {
|
||||
ImgStorePerson person = this.imgStorePersonMapper.selectByPrimaryKey(personId);
|
||||
if (DelStatusEnum.DELETED.getCode().shortValue() == person.getIsDel().shortValue()) {
|
||||
GroupPersonRef refBeforeUpdate = (GroupPersonRef)associatedPersonResultsBeforeUpdate.get(personId);
|
||||
refNeedDelete.add(refBeforeUpdate);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreIncrementSyn 整理待处理图库人员数据end");
|
||||
List<SyncPersonDTO> syncPersonList = Lists.newArrayList();
|
||||
if (StringUtils.isNotBlank(synData.getPersonId())) {
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreIncrementSyn 单人员更新注册照:{},{}", synData
|
||||
.getPersonId(), synData.getOldImageId());
|
||||
Map<String, GroupPersonRef> associatedPersonResultsAfterUpdate = this.cpImageStorePersonManager.getGroupPersonRefByPersons(waitSyncImageStore.getId(), Lists.newArrayList((Object[])new String[] { synData.getPersonId() }));
|
||||
Map<String, GroupPersonRef> associatedPersonResultsBeforeUpdate = this.cpImageStorePersonManager.getOldAssociatedPersonIds(waitSyncImageStore.getId(), Lists.newArrayList((Object[])new String[] { synData.getPersonId() }));
|
||||
GroupPersonRef refAfterUpdate = associatedPersonResultsAfterUpdate.get(synData.getPersonId());
|
||||
if (refAfterUpdate != null) {
|
||||
List<ImgStorePerson> associatedPersonExpiryDateAfterUpdate = this.imgStorePersonMapper.selectExpiryDateByIds(Lists.newArrayList((Object[])new String[] { synData.getPersonId() }));
|
||||
if (CollectionUtil.isNotEmpty(associatedPersonExpiryDateAfterUpdate)) {
|
||||
ImgStorePerson personExpiryDate = associatedPersonExpiryDateAfterUpdate.get(0);
|
||||
if (personExpiryDate.getExpiryBeginDate() != null || personExpiryDate.getExpiryEndDate() != null) {
|
||||
refAfterUpdate.setExpiryBeginDate(personExpiryDate.getExpiryBeginDate());
|
||||
refAfterUpdate.setExpiryEndDate(personExpiryDate.getExpiryEndDate());
|
||||
refAfterUpdate.setStatus(Short.valueOf(checkGroupPersonStatus(personExpiryDate.getExpiryBeginDate(), personExpiryDate
|
||||
.getExpiryEndDate())));
|
||||
}
|
||||
}
|
||||
}
|
||||
GroupPersonRef refBeforeUpdate = associatedPersonResultsBeforeUpdate.get(synData.getPersonId());
|
||||
if (refAfterUpdate != null && refBeforeUpdate != null) {
|
||||
refBeforeUpdate.setExpiryBeginDate(refAfterUpdate.getExpiryBeginDate());
|
||||
refBeforeUpdate.setExpiryEndDate(refAfterUpdate.getExpiryEndDate());
|
||||
refBeforeUpdate.setOldExpiryBeginDate(refBeforeUpdate.getExpiryBeginDate());
|
||||
refBeforeUpdate.setOldExpiryEndDate(refBeforeUpdate.getExpiryEndDate());
|
||||
refBeforeUpdate.setStatus(refAfterUpdate.getStatus());
|
||||
syncPersonList.add(this.cpImageStorePersonTxHandler
|
||||
.handleImageStorePersonUpdate(refBeforeUpdate, synData.getOldImageId()));
|
||||
} else if (refAfterUpdate == null && refBeforeUpdate != null) {
|
||||
refNeedDelete.add(refBeforeUpdate);
|
||||
} else if (refAfterUpdate != null) {
|
||||
refNeedAdd.add(refAfterUpdate);
|
||||
} else {
|
||||
this.logger.warn("CpImageStorePersonSynManager handleImageStoreIncrementSyn 更新前后数据丢失");
|
||||
}
|
||||
}
|
||||
syncPersonList.addAll(this.cpImageStorePersonTxHandler
|
||||
.handleImageStoreChange(waitSyncImageStore, refNeedAdd, refNeedUpdate, refNeedDelete));
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreIncrementSyn 添加有效期任务,并判断下发");
|
||||
this.cpImageStorePersonValidateManager.addValidateData(syncPersonList);
|
||||
this.logger.info("CpImageStorePersonSynManager handleImageStoreIncrementSyn 增量处理待同步图库end");
|
||||
}
|
||||
private AgImageStoreResult getImageStoreById(String imageStoreId) throws Exception {
|
||||
AgImageStoreQueryParam imageStoreQueryParamChange = new AgImageStoreQueryParam();
|
||||
imageStoreQueryParamChange.setId(imageStoreId);
|
||||
imageStoreQueryParamChange.setType(Short.valueOf((short)1));
|
||||
CloudwalkResult<List<AgImageStoreResult>> waitSyncImageStoreChangeResult = this.agImageStoreService.query(imageStoreQueryParamChange);
|
||||
if (!waitSyncImageStoreChangeResult.isSuccess()) {
|
||||
this.logger.warn("CpImageStorePersonSynManager handleImageStoreFullSyn query is_del change list fail,result:{}",
|
||||
JSONObject.toJSONString(waitSyncImageStoreChangeResult));
|
||||
throw new Exception("cwos查询图库信息失败");
|
||||
}
|
||||
if (Collections3.isEmpty((Collection)waitSyncImageStoreChangeResult.getData())) {
|
||||
return null;
|
||||
}
|
||||
return ((List<AgImageStoreResult>)waitSyncImageStoreChangeResult.getData()).get(0);
|
||||
}
|
||||
public Long addWaitSynTask(String imageStoreId, String jsonData) {
|
||||
this.logger.info("addWaitSynTask - 图库待同步任务队列队尾新增任务 imageStoreId:{}; jsonData: {}", imageStoreId, jsonData);
|
||||
return (Long)this.redisTemplate.execute(connection -> (Long)connection.eval(this.addWaitSynTaskRedisScript.getScriptAsString().getBytes(), ReturnType.INTEGER, 0, new byte[][] { imageStoreId.getBytes(), jsonData.getBytes() }));
|
||||
}
|
||||
public Long lockHandleSynTask(String imageStoreId) {
|
||||
return (Long)this.redisTemplate.execute(connection -> (Long)connection.eval(this.lockHandleSynTaskRedisScript.getScriptAsString().getBytes(), ReturnType.INTEGER, 0, new byte[][] { imageStoreId.getBytes(), this.serverInstanceId.getBytes(), this.lockHandleSynTaskSecond.getBytes() }));
|
||||
}
|
||||
public Long lockHeadSynTask(String imageStoreId) {
|
||||
return (Long)this.redisTemplate.execute(connection -> (Long)connection.eval(this.lockHeadSynTaskRedisScript.getScriptAsString().getBytes(), ReturnType.INTEGER, 1, new byte[][] { imageStoreId.getBytes(), imageStoreId.getBytes(), this.serverInstanceId.getBytes(), String.valueOf(this.taskIsAllThreshold).getBytes() }));
|
||||
}
|
||||
public Long handleSuccessSynTask(String imageStoreId) {
|
||||
return (Long)this.redisTemplate.execute(connection -> (Long)connection.eval(this.handleSuccessSynTaskRedisScript.getScriptAsString().getBytes(), ReturnType.INTEGER, 0, new byte[][] { imageStoreId.getBytes(), this.serverInstanceId.getBytes() }));
|
||||
}
|
||||
public Long handleFailSynTask(String imageStoreId) {
|
||||
return (Long)this.redisTemplate.execute(connection -> (Long)connection.eval(this.handleFailSynTaskRedisScript.getScriptAsString().getBytes(), ReturnType.INTEGER, 0, new byte[][] { imageStoreId.getBytes(), this.serverInstanceId.getBytes() }));
|
||||
}
|
||||
public void refreshHandleSynTaskLockExpireTime() {
|
||||
byte[] res = (byte[])this.redisTemplate.execute(connection -> (byte[])connection.eval(this.refreshHandleSynTaskRedisScript.getScriptAsString().getBytes(), ReturnType.VALUE, 0, new byte[][] { this.serverInstanceId.getBytes(), this.lockHandleSynTaskSecond.getBytes() }));
|
||||
this.logger.info("CpImageStorePersonSynManager refreshHandleSynTaskLockExpireTime : {}", new String(res));
|
||||
}
|
||||
public void checkHandleSynTaskException() {
|
||||
Set<String> synQueueHeadDataKeys = this.redisTemplate.keys("group_person_syn_queue_head_data:*");
|
||||
synQueueHeadDataKeys.forEach(synQueueHeadDataKey -> {
|
||||
String imageStoreId = synQueueHeadDataKey.replaceFirst("group_person_syn_queue_head_data:", "");
|
||||
Set<String> lockKeys = this.redisTemplate.keys(imageStoreId + ":*");
|
||||
if (Collections3.isEmpty(lockKeys)) {
|
||||
this.logger.info("CpImageStorePersonSynManager checkHandleSynTaskException 消费加锁");
|
||||
handleFailSynTask(imageStoreId);
|
||||
handleGroupPersonSynTask(imageStoreId);
|
||||
}
|
||||
});
|
||||
Set<String> waitSynTaskKeys = this.redisTemplate.keys("group_person_wait_syn_task:*");
|
||||
waitSynTaskKeys.forEach(waitSynTaskKey -> {
|
||||
String imageStoreId = waitSynTaskKey.replaceFirst("group_person_wait_syn_task:", "");
|
||||
Set<String> lockKeys = this.redisTemplate.keys(imageStoreId + ":*");
|
||||
if (Collections3.isEmpty(lockKeys)) {
|
||||
this.logger.info("CpImageStorePersonSynManager checkHandleSynTaskException 未消费");
|
||||
handleFailSynTask(imageStoreId);
|
||||
handleGroupPersonSynTask(imageStoreId);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/CpImageStorePersonSynManager.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+390
-385
@@ -1,6 +1,5 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
// 业务服务
|
||||
|
||||
import cn.cloudwalk.client.aggregate.common.enums.DelStatusEnum;
|
||||
import cn.cloudwalk.client.aggregate.common.enums.GroupModelStatusEnum;
|
||||
import cn.cloudwalk.client.aggregate.group.param.AgFeatureExtractParam;
|
||||
@@ -31,7 +30,6 @@ import com.google.common.collect.Sets;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
@@ -46,390 +44,397 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springside.modules.utils.Collections3;
|
||||
|
||||
@Component
|
||||
public class CpImageStorePersonTxHandler
|
||||
extends AbstractImagStoreService {
|
||||
@Value(value="${cloudwalk.imagestore.person.sync.batchsize:100}")
|
||||
private int batchSize;
|
||||
@Value(value="${cloudwalk.imagestore.person.sync.del.batchsize:100}")
|
||||
private int delBatchSize;
|
||||
@Resource
|
||||
private CpImageStoreToolService cpImageStoreToolService;
|
||||
@Resource
|
||||
private GroupPersonRefMapper groupPersonRefMapper;
|
||||
@Resource
|
||||
private DevicePersonSyncLogMapper devicePersonSyncLogMapper;
|
||||
@Resource
|
||||
private ImgStorePersonMapper imgStorePersonMapper;
|
||||
private CloudwalkCallContext context;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
this.context = this.getCloudwalkContext();
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor={Exception.class}, propagation=Propagation.REQUIRED)
|
||||
public List<SyncPersonDTO> handleImageStoreChange(AgImageStoreResult waitSyncImageStore, List<GroupPersonRef> personIdsNeedAdd, List<GroupPersonRef> personIdsNeedUpdate, List<GroupPersonRef> personIdsNeedDelete) {
|
||||
ArrayList<SyncPersonDTO> resultList = new ArrayList<SyncPersonDTO>();
|
||||
this.logger.info("CpImageStorePersonUpdateTask,处理新增人员start");
|
||||
resultList.addAll(this.handleImageStorePersonChange(personIdsNeedAdd, true));
|
||||
this.logger.info("CpImageStorePersonUpdateTask,处理新增人员end");
|
||||
this.logger.info("CpImageStorePersonUpdateTask,处理更新人员start");
|
||||
resultList.addAll(this.handleImageStorePersonChange(personIdsNeedUpdate, false));
|
||||
this.logger.info("CpImageStorePersonUpdateTask,处理更新人员end");
|
||||
this.logger.info("CpImageStorePersonUpdateTask,处理删除人员start");
|
||||
for (GroupPersonRef delGroupPersonRef : personIdsNeedDelete) {
|
||||
resultList.add(this.generateDelSyncPersonDTO(delGroupPersonRef, -1, delGroupPersonRef.getExpiryBeginDate(), delGroupPersonRef.getExpiryEndDate()));
|
||||
}
|
||||
this.handleImageStorePersonDelete(waitSyncImageStore.getId(), personIdsNeedDelete.stream().map(GroupPersonRef::getPersonId).collect(Collectors.toList()));
|
||||
this.logger.info("CpImageStorePersonUpdateTask,处理删除人员end");
|
||||
return resultList;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor={Exception.class}, propagation=Propagation.REQUIRED)
|
||||
public void handlePersonDelete(ImgStorePerson imgStorePerson, Set<String> imageStoreIdsNeedDelete) {
|
||||
this.deletePersonFromImageStores(imgStorePerson, imageStoreIdsNeedDelete);
|
||||
}
|
||||
|
||||
private List<SyncPersonDTO> handleImageStorePersonChange(List<GroupPersonRef> changePersonIds, boolean add) {
|
||||
ArrayList<SyncPersonDTO> syncPersonList = new ArrayList<SyncPersonDTO>();
|
||||
if (Collections3.isEmpty(changePersonIds)) {
|
||||
return syncPersonList;
|
||||
}
|
||||
if (add) {
|
||||
ArrayList<GroupPersonRef> groupPersonRefList = new ArrayList<GroupPersonRef>(this.batchSize);
|
||||
int total = 0;
|
||||
for (GroupPersonRef changePersonId : changePersonIds) {
|
||||
GroupPersonRef addGroupPersonRef = this.generateGroupPersonRefAdd(changePersonId);
|
||||
SyncPersonDTO addSyncPersonDTO = this.generateSyncPersonDTO(addGroupPersonRef, 0, null, null);
|
||||
if (StringUtils.isEmpty((Object)addSyncPersonDTO.getImageId())) {
|
||||
syncPersonList.add(addSyncPersonDTO);
|
||||
addGroupPersonRef.resetGroupStatus(Short.valueOf((short)0));
|
||||
} else {
|
||||
syncPersonList.add(addSyncPersonDTO);
|
||||
addGroupPersonRef.resetGroupStatus(GroupModelStatusEnum.MODEL_WAIT.getCode());
|
||||
}
|
||||
groupPersonRefList.add(addGroupPersonRef);
|
||||
if (++total < this.batchSize) continue;
|
||||
this.groupPersonRefMapper.batchInsert(groupPersonRefList);
|
||||
groupPersonRefList = new ArrayList(this.batchSize);
|
||||
total = 0;
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(groupPersonRefList)) {
|
||||
this.groupPersonRefMapper.batchInsert(groupPersonRefList);
|
||||
}
|
||||
} else {
|
||||
for (GroupPersonRef changePersonId : changePersonIds) {
|
||||
Short oldIsDel = changePersonId.getIsDel();
|
||||
GroupPersonRef modGroupPersonRef = this.generateGroupPersonRefMod(changePersonId);
|
||||
int personAction = DelStatusEnum.DELETED.getCode().shortValue() == oldIsDel.shortValue() && DelStatusEnum.NORAML.getCode().shortValue() == modGroupPersonRef.getIsDel().shortValue() ? 0 : (DelStatusEnum.NORAML.getCode().shortValue() == oldIsDel.shortValue() && DelStatusEnum.DELETED.getCode().shortValue() == modGroupPersonRef.getIsDel().shortValue() ? -1 : 1);
|
||||
SyncPersonDTO modSyncPersonDTO = this.generateSyncPersonDTO(modGroupPersonRef, personAction, modGroupPersonRef.getOldExpiryBeginDate(), modGroupPersonRef.getOldExpiryEndDate());
|
||||
boolean flag = personAction == 1 && DelStatusEnum.NORAML.getCode().shortValue() == modGroupPersonRef.getIsDel().shortValue() && DelStatusEnum.NORAML.getCode().shortValue() == oldIsDel.shortValue();
|
||||
this.logger.debug("CpImageStorePersonUpdateTask handleImageStorePersonChange mod flag: {}", (Object)flag);
|
||||
if (StringUtils.isEmpty((Object)modSyncPersonDTO.getImageId())) {
|
||||
modGroupPersonRef.resetGroupStatus(Short.valueOf((short)0));
|
||||
} else if (!flag) {
|
||||
modGroupPersonRef.resetGroupStatus(GroupModelStatusEnum.MODEL_WAIT.getCode());
|
||||
}
|
||||
modGroupPersonRef.setExpiryBeginDateStatus(Integer.valueOf(0));
|
||||
modGroupPersonRef.setExpiryEndDateStatus(Integer.valueOf(0));
|
||||
syncPersonList.add(modSyncPersonDTO);
|
||||
if (!flag) {
|
||||
this.groupPersonRefMapper.updateByPrimaryKey(modGroupPersonRef);
|
||||
} else {
|
||||
this.groupPersonRefMapper.updateByPrimaryKeySelective(modGroupPersonRef);
|
||||
}
|
||||
DevicePersonSyncLogDTO dto = new DevicePersonSyncLogDTO();
|
||||
dto.setGroupPersonRefId(modGroupPersonRef.getId());
|
||||
dto.setStatus(Integer.valueOf(SyncStatusEnum.NOT_PULL.getValue()));
|
||||
dto.setCode("");
|
||||
dto.setErrorMessage("");
|
||||
dto.setLastUpdateTime(modGroupPersonRef.getLastUpdateTime());
|
||||
dto.setUpdateInfo("更新图库人员信息,更新同步记录状态:设备未拉取");
|
||||
int res = this.devicePersonSyncLogMapper.updateStatusByGroupPersonRef(dto);
|
||||
this.logger.debug("更新图库人员信息[{}],更新[{}]条同步记录状态为未拉取", (Object)modGroupPersonRef.getId(), (Object)res);
|
||||
}
|
||||
}
|
||||
return syncPersonList;
|
||||
}
|
||||
|
||||
public SyncPersonDTO handleImageStorePersonUpdate(GroupPersonRef groupPersonRef, String oldImageId) {
|
||||
SyncPersonDTO result;
|
||||
GroupPersonRef modGroupPersonRef = this.generateGroupPersonRefMod(groupPersonRef);
|
||||
if (StringUtils.isEmpty((Object)oldImageId)) {
|
||||
result = this.generateSyncPersonDTO(modGroupPersonRef, 0, modGroupPersonRef.getOldExpiryBeginDate(), modGroupPersonRef.getOldExpiryEndDate());
|
||||
if (!StringUtils.isEmpty((Object)result.getImageId())) {
|
||||
modGroupPersonRef.resetGroupStatus(GroupModelStatusEnum.MODEL_WAIT.getCode());
|
||||
}
|
||||
} else {
|
||||
result = this.generateSyncPersonDTO(modGroupPersonRef, 1, modGroupPersonRef.getOldExpiryBeginDate(), modGroupPersonRef.getOldExpiryEndDate());
|
||||
result.setOldImageId(oldImageId);
|
||||
if (!StringUtils.isEmpty((Object)result.getImageId()) && !oldImageId.equals(result.getImageId())) {
|
||||
modGroupPersonRef.resetGroupStatus(GroupModelStatusEnum.MODEL_WAIT.getCode());
|
||||
}
|
||||
}
|
||||
if (StringUtils.isEmpty((Object)result.getImageId())) {
|
||||
modGroupPersonRef.resetGroupStatus(Short.valueOf((short)0));
|
||||
}
|
||||
this.groupPersonRefMapper.updateByPrimaryKey(modGroupPersonRef);
|
||||
DevicePersonSyncLogDTO syncLogDTO = new DevicePersonSyncLogDTO();
|
||||
syncLogDTO.setGroupPersonRefIds(Arrays.asList(modGroupPersonRef.getId()));
|
||||
syncLogDTO.setLastUpdateTime(modGroupPersonRef.getLastUpdateTime());
|
||||
this.devicePersonSyncLogMapper.updateLastTimeByGroupPersonRef(syncLogDTO);
|
||||
return result;
|
||||
}
|
||||
|
||||
private void handleImageStorePersonDelete(String imageStoreId, List<String> changePersonIds) {
|
||||
if (Collections3.isEmpty(changePersonIds)) {
|
||||
return;
|
||||
}
|
||||
DelGroupPersonDTO deleteParam = new DelGroupPersonDTO();
|
||||
deleteParam.setImageStoreId(imageStoreId);
|
||||
deleteParam.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
deleteParam.setLastUpdateUserId(this.context.getUser().getCaller());
|
||||
deleteParam.setExpiryBeginDateStatus(Integer.valueOf(0));
|
||||
deleteParam.setExpiryEndDateStatus(Integer.valueOf(0));
|
||||
DevicePersonSyncLogDTO devicePersonSyncLogDTO = new DevicePersonSyncLogDTO();
|
||||
devicePersonSyncLogDTO.setImageStoreId(imageStoreId);
|
||||
devicePersonSyncLogDTO.setStatus(Integer.valueOf(SyncStatusEnum.NOT_PULL.getValue()));
|
||||
devicePersonSyncLogDTO.setCode("");
|
||||
devicePersonSyncLogDTO.setErrorMessage("");
|
||||
devicePersonSyncLogDTO.setLastUpdateTime(deleteParam.getLastUpdateTime());
|
||||
devicePersonSyncLogDTO.setUpdateInfo("删除人员,更新同步记录状态:设备未拉取");
|
||||
devicePersonSyncLogDTO.setIsDel(Integer.valueOf(DelStatusEnum.DELETED.getCode().shortValue()));
|
||||
List<List> partition = Lists.partition(changePersonIds, (int)this.delBatchSize);
|
||||
for (List list : partition) {
|
||||
deleteParam.setPersonIds((Collection)list);
|
||||
devicePersonSyncLogDTO.setPersonIds(list);
|
||||
this.groupPersonRefMapper.logicDeleteExpireNullByParam(deleteParam);
|
||||
int res = this.devicePersonSyncLogMapper.updateStatusByCondition(devicePersonSyncLogDTO);
|
||||
this.logger.debug("删除人员,更新[{}]条同步记录,图库Id:[{}],人员Id列表[{}]", new Object[]{res, imageStoreId, JSON.toJSONString((Object)list)});
|
||||
}
|
||||
}
|
||||
|
||||
private void deletePersonFromImageStores(ImgStorePerson imgStorePerson, Set<String> imageStoreIdsNeedDelete) {
|
||||
if (!CollectionUtils.isEmpty(imageStoreIdsNeedDelete)) {
|
||||
DelGroupPersonDTO deleteParam = new DelGroupPersonDTO();
|
||||
deleteParam.setPersonId(imgStorePerson.getId());
|
||||
deleteParam.setImageStoreIds(imageStoreIdsNeedDelete);
|
||||
deleteParam.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
deleteParam.setLastUpdateUserId(this.context.getUser().getCaller());
|
||||
this.groupPersonRefMapper.logicDeleteExpireNullByParam(deleteParam);
|
||||
}
|
||||
for (String deleteImageStoreId : imageStoreIdsNeedDelete) {
|
||||
this.handleImageStoreImageChange(deleteImageStoreId, Sets.newHashSet((Object[])new String[]{imgStorePerson.getImageId()}), false);
|
||||
}
|
||||
}
|
||||
|
||||
@Async(value="handleImageTaskExecutor")
|
||||
public void handleImageStoreImageChange(String imageStoreId, Set<String> changeImageIds, boolean add) {
|
||||
if (Collections3.isEmpty(changeImageIds)) {
|
||||
return;
|
||||
}
|
||||
ArrayList<String> changeImageList = new ArrayList<String>(changeImageIds);
|
||||
if (add) {
|
||||
CpHandleFaceParam handleFaceParam = new CpHandleFaceParam();
|
||||
handleFaceParam.setImageStoreId(imageStoreId);
|
||||
changeImageList.stream().forEach(imageId -> {
|
||||
try {
|
||||
handleFaceParam.setImageId(imageId);
|
||||
CloudwalkResult addFaceResult = this.cpImageStoreToolService.addFace(handleFaceParam);
|
||||
this.updateGroupPersonRef(imageStoreId, (String)imageId, add, (CloudwalkResult<HandleFaceResult>)addFaceResult);
|
||||
}
|
||||
catch (ServiceException e) {
|
||||
this.logger.warn("handleImageStoreImageChange exception,errorCode:[{}], errorMessage:[{}]", (Object)e.getCode(), (Object)e.getMessage());
|
||||
}
|
||||
});
|
||||
} else {
|
||||
CpHandleFaceParam cpHandleFaceParam = new CpHandleFaceParam();
|
||||
cpHandleFaceParam.setImageStoreId(imageStoreId);
|
||||
changeImageList.stream().forEach(imageId -> {
|
||||
try {
|
||||
cpHandleFaceParam.setImageId(imageId);
|
||||
CloudwalkResult removeFaceResult = this.cpImageStoreToolService.removeFace(cpHandleFaceParam);
|
||||
this.updateGroupPersonRef(imageStoreId, (String)imageId, add, (CloudwalkResult<HandleFaceResult>)removeFaceResult);
|
||||
}
|
||||
catch (ServiceException e) {
|
||||
this.logger.warn("handleImageStoreImageChange exception,errorCode:[{}], errorMessage:[{}]", (Object)e.getCode(), (Object)e.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private int updateGroupPersonRef(String imageStoreId, String imageId, boolean add, CloudwalkResult<HandleFaceResult> handleFaceResult) throws ServiceException {
|
||||
ImgStorePersonQueryDto queryDto = new ImgStorePersonQueryDto();
|
||||
queryDto.setImageIds(Arrays.asList(imageId));
|
||||
List personList = this.imgStorePersonMapper.getByImageId(queryDto);
|
||||
if (CollectionUtils.isEmpty((Collection)personList)) {
|
||||
this.logger.warn("根据imageId[{}]获取不到人员信息", (Object)imageId);
|
||||
throw new ServiceException("人员信息详情查询失败,原因:{}", this.getMessage("人员信息详情查询失败,原因:{}"));
|
||||
}
|
||||
GroupPersonRef groupPersonRef = new GroupPersonRef();
|
||||
groupPersonRef.setImageStoreId(imageStoreId);
|
||||
List groupPersonRefList = this.groupPersonRefMapper.selectByCondition(groupPersonRef, personList.stream().map(i -> i.getId()).collect(Collectors.toList()));
|
||||
if (CollectionUtils.isEmpty((Collection)groupPersonRefList)) {
|
||||
this.logger.warn("图库图片同步失败,根据imageStoreId:[{}],personId:[{}]获取不到图库人员列表信息", (Object)imageStoreId, (Object)((HandleFaceResult)handleFaceResult.getData()).getPersonId());
|
||||
throw new ServiceException("53014702", this.getMessage("53014702"));
|
||||
}
|
||||
groupPersonRef.setGroupStatus(add ? GroupModelStatusEnum.MODEL_FAILED.getCode() : GroupModelStatusEnum.MODEL_DEL_FAILED.getCode());
|
||||
groupPersonRef.setErrorMessage(handleFaceResult.getMessage());
|
||||
if (handleFaceResult.isSuccess() && ((HandleFaceResult)handleFaceResult.getData()).getResult() == 0) {
|
||||
groupPersonRef.setGroupStatus(add ? GroupModelStatusEnum.MODEL_COMPLETED.getCode() : GroupModelStatusEnum.MODEL_WAIT.getCode());
|
||||
groupPersonRef.setGroupTime(add ? Long.valueOf(System.currentTimeMillis()) : null);
|
||||
groupPersonRef.setErrorMessage(((HandleFaceResult)handleFaceResult.getData()).getInfo());
|
||||
groupPersonRef.setGender(((HandleFaceResult)handleFaceResult.getData()).getGender());
|
||||
groupPersonRef.setAge(((HandleFaceResult)handleFaceResult.getData()).getAge());
|
||||
}
|
||||
return this.groupPersonRefMapper.updateImageDataByIds(groupPersonRef, Arrays.asList(((GroupPersonRef)groupPersonRefList.get(0)).getId()));
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor={Exception.class}, propagation=Propagation.REQUIRED)
|
||||
public void updateGroupPersonRefStatus(short status, Set<String> ids) {
|
||||
GroupPersonRef record = new GroupPersonRef();
|
||||
record.setStatus(Short.valueOf(status));
|
||||
if (0 == status) {
|
||||
record.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
} else {
|
||||
record.setIsDel(DelStatusEnum.DELETED.getCode());
|
||||
}
|
||||
record.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.groupPersonRefMapper.updateStatusByIds(record, ids);
|
||||
DevicePersonSyncLogDTO syncLogDTO = new DevicePersonSyncLogDTO();
|
||||
syncLogDTO.setGroupPersonRefIds(new ArrayList<String>(ids));
|
||||
syncLogDTO.setLastUpdateTime(record.getLastUpdateTime());
|
||||
this.devicePersonSyncLogMapper.updateLastTimeByGroupPersonRef(syncLogDTO);
|
||||
}
|
||||
|
||||
private GroupPersonRef generateGroupPersonRefAdd(GroupPersonRef groupPersonRef) {
|
||||
groupPersonRef.setId(CloudwalkDateUtils.getUUID());
|
||||
long time = System.currentTimeMillis();
|
||||
groupPersonRef.setCreateTime(Long.valueOf(time));
|
||||
groupPersonRef.setCreateUserId("system");
|
||||
groupPersonRef.setLastUpdateUserId("system");
|
||||
groupPersonRef.setLastUpdateTime(Long.valueOf(time));
|
||||
if (groupPersonRef.getStatus() == null) {
|
||||
groupPersonRef.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
} else if (0 == groupPersonRef.getStatus()) {
|
||||
groupPersonRef.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
} else {
|
||||
groupPersonRef.setIsDel(DelStatusEnum.DELETED.getCode());
|
||||
}
|
||||
return groupPersonRef;
|
||||
}
|
||||
|
||||
public SyncPersonDTO generateSyncPersonDTO(GroupPersonRef groupPersonRef, int action, Long oldExpiryBeginDate, Long oldExpiryEndDate) {
|
||||
ImgStorePerson person = this.imgStorePersonMapper.selectByPrimaryKey(groupPersonRef.getPersonId());
|
||||
SyncPersonDTO syncPersonDTO = new SyncPersonDTO(groupPersonRef.getId(), groupPersonRef.getImageStoreId(), person.getImageId(), action);
|
||||
syncPersonDTO.setOldExpiryBeginDate(oldExpiryBeginDate);
|
||||
syncPersonDTO.setOldExpiryEndDate(oldExpiryEndDate);
|
||||
syncPersonDTO.setNewExpiryBeginDate(groupPersonRef.getExpiryBeginDate());
|
||||
syncPersonDTO.setNewExpiryEndDate(groupPersonRef.getExpiryEndDate());
|
||||
return syncPersonDTO;
|
||||
}
|
||||
|
||||
private SyncPersonDTO generateDelSyncPersonDTO(GroupPersonRef groupPersonRef, int action, Long oldExpiryBeginDate, Long oldExpiryEndDate) {
|
||||
ImgStorePerson person = this.imgStorePersonMapper.selectByPrimaryKey(groupPersonRef.getPersonId());
|
||||
SyncPersonDTO syncPersonDTO = new SyncPersonDTO(groupPersonRef.getId(), groupPersonRef.getImageStoreId(), person.getImageId(), action);
|
||||
syncPersonDTO.setOldExpiryBeginDate(oldExpiryBeginDate);
|
||||
syncPersonDTO.setOldExpiryEndDate(oldExpiryEndDate);
|
||||
syncPersonDTO.setNewExpiryBeginDate(null);
|
||||
syncPersonDTO.setNewExpiryEndDate(null);
|
||||
return syncPersonDTO;
|
||||
}
|
||||
|
||||
private GroupPersonRef generateGroupPersonRefMod(GroupPersonRef groupPersonRef) {
|
||||
if (groupPersonRef.getStatus() == null) {
|
||||
groupPersonRef.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
} else if (0 == groupPersonRef.getStatus()) {
|
||||
groupPersonRef.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
} else {
|
||||
groupPersonRef.setIsDel(DelStatusEnum.DELETED.getCode());
|
||||
}
|
||||
long time = System.currentTimeMillis();
|
||||
groupPersonRef.setLastUpdateUserId("system");
|
||||
groupPersonRef.setLastUpdateTime(Long.valueOf(time));
|
||||
return groupPersonRef;
|
||||
}
|
||||
|
||||
@Async
|
||||
public void executeHandleGroupFace() {
|
||||
long s1 = System.currentTimeMillis();
|
||||
List list = this.groupPersonRefMapper.queryHandleFaceException(DelStatusEnum.NORAML.getCode(), Arrays.asList(GroupModelStatusEnum.MODEL_WAIT.getCode(), GroupModelStatusEnum.MODEL_FAILED.getCode()));
|
||||
long e1 = System.currentTimeMillis();
|
||||
this.logger.debug("HandleGroupFaceExceptionTask 查询人员正常但未入库、入库失败 耗时:[{}]", (Object)(e1 - s1));
|
||||
Map<Short, List<GroupPersonRefDTO>> groupPersonMap = (java.util.Map<java.lang.Short,java.util.List<cn.cloudwalk.data.organization.dto.GroupPersonRefDTO>>) list.stream().collect(Collectors.groupingBy(GroupPersonRef::getGroupStatus));
|
||||
if (!CollectionUtils.isEmpty((Collection)list)) {
|
||||
List<GroupPersonRefDTO> modelWaitList = groupPersonMap.get(GroupModelStatusEnum.MODEL_WAIT.getCode());
|
||||
List<GroupPersonRefDTO> modelFailedList = groupPersonMap.get(GroupModelStatusEnum.MODEL_FAILED.getCode());
|
||||
if (!CollectionUtils.isEmpty(modelWaitList)) {
|
||||
this.logger.debug("HandleGroupFaceExceptionTask 处理未入库[{}]", (Object)modelWaitList.size());
|
||||
modelWaitList.stream().forEach(groupPersonRef -> this.addFace((GroupPersonRefDTO)groupPersonRef));
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(modelFailedList)) {
|
||||
this.logger.debug("HandleGroupFaceExceptionTask 处理入库失败[{}]", (Object)modelFailedList.size());
|
||||
modelFailedList.stream().forEach(groupPersonRef -> this.addFace((GroupPersonRefDTO)groupPersonRef));
|
||||
}
|
||||
}
|
||||
if (CollectionUtils.isEmpty((Collection)list) || list.size() < 1000) {
|
||||
long s2 = System.currentTimeMillis();
|
||||
list = this.groupPersonRefMapper.queryHandleFaceException(DelStatusEnum.DELETED.getCode(), Arrays.asList(GroupModelStatusEnum.MODEL_COMPLETED.getCode(), GroupModelStatusEnum.MODEL_DEL_FAILED.getCode()));
|
||||
long e2 = System.currentTimeMillis();
|
||||
this.logger.debug("HandleGroupFaceExceptionTask 查询人员删除但入库完成、删除失败 耗时:[{}]", (Object)(e2 - s2));
|
||||
groupPersonMap = (java.util.Map<java.lang.Short,java.util.List<cn.cloudwalk.data.organization.dto.GroupPersonRefDTO>>) list.stream().collect(Collectors.groupingBy(GroupPersonRef::getGroupStatus));
|
||||
List<GroupPersonRefDTO> modelCompleteList = groupPersonMap.get(GroupModelStatusEnum.MODEL_COMPLETED.getCode());
|
||||
List<GroupPersonRefDTO> modelDelFailedList = groupPersonMap.get(GroupModelStatusEnum.MODEL_DEL_FAILED.getCode());
|
||||
if (!CollectionUtils.isEmpty(modelCompleteList)) {
|
||||
this.logger.debug("HandleGroupFaceExceptionTask 处理入库成功[{}]", (Object)modelCompleteList.size());
|
||||
modelCompleteList.stream().forEach(groupPersonRef -> this.removeFace((GroupPersonRefDTO)groupPersonRef));
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(modelDelFailedList)) {
|
||||
this.logger.debug("HandleGroupFaceExceptionTask 处理删除失败[{}]", (Object)modelDelFailedList.size());
|
||||
modelDelFailedList.stream().forEach(groupPersonRef -> this.removeFace((GroupPersonRefDTO)groupPersonRef));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void addFace(GroupPersonRefDTO groupPersonRef) {
|
||||
try {
|
||||
CpHandleFaceParam param = new CpHandleFaceParam();
|
||||
param.setImageStoreId(groupPersonRef.getImageStoreId());
|
||||
param.setImageId(groupPersonRef.getImageId());
|
||||
CloudwalkResult addFaceResult = this.cpImageStoreToolService.addFace(param);
|
||||
this.updateGroupPersonRef(groupPersonRef.getImageStoreId(), groupPersonRef.getImageId(), true, (CloudwalkResult<HandleFaceResult>)addFaceResult);
|
||||
}
|
||||
catch (ServiceException e) {
|
||||
this.logger.error("HandleGroupFaceExceptionTask executeHandleGroupFace[{}] addFace exception:{}", (Object)groupPersonRef.getId(), (Object)e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void removeFace(GroupPersonRefDTO groupPersonRef) {
|
||||
try {
|
||||
CpHandleFaceParam param = new CpHandleFaceParam();
|
||||
param.setImageStoreId(groupPersonRef.getImageStoreId());
|
||||
param.setImageId(groupPersonRef.getImageId());
|
||||
CloudwalkResult removeFaceResult = this.cpImageStoreToolService.removeFace(param);
|
||||
this.updateGroupPersonRef(groupPersonRef.getImageStoreId(), groupPersonRef.getImageId(), false, (CloudwalkResult<HandleFaceResult>)removeFaceResult);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("HandleGroupFaceExceptionTask executeHandleGroupFace[{}] removeFace exception:{}", (Object)groupPersonRef.getId(), (Object)e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void setPersonProperty(GroupPersonRefDTO groupPersonRef, GroupPersonRef cpGroupPersonRef) {
|
||||
AgFeatureExtractParam extractParam = new AgFeatureExtractParam();
|
||||
extractParam.setImageUrl(groupPersonRef.getComparePicture());
|
||||
try {
|
||||
CloudwalkResult extractResult = this.cpImageStoreToolService.extractFeature(extractParam);
|
||||
if (extractResult.isSuccess()) {
|
||||
List qualityScoreList = ((AgFeatureExtractResult)extractResult.getData()).getQuality().stream().map(x -> x + "").collect(Collectors.toList());
|
||||
cpGroupPersonRef.setAge(Integer.valueOf(new BigDecimal((String)qualityScoreList.get(10)).setScale(2, 3).intValue()));
|
||||
cpGroupPersonRef.setGender(Short.valueOf(new BigDecimal((String)qualityScoreList.get(11)).shortValue()));
|
||||
}
|
||||
}
|
||||
catch (ServiceException e) {
|
||||
this.logger.error("HandleGroupFaceExceptionTask setPersonProperty exception:{}", (Object)e.getMessage());
|
||||
}
|
||||
}
|
||||
extends AbstractImagStoreService
|
||||
{
|
||||
@Value("${cloudwalk.imagestore.person.sync.batchsize:100}")
|
||||
private int batchSize;
|
||||
@Value("${cloudwalk.imagestore.person.sync.del.batchsize:100}")
|
||||
private int delBatchSize;
|
||||
@Resource
|
||||
private CpImageStoreToolService cpImageStoreToolService;
|
||||
@Resource
|
||||
private GroupPersonRefMapper groupPersonRefMapper;
|
||||
@Resource
|
||||
private DevicePersonSyncLogMapper devicePersonSyncLogMapper;
|
||||
@Resource
|
||||
private ImgStorePersonMapper imgStorePersonMapper;
|
||||
private CloudwalkCallContext context;
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
this.context = getCloudwalkContext();
|
||||
}
|
||||
@Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
|
||||
public List<SyncPersonDTO> handleImageStoreChange(AgImageStoreResult waitSyncImageStore, List<GroupPersonRef> personIdsNeedAdd, List<GroupPersonRef> personIdsNeedUpdate, List<GroupPersonRef> personIdsNeedDelete) {
|
||||
List<SyncPersonDTO> resultList = new ArrayList<>();
|
||||
this.logger.info("CpImageStorePersonUpdateTask,处理新增人员start");
|
||||
resultList.addAll(handleImageStorePersonChange(personIdsNeedAdd, true));
|
||||
this.logger.info("CpImageStorePersonUpdateTask,处理新增人员end");
|
||||
this.logger.info("CpImageStorePersonUpdateTask,处理更新人员start");
|
||||
resultList.addAll(handleImageStorePersonChange(personIdsNeedUpdate, false));
|
||||
this.logger.info("CpImageStorePersonUpdateTask,处理更新人员end");
|
||||
this.logger.info("CpImageStorePersonUpdateTask,处理删除人员start");
|
||||
for (GroupPersonRef delGroupPersonRef : personIdsNeedDelete) {
|
||||
resultList.add(generateDelSyncPersonDTO(delGroupPersonRef, -1, delGroupPersonRef
|
||||
.getExpiryBeginDate(), delGroupPersonRef.getExpiryEndDate()));
|
||||
}
|
||||
handleImageStorePersonDelete(waitSyncImageStore.getId(), (List<String>)personIdsNeedDelete.stream().map(GroupPersonRef::getPersonId).collect(Collectors.toList()));
|
||||
this.logger.info("CpImageStorePersonUpdateTask,处理删除人员end");
|
||||
return resultList;
|
||||
}
|
||||
@Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
|
||||
public void handlePersonDelete(ImgStorePerson imgStorePerson, Set<String> imageStoreIdsNeedDelete) {
|
||||
deletePersonFromImageStores(imgStorePerson, imageStoreIdsNeedDelete);
|
||||
}
|
||||
private List<SyncPersonDTO> handleImageStorePersonChange(List<GroupPersonRef> changePersonIds, boolean add) {
|
||||
List<SyncPersonDTO> syncPersonList = new ArrayList<>();
|
||||
if (Collections3.isEmpty(changePersonIds)) {
|
||||
return syncPersonList;
|
||||
}
|
||||
if (add) {
|
||||
List<GroupPersonRef> groupPersonRefList = new ArrayList<>(this.batchSize);
|
||||
int total = 0;
|
||||
for (GroupPersonRef changePersonId : changePersonIds) {
|
||||
GroupPersonRef addGroupPersonRef = generateGroupPersonRefAdd(changePersonId);
|
||||
SyncPersonDTO addSyncPersonDTO = generateSyncPersonDTO(addGroupPersonRef, 0, (Long)null, (Long)null);
|
||||
if (StringUtils.isEmpty(addSyncPersonDTO.getImageId())) {
|
||||
syncPersonList.add(addSyncPersonDTO);
|
||||
addGroupPersonRef.resetGroupStatus(Short.valueOf((short)0));
|
||||
} else {
|
||||
syncPersonList.add(addSyncPersonDTO);
|
||||
addGroupPersonRef.resetGroupStatus(GroupModelStatusEnum.MODEL_WAIT.getCode());
|
||||
}
|
||||
groupPersonRefList.add(addGroupPersonRef);
|
||||
total++;
|
||||
if (total >= this.batchSize) {
|
||||
this.groupPersonRefMapper.batchInsert(groupPersonRefList);
|
||||
groupPersonRefList = new ArrayList<>(this.batchSize);
|
||||
total = 0;
|
||||
}
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(groupPersonRefList)) {
|
||||
this.groupPersonRefMapper.batchInsert(groupPersonRefList);
|
||||
}
|
||||
} else {
|
||||
for (GroupPersonRef changePersonId : changePersonIds) {
|
||||
int personAction; Short oldIsDel = changePersonId.getIsDel();
|
||||
GroupPersonRef modGroupPersonRef = generateGroupPersonRefMod(changePersonId);
|
||||
if (DelStatusEnum.DELETED.getCode().shortValue() == oldIsDel.shortValue() && DelStatusEnum.NORAML
|
||||
.getCode().shortValue() == modGroupPersonRef.getIsDel().shortValue()) {
|
||||
personAction = 0;
|
||||
} else if (DelStatusEnum.NORAML.getCode().shortValue() == oldIsDel.shortValue() && DelStatusEnum.DELETED
|
||||
.getCode().shortValue() == modGroupPersonRef.getIsDel().shortValue()) {
|
||||
personAction = -1;
|
||||
} else {
|
||||
personAction = 1;
|
||||
}
|
||||
SyncPersonDTO modSyncPersonDTO = generateSyncPersonDTO(modGroupPersonRef, personAction, modGroupPersonRef
|
||||
.getOldExpiryBeginDate(), modGroupPersonRef.getOldExpiryEndDate());
|
||||
boolean flag = (personAction == 1 && DelStatusEnum.NORAML.getCode().shortValue() == modGroupPersonRef.getIsDel().shortValue() && DelStatusEnum.NORAML.getCode().shortValue() == oldIsDel.shortValue());
|
||||
this.logger.debug("CpImageStorePersonUpdateTask handleImageStorePersonChange mod flag: {}", Boolean.valueOf(flag));
|
||||
if (StringUtils.isEmpty(modSyncPersonDTO.getImageId())) {
|
||||
modGroupPersonRef.resetGroupStatus(Short.valueOf((short)0));
|
||||
}
|
||||
else if (!flag) {
|
||||
modGroupPersonRef.resetGroupStatus(GroupModelStatusEnum.MODEL_WAIT.getCode());
|
||||
}
|
||||
modGroupPersonRef.setExpiryBeginDateStatus(Integer.valueOf(0));
|
||||
modGroupPersonRef.setExpiryEndDateStatus(Integer.valueOf(0));
|
||||
syncPersonList.add(modSyncPersonDTO);
|
||||
if (!flag) {
|
||||
this.groupPersonRefMapper.updateByPrimaryKey(modGroupPersonRef);
|
||||
} else {
|
||||
this.groupPersonRefMapper.updateByPrimaryKeySelective(modGroupPersonRef);
|
||||
}
|
||||
DevicePersonSyncLogDTO dto = new DevicePersonSyncLogDTO();
|
||||
dto.setGroupPersonRefId(modGroupPersonRef.getId());
|
||||
dto.setStatus(Integer.valueOf(SyncStatusEnum.NOT_PULL.getValue()));
|
||||
dto.setCode("");
|
||||
dto.setErrorMessage("");
|
||||
dto.setLastUpdateTime(modGroupPersonRef.getLastUpdateTime());
|
||||
dto.setUpdateInfo("更新图库人员信息,更新同步记录状态:设备未拉取");
|
||||
int res = this.devicePersonSyncLogMapper.updateStatusByGroupPersonRef(dto);
|
||||
this.logger.debug("更新图库人员信息[{}],更新[{}]条同步记录状态为未拉取", modGroupPersonRef.getId(), Integer.valueOf(res));
|
||||
}
|
||||
}
|
||||
return syncPersonList;
|
||||
}
|
||||
public SyncPersonDTO handleImageStorePersonUpdate(GroupPersonRef groupPersonRef, String oldImageId) {
|
||||
SyncPersonDTO result;
|
||||
GroupPersonRef modGroupPersonRef = generateGroupPersonRefMod(groupPersonRef);
|
||||
if (StringUtils.isEmpty(oldImageId)) {
|
||||
result = generateSyncPersonDTO(modGroupPersonRef, 0, modGroupPersonRef
|
||||
.getOldExpiryBeginDate(), modGroupPersonRef.getOldExpiryEndDate());
|
||||
if (!StringUtils.isEmpty(result.getImageId()))
|
||||
{
|
||||
modGroupPersonRef.resetGroupStatus(GroupModelStatusEnum.MODEL_WAIT.getCode());
|
||||
}
|
||||
} else {
|
||||
result = generateSyncPersonDTO(modGroupPersonRef, 1, modGroupPersonRef
|
||||
.getOldExpiryBeginDate(), modGroupPersonRef.getOldExpiryEndDate());
|
||||
result.setOldImageId(oldImageId);
|
||||
if (!StringUtils.isEmpty(result.getImageId()) && !oldImageId.equals(result.getImageId()))
|
||||
{
|
||||
modGroupPersonRef.resetGroupStatus(GroupModelStatusEnum.MODEL_WAIT.getCode());
|
||||
}
|
||||
}
|
||||
if (StringUtils.isEmpty(result.getImageId()))
|
||||
{
|
||||
modGroupPersonRef.resetGroupStatus(Short.valueOf((short)0));
|
||||
}
|
||||
this.groupPersonRefMapper.updateByPrimaryKey(modGroupPersonRef);
|
||||
DevicePersonSyncLogDTO syncLogDTO = new DevicePersonSyncLogDTO();
|
||||
syncLogDTO.setGroupPersonRefIds(Arrays.asList(new String[] { modGroupPersonRef.getId() }));
|
||||
syncLogDTO.setLastUpdateTime(modGroupPersonRef.getLastUpdateTime());
|
||||
this.devicePersonSyncLogMapper.updateLastTimeByGroupPersonRef(syncLogDTO);
|
||||
return result;
|
||||
}
|
||||
private void handleImageStorePersonDelete(String imageStoreId, List<String> changePersonIds) {
|
||||
if (Collections3.isEmpty(changePersonIds)) {
|
||||
return;
|
||||
}
|
||||
DelGroupPersonDTO deleteParam = new DelGroupPersonDTO();
|
||||
deleteParam.setImageStoreId(imageStoreId);
|
||||
deleteParam.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
deleteParam.setLastUpdateUserId(this.context.getUser().getCaller());
|
||||
deleteParam.setExpiryBeginDateStatus(Integer.valueOf(0));
|
||||
deleteParam.setExpiryEndDateStatus(Integer.valueOf(0));
|
||||
DevicePersonSyncLogDTO devicePersonSyncLogDTO = new DevicePersonSyncLogDTO();
|
||||
devicePersonSyncLogDTO.setImageStoreId(imageStoreId);
|
||||
devicePersonSyncLogDTO.setStatus(Integer.valueOf(SyncStatusEnum.NOT_PULL.getValue()));
|
||||
devicePersonSyncLogDTO.setCode("");
|
||||
devicePersonSyncLogDTO.setErrorMessage("");
|
||||
devicePersonSyncLogDTO.setLastUpdateTime(deleteParam.getLastUpdateTime());
|
||||
devicePersonSyncLogDTO.setUpdateInfo("删除人员,更新同步记录状态:设备未拉取");
|
||||
devicePersonSyncLogDTO.setIsDel(Integer.valueOf(DelStatusEnum.DELETED.getCode().shortValue()));
|
||||
List<List<String>> partition = Lists.partition(changePersonIds, this.delBatchSize);
|
||||
for (List<String> list : partition) {
|
||||
deleteParam.setPersonIds(list);
|
||||
devicePersonSyncLogDTO.setPersonIds(list);
|
||||
this.groupPersonRefMapper.logicDeleteExpireNullByParam(deleteParam);
|
||||
int res = this.devicePersonSyncLogMapper.updateStatusByCondition(devicePersonSyncLogDTO);
|
||||
this.logger.debug("删除人员,更新[{}]条同步记录,图库Id:[{}],人员Id列表[{}]", new Object[] { Integer.valueOf(res), imageStoreId, JSON.toJSONString(list) });
|
||||
}
|
||||
}
|
||||
private void deletePersonFromImageStores(ImgStorePerson imgStorePerson, Set<String> imageStoreIdsNeedDelete) {
|
||||
if (!CollectionUtils.isEmpty(imageStoreIdsNeedDelete)) {
|
||||
DelGroupPersonDTO deleteParam = new DelGroupPersonDTO();
|
||||
deleteParam.setPersonId(imgStorePerson.getId());
|
||||
deleteParam.setImageStoreIds(imageStoreIdsNeedDelete);
|
||||
deleteParam.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
deleteParam.setLastUpdateUserId(this.context.getUser().getCaller());
|
||||
this.groupPersonRefMapper.logicDeleteExpireNullByParam(deleteParam);
|
||||
}
|
||||
for (String deleteImageStoreId : imageStoreIdsNeedDelete) {
|
||||
handleImageStoreImageChange(deleteImageStoreId,
|
||||
Sets.newHashSet((Object[])new String[] { imgStorePerson.getImageId() }), false);
|
||||
}
|
||||
}
|
||||
@Async("handleImageTaskExecutor")
|
||||
public void handleImageStoreImageChange(String imageStoreId, Set<String> changeImageIds, boolean add) {
|
||||
if (Collections3.isEmpty(changeImageIds)) {
|
||||
return;
|
||||
}
|
||||
List<String> changeImageList = new ArrayList<>(changeImageIds);
|
||||
if (add) {
|
||||
CpHandleFaceParam handleFaceParam = new CpHandleFaceParam();
|
||||
handleFaceParam.setImageStoreId(imageStoreId);
|
||||
changeImageList.stream().forEach(imageId -> {
|
||||
try {
|
||||
handleFaceParam.setImageId(imageId);
|
||||
CloudwalkResult<HandleFaceResult> addFaceResult = this.cpImageStoreToolService.addFace(handleFaceParam);
|
||||
updateGroupPersonRef(imageStoreId, imageId, add, addFaceResult);
|
||||
} catch (ServiceException e) {
|
||||
this.logger.warn("handleImageStoreImageChange exception,errorCode:[{}], errorMessage:[{}]", e.getCode(), e.getMessage());
|
||||
}
|
||||
});
|
||||
} else {
|
||||
CpHandleFaceParam cpHandleFaceParam = new CpHandleFaceParam();
|
||||
cpHandleFaceParam.setImageStoreId(imageStoreId);
|
||||
changeImageList.stream().forEach(imageId -> {
|
||||
try {
|
||||
cpHandleFaceParam.setImageId(imageId);
|
||||
CloudwalkResult<HandleFaceResult> removeFaceResult = this.cpImageStoreToolService.removeFace(cpHandleFaceParam);
|
||||
updateGroupPersonRef(imageStoreId, imageId, add, removeFaceResult);
|
||||
} catch (ServiceException e) {
|
||||
this.logger.warn("handleImageStoreImageChange exception,errorCode:[{}], errorMessage:[{}]", e.getCode(), e.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
private int updateGroupPersonRef(String imageStoreId, String imageId, boolean add, CloudwalkResult<HandleFaceResult> handleFaceResult) throws ServiceException {
|
||||
ImgStorePersonQueryDto queryDto = new ImgStorePersonQueryDto();
|
||||
queryDto.setImageIds(Arrays.asList(new String[] { imageId }));
|
||||
List<ImgStorePerson> personList = this.imgStorePersonMapper.getByImageId(queryDto);
|
||||
if (CollectionUtils.isEmpty(personList)) {
|
||||
this.logger.warn("根据imageId[{}]获取不到人员信息", imageId);
|
||||
throw new ServiceException("人员信息详情查询失败,原因:{}", getMessage("人员信息详情查询失败,原因:{}"));
|
||||
}
|
||||
GroupPersonRef groupPersonRef = new GroupPersonRef();
|
||||
groupPersonRef.setImageStoreId(imageStoreId);
|
||||
List<GroupPersonRef> groupPersonRefList = this.groupPersonRefMapper.selectByCondition(groupPersonRef, (List)personList.stream().map(ImgStorePerson::getId).collect(
|
||||
Collectors.toList()));
|
||||
if (CollectionUtils.isEmpty(groupPersonRefList)) {
|
||||
this.logger.warn("图库图片同步失败,根据imageStoreId:[{}],personId:[{}]获取不到图库人员列表信息", imageStoreId, ((HandleFaceResult)handleFaceResult.getData()).getPersonId());
|
||||
throw new ServiceException("53014702", getMessage("53014702"));
|
||||
}
|
||||
groupPersonRef.setGroupStatus(add ? GroupModelStatusEnum.MODEL_FAILED.getCode() : GroupModelStatusEnum.MODEL_DEL_FAILED.getCode());
|
||||
groupPersonRef.setErrorMessage(handleFaceResult.getMessage());
|
||||
if (handleFaceResult.isSuccess() && ((HandleFaceResult)handleFaceResult.getData()).getResult().intValue() == 0) {
|
||||
groupPersonRef.setGroupStatus(add ? GroupModelStatusEnum.MODEL_COMPLETED.getCode() : GroupModelStatusEnum.MODEL_WAIT.getCode());
|
||||
groupPersonRef.setGroupTime(add ? Long.valueOf(System.currentTimeMillis()) : null);
|
||||
groupPersonRef.setErrorMessage(((HandleFaceResult)handleFaceResult.getData()).getInfo());
|
||||
groupPersonRef.setGender(((HandleFaceResult)handleFaceResult.getData()).getGender());
|
||||
groupPersonRef.setAge(((HandleFaceResult)handleFaceResult.getData()).getAge());
|
||||
}
|
||||
return this.groupPersonRefMapper.updateImageDataByIds(groupPersonRef, Arrays.asList(new String[] { ((GroupPersonRef)groupPersonRefList.get(0)).getId() }));
|
||||
}
|
||||
@Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
|
||||
public void updateGroupPersonRefStatus(short status, Set<String> ids) {
|
||||
GroupPersonRef record = new GroupPersonRef();
|
||||
record.setStatus(Short.valueOf(status));
|
||||
if (0 == status) {
|
||||
record.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
} else {
|
||||
record.setIsDel(DelStatusEnum.DELETED.getCode());
|
||||
}
|
||||
record.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.groupPersonRefMapper.updateStatusByIds(record, ids);
|
||||
DevicePersonSyncLogDTO syncLogDTO = new DevicePersonSyncLogDTO();
|
||||
syncLogDTO.setGroupPersonRefIds(new ArrayList<>(ids));
|
||||
syncLogDTO.setLastUpdateTime(record.getLastUpdateTime());
|
||||
this.devicePersonSyncLogMapper.updateLastTimeByGroupPersonRef(syncLogDTO);
|
||||
}
|
||||
private GroupPersonRef generateGroupPersonRefAdd(GroupPersonRef groupPersonRef) {
|
||||
groupPersonRef.setId(CloudwalkDateUtils.getUUID());
|
||||
long time = System.currentTimeMillis();
|
||||
groupPersonRef.setCreateTime(Long.valueOf(time));
|
||||
groupPersonRef.setCreateUserId("system");
|
||||
groupPersonRef.setLastUpdateUserId("system");
|
||||
groupPersonRef.setLastUpdateTime(Long.valueOf(time));
|
||||
if (groupPersonRef.getStatus() == null) {
|
||||
groupPersonRef.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
}
|
||||
else if (0 == groupPersonRef.getStatus().shortValue()) {
|
||||
groupPersonRef.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
} else {
|
||||
groupPersonRef.setIsDel(DelStatusEnum.DELETED.getCode());
|
||||
}
|
||||
return groupPersonRef;
|
||||
}
|
||||
public SyncPersonDTO generateSyncPersonDTO(GroupPersonRef groupPersonRef, int action, Long oldExpiryBeginDate, Long oldExpiryEndDate) {
|
||||
ImgStorePerson person = this.imgStorePersonMapper.selectByPrimaryKey(groupPersonRef.getPersonId());
|
||||
SyncPersonDTO syncPersonDTO = new SyncPersonDTO(groupPersonRef.getId(), groupPersonRef.getImageStoreId(), person.getImageId(), action);
|
||||
syncPersonDTO.setOldExpiryBeginDate(oldExpiryBeginDate);
|
||||
syncPersonDTO.setOldExpiryEndDate(oldExpiryEndDate);
|
||||
syncPersonDTO.setNewExpiryBeginDate(groupPersonRef.getExpiryBeginDate());
|
||||
syncPersonDTO.setNewExpiryEndDate(groupPersonRef.getExpiryEndDate());
|
||||
return syncPersonDTO;
|
||||
}
|
||||
private SyncPersonDTO generateDelSyncPersonDTO(GroupPersonRef groupPersonRef, int action, Long oldExpiryBeginDate, Long oldExpiryEndDate) {
|
||||
ImgStorePerson person = this.imgStorePersonMapper.selectByPrimaryKey(groupPersonRef.getPersonId());
|
||||
SyncPersonDTO syncPersonDTO = new SyncPersonDTO(groupPersonRef.getId(), groupPersonRef.getImageStoreId(), person.getImageId(), action);
|
||||
syncPersonDTO.setOldExpiryBeginDate(oldExpiryBeginDate);
|
||||
syncPersonDTO.setOldExpiryEndDate(oldExpiryEndDate);
|
||||
syncPersonDTO.setNewExpiryBeginDate(null);
|
||||
syncPersonDTO.setNewExpiryEndDate(null);
|
||||
return syncPersonDTO;
|
||||
}
|
||||
private GroupPersonRef generateGroupPersonRefMod(GroupPersonRef groupPersonRef) {
|
||||
if (groupPersonRef.getStatus() == null) {
|
||||
groupPersonRef.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
}
|
||||
else if (0 == groupPersonRef.getStatus().shortValue()) {
|
||||
groupPersonRef.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
} else {
|
||||
groupPersonRef.setIsDel(DelStatusEnum.DELETED.getCode());
|
||||
}
|
||||
long time = System.currentTimeMillis();
|
||||
groupPersonRef.setLastUpdateUserId("system");
|
||||
groupPersonRef.setLastUpdateTime(Long.valueOf(time));
|
||||
return groupPersonRef;
|
||||
}
|
||||
@Async
|
||||
public void executeHandleGroupFace() {
|
||||
long s1 = System.currentTimeMillis();
|
||||
List<GroupPersonRefDTO> list = this.groupPersonRefMapper.queryHandleFaceException(DelStatusEnum.NORAML.getCode(),
|
||||
Arrays.asList(new Short[] { GroupModelStatusEnum.MODEL_WAIT.getCode(), GroupModelStatusEnum.MODEL_FAILED.getCode() }));
|
||||
long e1 = System.currentTimeMillis();
|
||||
this.logger.debug("HandleGroupFaceExceptionTask 查询人员正常但未入库、入库失败 耗时:[{}]", Long.valueOf(e1 - s1));
|
||||
Map<Short, List<GroupPersonRefDTO>> groupPersonMap = (Map<Short, List<GroupPersonRefDTO>>)list.stream().collect(Collectors.groupingBy(GroupPersonRef::getGroupStatus));
|
||||
if (!CollectionUtils.isEmpty(list)) {
|
||||
List<GroupPersonRefDTO> modelWaitList = groupPersonMap.get(GroupModelStatusEnum.MODEL_WAIT.getCode());
|
||||
List<GroupPersonRefDTO> modelFailedList = groupPersonMap.get(GroupModelStatusEnum.MODEL_FAILED.getCode());
|
||||
if (!CollectionUtils.isEmpty(modelWaitList)) {
|
||||
this.logger.debug("HandleGroupFaceExceptionTask 处理未入库[{}]", Integer.valueOf(modelWaitList.size()));
|
||||
modelWaitList.stream().forEach(groupPersonRef -> addFace(groupPersonRef));
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(modelFailedList)) {
|
||||
this.logger.debug("HandleGroupFaceExceptionTask 处理入库失败[{}]", Integer.valueOf(modelFailedList.size()));
|
||||
modelFailedList.stream().forEach(groupPersonRef -> addFace(groupPersonRef));
|
||||
}
|
||||
}
|
||||
if (CollectionUtils.isEmpty(list) || list.size() < 1000) {
|
||||
long s2 = System.currentTimeMillis();
|
||||
list = this.groupPersonRefMapper.queryHandleFaceException(DelStatusEnum.DELETED.getCode(),
|
||||
Arrays.asList(new Short[] { GroupModelStatusEnum.MODEL_COMPLETED.getCode(), GroupModelStatusEnum.MODEL_DEL_FAILED.getCode() }));
|
||||
long e2 = System.currentTimeMillis();
|
||||
this.logger.debug("HandleGroupFaceExceptionTask 查询人员删除但入库完成、删除失败 耗时:[{}]", Long.valueOf(e2 - s2));
|
||||
groupPersonMap = (Map<Short, List<GroupPersonRefDTO>>)list.stream().collect(Collectors.groupingBy(GroupPersonRef::getGroupStatus));
|
||||
List<GroupPersonRefDTO> modelCompleteList = groupPersonMap.get(GroupModelStatusEnum.MODEL_COMPLETED.getCode());
|
||||
List<GroupPersonRefDTO> modelDelFailedList = groupPersonMap.get(GroupModelStatusEnum.MODEL_DEL_FAILED.getCode());
|
||||
if (!CollectionUtils.isEmpty(modelCompleteList)) {
|
||||
this.logger.debug("HandleGroupFaceExceptionTask 处理入库成功[{}]", Integer.valueOf(modelCompleteList.size()));
|
||||
modelCompleteList.stream().forEach(groupPersonRef -> removeFace(groupPersonRef));
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(modelDelFailedList)) {
|
||||
this.logger.debug("HandleGroupFaceExceptionTask 处理删除失败[{}]", Integer.valueOf(modelDelFailedList.size()));
|
||||
modelDelFailedList.stream().forEach(groupPersonRef -> removeFace(groupPersonRef));
|
||||
}
|
||||
}
|
||||
}
|
||||
private void addFace(GroupPersonRefDTO groupPersonRef) {
|
||||
try {
|
||||
CpHandleFaceParam param = new CpHandleFaceParam();
|
||||
param.setImageStoreId(groupPersonRef.getImageStoreId());
|
||||
param.setImageId(groupPersonRef.getImageId());
|
||||
CloudwalkResult<HandleFaceResult> addFaceResult = this.cpImageStoreToolService.addFace(param);
|
||||
updateGroupPersonRef(groupPersonRef.getImageStoreId(), groupPersonRef.getImageId(), true, addFaceResult);
|
||||
} catch (ServiceException e) {
|
||||
this.logger.error("HandleGroupFaceExceptionTask executeHandleGroupFace[{}] addFace exception:{}", groupPersonRef.getId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
private void removeFace(GroupPersonRefDTO groupPersonRef) {
|
||||
try {
|
||||
CpHandleFaceParam param = new CpHandleFaceParam();
|
||||
param.setImageStoreId(groupPersonRef.getImageStoreId());
|
||||
param.setImageId(groupPersonRef.getImageId());
|
||||
CloudwalkResult<HandleFaceResult> removeFaceResult = this.cpImageStoreToolService.removeFace(param);
|
||||
updateGroupPersonRef(groupPersonRef.getImageStoreId(), groupPersonRef.getImageId(), false, removeFaceResult);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("HandleGroupFaceExceptionTask executeHandleGroupFace[{}] removeFace exception:{}", groupPersonRef.getId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
private void setPersonProperty(GroupPersonRefDTO groupPersonRef, GroupPersonRef cpGroupPersonRef) {
|
||||
AgFeatureExtractParam extractParam = new AgFeatureExtractParam();
|
||||
extractParam.setImageUrl(groupPersonRef.getComparePicture());
|
||||
try {
|
||||
CloudwalkResult<AgFeatureExtractResult> extractResult = this.cpImageStoreToolService.extractFeature(extractParam);
|
||||
if (extractResult.isSuccess()) {
|
||||
List<String> qualityScoreList = (List<String>)((AgFeatureExtractResult)extractResult.getData()).getQuality().stream().map(x -> x + "").collect(
|
||||
Collectors.toList());
|
||||
cpGroupPersonRef.setAge(Integer.valueOf((new BigDecimal(qualityScoreList.get(10))).setScale(2, 3).intValue()));
|
||||
cpGroupPersonRef.setGender(Short.valueOf((new BigDecimal(qualityScoreList.get(11))).shortValue()));
|
||||
}
|
||||
} catch (ServiceException e) {
|
||||
this.logger.error("HandleGroupFaceExceptionTask setPersonProperty exception:{}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/CpImageStorePersonTxHandler.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+481
-569
File diff suppressed because it is too large
Load Diff
+783
@@ -0,0 +1,783 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.account.account.param.GeneralQueryBusinessParam;
|
||||
import cn.cloudwalk.client.account.account.result.AcBusinessDTO;
|
||||
import cn.cloudwalk.client.account.account.service.AcBusinessService;
|
||||
import cn.cloudwalk.client.aggregate.application.param.ApplicationImageStoreQueryParam;
|
||||
import cn.cloudwalk.client.aggregate.application.result.ApplicationImageStoreQueryResult;
|
||||
import cn.cloudwalk.client.aggregate.application.service.ApplicationImageStoreService;
|
||||
import cn.cloudwalk.client.aggregate.common.enums.DelStatusEnum;
|
||||
import cn.cloudwalk.client.aggregate.common.enums.SyncStatusEnum;
|
||||
import cn.cloudwalk.client.aggregate.device.param.DeviceImageStoreQueryParam;
|
||||
import cn.cloudwalk.client.aggregate.device.result.DeviceImageStoreQueryResult;
|
||||
import cn.cloudwalk.client.aggregate.device.service.AggDeviceImageStoreService;
|
||||
import cn.cloudwalk.client.aggregate.group.param.AgImageStoreAddParam;
|
||||
import cn.cloudwalk.client.aggregate.group.param.AgImageStoreEditParam;
|
||||
import cn.cloudwalk.client.aggregate.group.param.AgImageStoreKeyParam;
|
||||
import cn.cloudwalk.client.aggregate.group.param.AgImageStoreQueryParam;
|
||||
import cn.cloudwalk.client.aggregate.group.result.AgImageStoreResult;
|
||||
import cn.cloudwalk.client.aggregate.group.service.AgImageStoreService;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.param.CoreDeviceQueryParam;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.result.AtomicDeviceGetResult;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.service.AtomicDeviceService;
|
||||
import cn.cloudwalk.client.organization.common.enums.CpImageStoreMatchPatternEnum;
|
||||
import cn.cloudwalk.client.organization.service.store.param.AddImageStoreParam;
|
||||
import cn.cloudwalk.client.organization.service.store.param.AssociatedParam;
|
||||
import cn.cloudwalk.client.organization.service.store.param.BaseImageStoreParam;
|
||||
import cn.cloudwalk.client.organization.service.store.param.DelImageStoreParam;
|
||||
import cn.cloudwalk.client.organization.service.store.param.DetailImageStoreParam;
|
||||
import cn.cloudwalk.client.organization.service.store.param.EditImageStoreParam;
|
||||
import cn.cloudwalk.client.organization.service.store.param.QueryImageStoreParam;
|
||||
import cn.cloudwalk.client.organization.service.store.result.AssociatedResult;
|
||||
import cn.cloudwalk.client.organization.service.store.result.DeviceInfoResult;
|
||||
import cn.cloudwalk.client.organization.service.store.result.ImageStoreDetailResult;
|
||||
import cn.cloudwalk.client.organization.service.store.result.ImageStoreResult;
|
||||
import cn.cloudwalk.client.organization.service.store.result.ImgStorePersonResult;
|
||||
import cn.cloudwalk.client.organization.service.store.result.LabelResult;
|
||||
import cn.cloudwalk.client.organization.service.store.result.OrganizationResult;
|
||||
import cn.cloudwalk.client.organization.service.store.result.PageImageStoreResult;
|
||||
import cn.cloudwalk.client.organization.service.store.service.CpImageStoreService;
|
||||
import cn.cloudwalk.client.resource.application.param.ApplicationBasicParam;
|
||||
import cn.cloudwalk.client.resource.application.param.ApplicationQueryParam;
|
||||
import cn.cloudwalk.client.resource.application.result.ApplicationResult;
|
||||
import cn.cloudwalk.client.resource.application.service.ApplicationService;
|
||||
import cn.cloudwalk.client.resource.common.en.CommonStatusEnum;
|
||||
import cn.cloudwalk.cloud.annotation.CloudwalkParamsValidate;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkCallContext;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
import cn.cloudwalk.cloud.page.CloudwalkPageAble;
|
||||
import cn.cloudwalk.cloud.page.CloudwalkPageInfo;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.cloud.utils.BeanCopyUtils;
|
||||
import cn.cloudwalk.cloud.utils.CloudwalkDateUtils;
|
||||
import cn.cloudwalk.data.organization.dto.DelGroupPersonDTO;
|
||||
import cn.cloudwalk.data.organization.dto.GetsImageStoreAssociatedDTO;
|
||||
import cn.cloudwalk.data.organization.dto.ImageStoreCountDTO;
|
||||
import cn.cloudwalk.data.organization.dto.ImgStorePersonQueryDto;
|
||||
import cn.cloudwalk.data.organization.dto.OrganizationImageStoreQueryDTO;
|
||||
import cn.cloudwalk.data.organization.dto.QueryGroupPersonDTO;
|
||||
import cn.cloudwalk.data.organization.entity.GroupPersonRef;
|
||||
import cn.cloudwalk.data.organization.entity.ImgStorePerson;
|
||||
import cn.cloudwalk.data.organization.entity.IsImageStoreAssociated;
|
||||
import cn.cloudwalk.data.organization.entity.OrganizationImageStore;
|
||||
import cn.cloudwalk.data.organization.mapper.GroupPersonRefMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStoreLabelMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStoreOrganizationMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.IsImageStoreAssociatedMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.OrganizationImageStoreMapper;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import cn.cloudwalk.service.organization.common.JsonUtils;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.google.common.collect.Lists;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Resource;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springside.modules.utils.Collections3;
|
||||
@Service
|
||||
public class CpImageStoreServiceImpl
|
||||
extends AbstractImagStoreService
|
||||
implements CpImageStoreService
|
||||
{
|
||||
@Autowired
|
||||
private IsImageStoreAssociatedMapper isImageStoreAssociatedMapper;
|
||||
@Autowired
|
||||
private ImgStoreLabelMapper imgStoreLabelMapper;
|
||||
@Autowired
|
||||
private ImgStoreOrganizationMapper imgStoreOrganizationMapper;
|
||||
@Autowired
|
||||
private ImgStorePersonMapper personMapper;
|
||||
@Autowired
|
||||
private GroupPersonRefMapper groupPersonRefMapper;
|
||||
@Autowired
|
||||
private OrganizationImageStoreMapper organizationImageStoreMapper;
|
||||
@Autowired
|
||||
private AcBusinessService acBusinessService;
|
||||
@Autowired
|
||||
private ApplicationService applicationService;
|
||||
@Autowired
|
||||
private AgImageStoreService agImageStoreService;
|
||||
@Autowired
|
||||
private ApplicationImageStoreService applicationImageStoreService;
|
||||
@Autowired
|
||||
private AggDeviceImageStoreService deviceImageStoreService;
|
||||
@Autowired
|
||||
private CpImageStorePersonSynManager cpImageStorePersonSynManager;
|
||||
@Resource
|
||||
private CpImageStorePersonManager cpImageStorePersonManager;
|
||||
@Resource
|
||||
private AtomicDeviceService atomicDeviceService;
|
||||
@Resource
|
||||
private ApplicationImageStoreService appImageStoreService;
|
||||
@Value("${cloudwalk.imagestore.person.searchSize:2}")
|
||||
private int searchSize;
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<String> add(AddImageStoreParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String imageStoreId = CloudwalkDateUtils.getUUID();
|
||||
AgImageStoreAddParam addParam = new AgImageStoreAddParam();
|
||||
addParam.setId(imageStoreId);
|
||||
addParam.setName(param.getName());
|
||||
addParam.setType(param.getType());
|
||||
addParam.setBusinessId(param.getBusinessId());
|
||||
addParam.setSourceApplicationId(param.getSourceApplicationId());
|
||||
if (StringUtils.isBlank(param.getBusinessId()))
|
||||
{
|
||||
addParam.setBusinessId(context.getCompany().getCompanyId());
|
||||
}
|
||||
List<IsImageStoreAssociated> imageStoreAssociatedList = addBaseImageStore((BaseImageStoreParam)param, context, imageStoreId, addParam.getBusinessId());
|
||||
if (imageStoreAssociatedList.size() > 0) {
|
||||
this.isImageStoreAssociatedMapper.batchInsert(imageStoreAssociatedList);
|
||||
}
|
||||
CloudwalkResult<String> addResult = this.agImageStoreService.add(addParam, context);
|
||||
if (!addResult.isSuccess()) {
|
||||
throw new ServiceException(addResult.getCode(), addResult.getMessage());
|
||||
}
|
||||
this.cpImageStorePersonSynManager.addGroupPersonSynTask(Lists.newArrayList(imageStoreId ), "isAll");
|
||||
return CloudwalkResult.success(imageStoreId);
|
||||
}
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> edit(EditImageStoreParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
checkExistAndStatus(param.getImageStoreId());
|
||||
AgImageStoreEditParam editParam = new AgImageStoreEditParam();
|
||||
editParam.setId(param.getImageStoreId());
|
||||
editParam.setName(param.getName());
|
||||
String businessId = param.getBusinessId();
|
||||
if (StringUtils.isBlank(businessId))
|
||||
{
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
List<IsImageStoreAssociated> imageStoreAssociatedList = addBaseImageStore((BaseImageStoreParam)param, context, param.getImageStoreId(), businessId);
|
||||
if (checkAssociatedIsChange(param.getImageStoreId(), imageStoreAssociatedList)) {
|
||||
this.isImageStoreAssociatedMapper.deleteAllByImageId(param.getImageStoreId());
|
||||
if (imageStoreAssociatedList.size() > 0) {
|
||||
this.isImageStoreAssociatedMapper.batchInsert(imageStoreAssociatedList);
|
||||
}
|
||||
editParam.setStatus(SyncStatusEnum.SYNC_WAIT.getCode());
|
||||
}
|
||||
CloudwalkResult<Boolean> editResult = this.agImageStoreService.edit(editParam, context);
|
||||
if (!editResult.isSuccess()) {
|
||||
throw new ServiceException(editResult.getCode(), editResult.getMessage());
|
||||
}
|
||||
this.cpImageStorePersonSynManager.addGroupPersonSynTask(Lists.newArrayList(param.getImageStoreId() ), "isAll");
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
private boolean checkAssociatedIsChange(String imageStoreId, List<IsImageStoreAssociated> associatedListAfterUpdate) {
|
||||
GetsImageStoreAssociatedDTO queryDTO = new GetsImageStoreAssociatedDTO();
|
||||
queryDTO.setImageStoreId(imageStoreId);
|
||||
List<IsImageStoreAssociated> associatedListBeforeUpdate = this.isImageStoreAssociatedMapper.gets(queryDTO);
|
||||
if (CollectionUtils.isEmpty(associatedListBeforeUpdate) &&
|
||||
CollectionUtils.isEmpty(associatedListAfterUpdate)) {
|
||||
return false;
|
||||
}
|
||||
if (associatedListBeforeUpdate.size() != associatedListAfterUpdate.size()) {
|
||||
return true;
|
||||
}
|
||||
Set<String> associatedStrBeforeUpdate = new HashSet<>(associatedListBeforeUpdate.size());
|
||||
for (IsImageStoreAssociated associateBefore : associatedListBeforeUpdate) {
|
||||
String action = (associateBefore.getAssociatedAction() != null) ? String.valueOf(associateBefore.getAssociatedAction()) : "";
|
||||
associatedStrBeforeUpdate.add(action + associateBefore.getAssociatedObjectIdType() + associateBefore.getAssociatedObjectId() + associateBefore
|
||||
.getExpiryBeginDate() + associateBefore.getExpiryEndDate() + associateBefore.getValidDateCron());
|
||||
}
|
||||
Set<String> associatedStrAfterUpdate = new HashSet<>(associatedListAfterUpdate.size());
|
||||
for (IsImageStoreAssociated associateBeforeAfter : associatedListAfterUpdate) {
|
||||
String action = (associateBeforeAfter.getAssociatedAction() != null) ? String.valueOf(associateBeforeAfter.getAssociatedAction()) : "";
|
||||
associatedStrAfterUpdate.add(action + associateBeforeAfter.getAssociatedObjectIdType() + associateBeforeAfter.getAssociatedObjectId() + associateBeforeAfter
|
||||
.getExpiryBeginDate() + associateBeforeAfter.getExpiryEndDate() + associateBeforeAfter.getValidDateCron());
|
||||
}
|
||||
associatedStrBeforeUpdate.removeAll(associatedStrAfterUpdate);
|
||||
return !CollectionUtils.isEmpty(associatedStrBeforeUpdate);
|
||||
}
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> delete(DelImageStoreParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
checkAppRefByImageStoreIdForDelete(param.getId(), context);
|
||||
checkExistAndStatus(param.getId());
|
||||
QueryGroupPersonDTO queryDTO = new QueryGroupPersonDTO();
|
||||
queryDTO.setImageStoreId(param.getId());
|
||||
queryDTO.setIsDel(Short.valueOf(DelStatusEnum.NORAML.getCode().shortValue()));
|
||||
List<GroupPersonRef> groupPersonList = this.groupPersonRefMapper.query(queryDTO);
|
||||
this.isImageStoreAssociatedMapper.deleteAllByImageId(param.getId());
|
||||
DelGroupPersonDTO delGroupPersonDTO = new DelGroupPersonDTO();
|
||||
delGroupPersonDTO.setImageStoreId(param.getId());
|
||||
delGroupPersonDTO.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
delGroupPersonDTO.setLastUpdateUserId(context.getUser().getCaller());
|
||||
this.groupPersonRefMapper.logicDeleteByParam(delGroupPersonDTO);
|
||||
CloudwalkResult<Boolean> delete = this.agImageStoreService.delete((AgImageStoreKeyParam)BeanCopyUtils.copyProperties(param, AgImageStoreKeyParam.class), context);
|
||||
if (!delete.isSuccess()) {
|
||||
throw new ServiceException(delete.getCode(), delete.getMessage());
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
private void checkAppRefByImageStoreIdForDelete(String imageStoreId, CloudwalkCallContext context) throws ServiceException {
|
||||
ApplicationImageStoreQueryParam queryParam = new ApplicationImageStoreQueryParam();
|
||||
queryParam.setImageStoreId(imageStoreId);
|
||||
CloudwalkResult<List<ApplicationImageStoreQueryResult>> queryResult = this.applicationImageStoreService.query(queryParam, context);
|
||||
if (!queryResult.isSuccess()) {
|
||||
throw new ServiceException(queryResult.getCode(), queryResult.getMessage());
|
||||
}
|
||||
if (!CollectionUtils.isEmpty((Collection)queryResult.getData())) {
|
||||
throw new ServiceException("53013545",
|
||||
getMessage("53013545"));
|
||||
}
|
||||
}
|
||||
public CloudwalkResult<CloudwalkPageAble<PageImageStoreResult>> page(QueryImageStoreParam queryImageStoreParam, CloudwalkCallContext context) throws ServiceException {
|
||||
boolean isEnd = handleQueryParam(queryImageStoreParam);
|
||||
if (isEnd) {
|
||||
return CloudwalkResult.success(new CloudwalkPageAble(new ArrayList(), new CloudwalkPageInfo(queryImageStoreParam
|
||||
.getCurrentPage(), queryImageStoreParam.getRowsOfPage()), 0L));
|
||||
}
|
||||
AgImageStoreQueryParam queryParam = (AgImageStoreQueryParam)BeanCopyUtils.copyProperties(queryImageStoreParam, AgImageStoreQueryParam.class);
|
||||
if (StringUtils.isBlank(queryParam.getBusinessId()))
|
||||
{
|
||||
queryParam.setBusinessId(context.getCompany().getCompanyId());
|
||||
}
|
||||
CloudwalkResult<CloudwalkPageAble<AgImageStoreResult>> agPageResult = this.agImageStoreService.page(queryParam);
|
||||
if (!agPageResult.isSuccess()) {
|
||||
return CloudwalkResult.fail(agPageResult.getCode(), agPageResult.getMessage());
|
||||
}
|
||||
if (agPageResult.getData() == null) {
|
||||
return CloudwalkResult.success(new CloudwalkPageAble(new ArrayList(), new CloudwalkPageInfo(queryParam
|
||||
.getCurrentPage(), queryParam.getRowsOfPage()), 0L));
|
||||
}
|
||||
List<PageImageStoreResult> resultList = packageCpResult(((CloudwalkPageAble)agPageResult.getData()).getDatas(), queryParam.getBusinessId());
|
||||
return CloudwalkResult.success(new CloudwalkPageAble(resultList, new CloudwalkPageInfo(
|
||||
(int)((CloudwalkPageAble)agPageResult.getData()).getCurrentPage(), (int)((CloudwalkPageAble)agPageResult.getData()).getPageSize()), ((CloudwalkPageAble)agPageResult
|
||||
.getData()).getTotalRows()));
|
||||
}
|
||||
public CloudwalkResult<List<ImageStoreResult>> list(QueryImageStoreParam queryImageStoreParam, CloudwalkCallContext cloudwalkContext) throws ServiceException {
|
||||
List<ImageStoreResult> resultList = new ArrayList<>();
|
||||
boolean isEnd = handleQueryParam(queryImageStoreParam);
|
||||
if (isEnd) {
|
||||
return CloudwalkResult.success(resultList);
|
||||
}
|
||||
AgImageStoreQueryParam queryParam = (AgImageStoreQueryParam)BeanCopyUtils.copyProperties(queryImageStoreParam, AgImageStoreQueryParam.class);
|
||||
if (StringUtils.isBlank(queryParam.getBusinessId()))
|
||||
{
|
||||
queryParam.setBusinessId(cloudwalkContext.getCompany().getCompanyId());
|
||||
}
|
||||
CloudwalkResult<List<AgImageStoreResult>> agQueryResult = this.agImageStoreService.query(queryParam);
|
||||
if (!agQueryResult.isSuccess()) {
|
||||
return CloudwalkResult.fail(agQueryResult.getCode(), agQueryResult.getMessage());
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(queryImageStoreParam.getLabelIds())) {
|
||||
GetsImageStoreAssociatedDTO get = new GetsImageStoreAssociatedDTO();
|
||||
get.setAssociatedObjectIds(queryImageStoreParam.getLabelIds());
|
||||
get.setAssociatedObjectIdType(Integer.valueOf(2));
|
||||
List<IsImageStoreAssociated> associateds = this.isImageStoreAssociatedMapper.gets(get);
|
||||
if (CollectionUtils.isEmpty(associateds)) {
|
||||
return CloudwalkResult.success(resultList);
|
||||
}
|
||||
List<String> imageStoreIds = Collections3.extractToList(associateds, "imageStoreId");
|
||||
List<AgImageStoreResult> collect = (List<AgImageStoreResult>)((List)agQueryResult.getData()).stream().filter(a -> imageStoreIds.contains(a.getId())).collect(
|
||||
Collectors.toList());
|
||||
agQueryResult.setData(collect);
|
||||
}
|
||||
resultList = packageImageStoreResult((Collection<AgImageStoreResult>)agQueryResult.getData(), queryParam.getBusinessId());
|
||||
return CloudwalkResult.success(resultList);
|
||||
}
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<ImageStoreDetailResult> detail(DetailImageStoreParam param, CloudwalkCallContext context) {
|
||||
AgImageStoreQueryParam queryParam = new AgImageStoreQueryParam();
|
||||
queryParam.setId(param.getId());
|
||||
CloudwalkResult<List<AgImageStoreResult>> queryResult = this.agImageStoreService.query(queryParam);
|
||||
if (!queryResult.isSuccess()) {
|
||||
return CloudwalkResult.fail(queryResult.getCode(), queryResult.getMessage());
|
||||
}
|
||||
if (CollectionUtils.isEmpty((Collection)queryResult.getData())) {
|
||||
return CloudwalkResult.fail("53013502",
|
||||
getMessage("53013502"));
|
||||
}
|
||||
AgImageStoreResult agImageStoreResult = ((List<AgImageStoreResult>)queryResult.getData()).get(0);
|
||||
ImageStoreDetailResult result = (ImageStoreDetailResult)BeanCopyUtils.copyProperties(agImageStoreResult, ImageStoreDetailResult.class);
|
||||
result.setPersonNum(getPersonNum(agImageStoreResult.getId()));
|
||||
try {
|
||||
result.setBusinessName(getBusinessName(result.getBusinessId()));
|
||||
} catch (ServiceException e) {
|
||||
this.logger.error("查询企业名称错误e:{}", e.getMessage());
|
||||
return CloudwalkResult.fail(e.getCode(), e.getMessage());
|
||||
}
|
||||
try {
|
||||
result.setSourceApplicationName(getSourceApplicationName(result.getSourceApplicationId()));
|
||||
} catch (ServiceException e) {
|
||||
this.logger.error("查询来源应用名称错误e:{}", e.getMessage());
|
||||
return CloudwalkResult.fail(e.getCode(), e.getMessage());
|
||||
}
|
||||
getAssociated(result);
|
||||
DeviceImageStoreQueryParam deviceParam = new DeviceImageStoreQueryParam();
|
||||
deviceParam.setImageStoreId(param.getId());
|
||||
CloudwalkResult<List<DeviceImageStoreQueryResult>> deviceResult = this.deviceImageStoreService.query(deviceParam, context);
|
||||
if (deviceResult.isSuccess()) {
|
||||
result.setDevices(getDeviceList((List<DeviceImageStoreQueryResult>)deviceResult.getData(), context));
|
||||
} else {
|
||||
this.logger.error("图库详情关联设备名称获取失败,result:[{}]", JSONObject.toJSONString(deviceResult));
|
||||
}
|
||||
ApplicationImageStoreQueryParam appParam = new ApplicationImageStoreQueryParam();
|
||||
appParam.setImageStoreId(param.getId());
|
||||
CloudwalkResult<List<ApplicationImageStoreQueryResult>> appResult = this.applicationImageStoreService.query(appParam, context);
|
||||
if (appResult.isSuccess()) {
|
||||
result.setApplicationNames(Collections3.extractToList((Collection)appResult.getData(), "applicationName"));
|
||||
} else {
|
||||
this.logger.error("图库详情关联应用名称获取失败,result:[{}]", JSONObject.toJSONString(appResult));
|
||||
}
|
||||
return CloudwalkResult.success(result);
|
||||
}
|
||||
private List<DeviceInfoResult> getDeviceList(List<DeviceImageStoreQueryResult> resultList, CloudwalkCallContext context) {
|
||||
List<DeviceInfoResult> list = Lists.newArrayListWithCapacity(resultList.size());
|
||||
try {
|
||||
List<String> deviceIds = (List<String>)resultList.stream().map(DeviceImageStoreQueryResult::getDeviceId).collect(Collectors.toList());
|
||||
CoreDeviceQueryParam param = new CoreDeviceQueryParam();
|
||||
param.setIds(deviceIds);
|
||||
param.setBusinessId(context.getCompany().getCompanyId());
|
||||
CloudwalkResult<List<AtomicDeviceGetResult>> deviceResult = this.atomicDeviceService.list(param, context);
|
||||
Map<String, String> deviceMap = new HashMap<>();
|
||||
if (deviceResult.isSuccess()) {
|
||||
deviceMap = (Map<String, String>)((List)deviceResult.getData()).stream().collect(Collectors.toMap(device -> device.getId(), device -> device.getDeviceCode()));
|
||||
}
|
||||
for (DeviceImageStoreQueryResult result : resultList) {
|
||||
DeviceInfoResult dr = new DeviceInfoResult();
|
||||
dr.setDeviceId(result.getDeviceId());
|
||||
dr.setDeviceCode(deviceMap.get(result.getDeviceId()));
|
||||
dr.setDeviceName(result.getDeviceName());
|
||||
dr.setIdentifyType(result.getIdentifyType());
|
||||
list.add(dr);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
this.logger.error("exception:{}", e.getMessage());
|
||||
}
|
||||
return list;
|
||||
}
|
||||
private IsImageStoreAssociated getAssociated(String objectId, long time, String userId, String imageStoreId, Integer action, Integer objectType) {
|
||||
IsImageStoreAssociated associated = new IsImageStoreAssociated();
|
||||
associated.setId(getPrimaryId());
|
||||
associated.setAssociatedAction(action);
|
||||
associated.setAssociatedObjectId(objectId);
|
||||
associated.setAssociatedObjectIdType(objectType);
|
||||
associated.setCreateTime(Long.valueOf(time));
|
||||
associated.setCreateUserId(userId);
|
||||
associated.setImageStoreId(imageStoreId);
|
||||
associated.setLastUpdateTime(Long.valueOf(time));
|
||||
associated.setLastUpdateUserId(userId);
|
||||
return associated;
|
||||
}
|
||||
private IsImageStoreAssociated getAssociated(AssociatedParam associatedParam, long time, String userId, String imageStoreId, Integer action, Integer objectType) {
|
||||
IsImageStoreAssociated associated = getAssociated(associatedParam.getObjectId(), time, userId, imageStoreId, action, objectType);
|
||||
associated.setExpiryBeginDate(associatedParam.getExpiryBeginDate());
|
||||
associated.setExpiryEndDate(associatedParam.getExpiryEndDate());
|
||||
associated.setValidDateCron(null);
|
||||
if (!CollectionUtils.isEmpty(associatedParam.getValidDateCron())) {
|
||||
associated.setValidDateCron(JSON.toJSONString(associatedParam.getValidDateCron()));
|
||||
}
|
||||
return associated;
|
||||
}
|
||||
private List<IsImageStoreAssociated> addBaseImageStore(BaseImageStoreParam param, CloudwalkCallContext context, String imageStoreId, String businessId) throws ServiceException {
|
||||
List<String> includePersonIds;
|
||||
long time = System.currentTimeMillis();
|
||||
if (CollectionUtils.isEmpty(param.getIncludePersons())) {
|
||||
includePersonIds = new ArrayList<>();
|
||||
} else {
|
||||
includePersonIds = (List<String>)param.getIncludePersons().stream().map(AssociatedParam::getObjectId).collect(Collectors.toList());
|
||||
}
|
||||
if (CollectionUtils.isEmpty(param.getIncludeOrganizations()) &&
|
||||
CollectionUtils.isEmpty(param.getIncludeLabels()) &&
|
||||
CollectionUtils.isEmpty(includePersonIds)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
List<IsImageStoreAssociated> imageStoreAssociatedList = new ArrayList<>();
|
||||
if (CpImageStoreMatchPatternEnum.getByCode(param.getMatchPattern()) != null) {
|
||||
imageStoreAssociatedList.add(getAssociated(param.getMatchPattern(), time, context.getUser().getCaller(), imageStoreId, (Integer)null,
|
||||
Integer.valueOf(4)));
|
||||
} else {
|
||||
imageStoreAssociatedList.add(getAssociated(CpImageStoreMatchPatternEnum.MERGE.getCode(), time, context.getUser().getCaller(), imageStoreId, (Integer)null,
|
||||
Integer.valueOf(4)));
|
||||
}
|
||||
AssociatedParam imageStoreAssociatedParam = new AssociatedParam();
|
||||
imageStoreAssociatedParam.setObjectId(imageStoreId);
|
||||
imageStoreAssociatedParam.setExpiryBeginDate(param.getExpiryBeginDate());
|
||||
imageStoreAssociatedParam.setExpiryEndDate(param.getExpiryEndDate());
|
||||
imageStoreAssociatedParam.setValidDateCron(param.getValidDateCron());
|
||||
imageStoreAssociatedList.add(getAssociated(imageStoreAssociatedParam, time, context.getUser().getCaller(), imageStoreId,
|
||||
Integer.valueOf(0), Integer.valueOf(5)));
|
||||
if (!CollectionUtils.isEmpty(param.getIncludeOrganizations())) {
|
||||
if (this.imgStoreOrganizationMapper.getOrgByIds(param.getIncludeOrganizations(), businessId).size() != param
|
||||
.getIncludeOrganizations().size()) {
|
||||
throw new ServiceException("53013513", getMessage("53013513"));
|
||||
}
|
||||
for (String objectId : param.getIncludeOrganizations()) {
|
||||
imageStoreAssociatedList.add(getAssociated(objectId, time, context.getUser().getCaller(), imageStoreId,
|
||||
Integer.valueOf(0), Integer.valueOf(1)));
|
||||
}
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(param.getIncludeLabels())) {
|
||||
if (this.imgStoreLabelMapper.getLabelByIds(param.getIncludeLabels(), businessId).size() != param
|
||||
.getIncludeLabels().size()) {
|
||||
throw new ServiceException("53013514", getMessage("53013514"));
|
||||
}
|
||||
for (String objectId : param.getIncludeLabels()) {
|
||||
imageStoreAssociatedList.add(getAssociated(objectId, time, context.getUser().getCaller(), imageStoreId,
|
||||
Integer.valueOf(0), Integer.valueOf(2)));
|
||||
}
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(includePersonIds)) {
|
||||
ImgStorePersonQueryDto dto = new ImgStorePersonQueryDto();
|
||||
dto.setIds(includePersonIds);
|
||||
dto.setBusinessId(businessId);
|
||||
dto.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
if (this.personMapper.gets(dto).size() != includePersonIds.size()) {
|
||||
throw new ServiceException("53013515", getMessage("53013515"));
|
||||
}
|
||||
for (AssociatedParam associatedParam : param.getIncludePersons()) {
|
||||
if (!param.getNullDateIsLongTerm().booleanValue() && (null == associatedParam
|
||||
.getExpiryBeginDate() || null == associatedParam.getExpiryEndDate())) {
|
||||
associatedParam.setExpiryBeginDate(imageStoreAssociatedParam.getExpiryBeginDate());
|
||||
associatedParam.setExpiryEndDate(imageStoreAssociatedParam.getExpiryEndDate());
|
||||
associatedParam.setValidDateCron(imageStoreAssociatedParam.getValidDateCron());
|
||||
}
|
||||
imageStoreAssociatedList.add(getAssociated(associatedParam, time, context.getUser().getCaller(), imageStoreId,
|
||||
Integer.valueOf(0), Integer.valueOf(3)));
|
||||
}
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(param.getExcludeLabels())) {
|
||||
if (this.imgStoreLabelMapper.getLabelByIds(param.getExcludeLabels(), businessId).size() != param
|
||||
.getExcludeLabels().size()) {
|
||||
throw new ServiceException("53013516", getMessage("53013516"));
|
||||
}
|
||||
for (String objectId : param.getExcludeLabels()) {
|
||||
imageStoreAssociatedList.add(getAssociated(objectId, time, context.getUser().getCaller(), imageStoreId,
|
||||
Integer.valueOf(1), Integer.valueOf(2)));
|
||||
}
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(param.getExcludePersons())) {
|
||||
ImgStorePersonQueryDto dto = new ImgStorePersonQueryDto();
|
||||
dto.setIds(param.getExcludePersons());
|
||||
dto.setBusinessId(businessId);
|
||||
dto.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
if (this.personMapper.gets(dto).size() != param.getExcludePersons().size()) {
|
||||
throw new ServiceException("53013517", getMessage("53013517"));
|
||||
}
|
||||
for (String objectId : param.getExcludePersons()) {
|
||||
imageStoreAssociatedList.add(getAssociated(objectId, time, context.getUser().getCaller(), imageStoreId,
|
||||
Integer.valueOf(1), Integer.valueOf(3)));
|
||||
}
|
||||
}
|
||||
return imageStoreAssociatedList;
|
||||
}
|
||||
private String getBusinessName(String businessId) throws ServiceException {
|
||||
GeneralQueryBusinessParam generalQueryBusinessParam = new GeneralQueryBusinessParam();
|
||||
generalQueryBusinessParam.setId(businessId);
|
||||
CloudwalkResult<List<AcBusinessDTO>> cloudwalkResult = this.acBusinessService.generalQuery(generalQueryBusinessParam);
|
||||
if (cloudwalkResult == null) {
|
||||
throw new ServiceException("53013535",
|
||||
getMessage("53013535"));
|
||||
}
|
||||
if (!cloudwalkResult.isSuccess()) {
|
||||
throw new ServiceException(cloudwalkResult.getCode(), cloudwalkResult.getMessage());
|
||||
}
|
||||
if (cloudwalkResult.getData() != null && ((List)cloudwalkResult.getData()).size() > 0) {
|
||||
return ((AcBusinessDTO)((List<AcBusinessDTO>)cloudwalkResult.getData()).get(0)).getName();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
private String getSourceApplicationName(String sourceApplicationId) throws ServiceException {
|
||||
if (StringUtils.isEmpty(sourceApplicationId)) {
|
||||
return null;
|
||||
}
|
||||
ApplicationBasicParam applicationBasicParam = new ApplicationBasicParam();
|
||||
applicationBasicParam.setIds(Arrays.asList(new String[] { sourceApplicationId }));
|
||||
CloudwalkResult<List<ApplicationResult>> cloudwalkResult = this.applicationService.gets(applicationBasicParam);
|
||||
if (cloudwalkResult == null) {
|
||||
throw new ServiceException("53013547",
|
||||
getMessage("53013547"));
|
||||
}
|
||||
if (!cloudwalkResult.isSuccess()) {
|
||||
throw new ServiceException(cloudwalkResult.getCode(), cloudwalkResult.getMessage());
|
||||
}
|
||||
if (cloudwalkResult.getData() != null && ((List)cloudwalkResult.getData()).size() > 0) {
|
||||
return ((ApplicationResult)((List<ApplicationResult>)cloudwalkResult.getData()).get(0)).getName();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
private void checkExistAndStatus(String iamgeStoreId) throws ServiceException {
|
||||
AgImageStoreQueryParam queryParam = new AgImageStoreQueryParam();
|
||||
queryParam.setId(iamgeStoreId);
|
||||
CloudwalkResult<List<AgImageStoreResult>> query = this.agImageStoreService.query(queryParam);
|
||||
if (!query.isSuccess()) {
|
||||
throw new ServiceException(query.getCode(), query.getMessage());
|
||||
}
|
||||
if (CollectionUtils.isEmpty((Collection)query.getData())) {
|
||||
throw new ServiceException("53013502",
|
||||
getMessage("53013502"));
|
||||
}
|
||||
if (SyncStatusEnum.SYNC_ING.getCode().equals(((AgImageStoreResult)((List<AgImageStoreResult>)query.getData()).get(0)).getStatus())) {
|
||||
throw new ServiceException("53013512",
|
||||
getMessage("53013512"));
|
||||
}
|
||||
}
|
||||
private Map<String, String> getBusinessNameMap() throws ServiceException {
|
||||
CloudwalkResult<List<AcBusinessDTO>> listCloudwalkResult = this.acBusinessService.generalQuery(new GeneralQueryBusinessParam());
|
||||
if (!listCloudwalkResult.isSuccess()) {
|
||||
throw new ServiceException(listCloudwalkResult.getCode(), listCloudwalkResult.getMessage());
|
||||
}
|
||||
if (CollectionUtils.isEmpty((Collection)listCloudwalkResult.getData())) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
return Collections3.extractToMap((Collection)listCloudwalkResult.getData(), "id", "name");
|
||||
}
|
||||
private Map<String, String> getSourceApplicationNameMap(String businessId) throws ServiceException {
|
||||
ApplicationQueryParam param = new ApplicationQueryParam();
|
||||
param.setBusinessId(businessId);
|
||||
param.setStatus(CommonStatusEnum.ENABLE.getCode());
|
||||
CloudwalkResult<List<ApplicationResult>> listCloudwalkResult = this.applicationService.query(param);
|
||||
if (!listCloudwalkResult.isSuccess()) {
|
||||
throw new ServiceException(listCloudwalkResult.getCode(), listCloudwalkResult.getMessage());
|
||||
}
|
||||
if (CollectionUtils.isEmpty((Collection)listCloudwalkResult.getData())) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
return Collections3.extractToMap((Collection)listCloudwalkResult.getData(), "id", "name");
|
||||
}
|
||||
private void getAssociated(ImageStoreDetailResult result) {
|
||||
GetsImageStoreAssociatedDTO get = new GetsImageStoreAssociatedDTO();
|
||||
get.setImageStoreId(result.getId());
|
||||
List<IsImageStoreAssociated> associateds = this.isImageStoreAssociatedMapper.gets(get);
|
||||
String matchPattern = null;
|
||||
List<String> includeLabelIds = new ArrayList<>();
|
||||
List<String> includeOrganizationIds = new ArrayList<>();
|
||||
List<String> includePersonIds = new ArrayList<>();
|
||||
Map<String, AssociatedResult> includePersonMap = new HashMap<>();
|
||||
List<String> excludeLabelIds = new ArrayList<>();
|
||||
List<String> excludePersonIds = new ArrayList<>();
|
||||
String businessId = result.getBusinessId();
|
||||
for (IsImageStoreAssociated associated : associateds) {
|
||||
if (4 == associated.getAssociatedObjectIdType().intValue()) {
|
||||
matchPattern = associated.getAssociatedObjectId(); continue;
|
||||
}
|
||||
if (0 == associated.getAssociatedAction().intValue()) {
|
||||
if (1 == associated.getAssociatedObjectIdType().intValue()) {
|
||||
includeOrganizationIds.add(associated.getAssociatedObjectId()); continue;
|
||||
} if (2 == associated.getAssociatedObjectIdType().intValue()) {
|
||||
includeLabelIds.add(associated.getAssociatedObjectId()); continue;
|
||||
} if (3 == associated.getAssociatedObjectIdType().intValue()) {
|
||||
includePersonIds.add(associated.getAssociatedObjectId());
|
||||
AssociatedResult associatedResult = new AssociatedResult();
|
||||
BeanCopyUtils.copyProperties(associated, associatedResult);
|
||||
associatedResult.setObjectId(associated.getAssociatedObjectId());
|
||||
includePersonMap.put(associated.getAssociatedObjectId(), associatedResult); continue;
|
||||
} if (5 == associated.getAssociatedObjectIdType().intValue()) {
|
||||
result.setExpiryBeginDate(associated.getExpiryBeginDate());
|
||||
result.setExpiryEndDate(associated.getExpiryEndDate());
|
||||
result.setValidDateCron(JsonUtils.toStrList(associated.getValidDateCron()));
|
||||
} continue;
|
||||
} if (1 == associated.getAssociatedAction().intValue()) {
|
||||
if (2 == associated.getAssociatedObjectIdType().intValue()) {
|
||||
excludeLabelIds.add(associated.getAssociatedObjectId()); continue;
|
||||
} if (3 == associated.getAssociatedObjectIdType().intValue()) {
|
||||
excludePersonIds.add(associated.getAssociatedObjectId());
|
||||
}
|
||||
}
|
||||
}
|
||||
result.setMatchPattern(matchPattern);
|
||||
if (!CollectionUtils.isEmpty(includeLabelIds)) {
|
||||
result.setIncludeLabels(BeanCopyUtils.copy(this.imgStoreLabelMapper.getLabelByIds(includeLabelIds, businessId), LabelResult.class));
|
||||
} else {
|
||||
result.setIncludeLabels(new ArrayList());
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(includeOrganizationIds)) {
|
||||
result.setIncludeOrganizations(BeanCopyUtils.copy(this.imgStoreOrganizationMapper.getOrgByIds(includeOrganizationIds, businessId), OrganizationResult.class));
|
||||
} else {
|
||||
result.setIncludeOrganizations(new ArrayList());
|
||||
}
|
||||
ImgStorePersonQueryDto getDTO = new ImgStorePersonQueryDto();
|
||||
if (!CollectionUtils.isEmpty(includePersonIds)) {
|
||||
getDTO.setIds(includePersonIds);
|
||||
getDTO.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
List<ImgStorePerson> personList = this.personMapper.gets(getDTO);
|
||||
List<ImgStorePersonResult> includePersons = new ArrayList<>();
|
||||
personList.forEach(imgStorePerson -> {
|
||||
ImgStorePersonResult imgStorePersonResult = new ImgStorePersonResult();
|
||||
BeanCopyUtils.copyProperties(imgStorePerson, imgStorePersonResult);
|
||||
AssociatedResult associatedResult = (AssociatedResult)includePersonMap.get(imgStorePerson.getId());
|
||||
BeanCopyUtils.copyProperties(associatedResult, imgStorePersonResult);
|
||||
imgStorePersonResult.setValidDateCron(JsonUtils.toStrList(associatedResult.getValidDateCron()));
|
||||
includePersons.add(imgStorePersonResult);
|
||||
});
|
||||
result.setIncludePersons(includePersons);
|
||||
} else {
|
||||
result.setIncludePersons(new ArrayList());
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(excludeLabelIds)) {
|
||||
result.setExcludeLabels(BeanCopyUtils.copy(this.imgStoreLabelMapper.getLabelByIds(excludeLabelIds, businessId), LabelResult.class));
|
||||
} else {
|
||||
result.setExcludeLabels(new ArrayList());
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(excludePersonIds)) {
|
||||
getDTO.setIds(excludePersonIds);
|
||||
getDTO.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
result.setExcludePersons(BeanCopyUtils.copy(this.personMapper.gets(getDTO), ImgStorePersonResult.class));
|
||||
} else {
|
||||
result.setExcludePersons(new ArrayList());
|
||||
}
|
||||
}
|
||||
private boolean handleQueryParam(QueryImageStoreParam queryParam) {
|
||||
if (StringUtils.isNotBlank(queryParam.getOrgId()) ||
|
||||
!CollectionUtils.isEmpty(queryParam.getOrgIds())) {
|
||||
List<OrganizationImageStore> orgImageStoreList = this.organizationImageStoreMapper.query((OrganizationImageStoreQueryDTO)BeanCopyUtils.copyProperties(queryParam, OrganizationImageStoreQueryDTO.class));
|
||||
GetsImageStoreAssociatedDTO orgParam = new GetsImageStoreAssociatedDTO();
|
||||
orgParam.setAssociatedObjectIdType(Integer.valueOf(1));
|
||||
List<String> orgIds = new ArrayList<>(500);
|
||||
if (StringUtils.isNotBlank(queryParam.getOrgId())) {
|
||||
orgIds.add(queryParam.getOrgId());
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(queryParam.getOrgIds())) {
|
||||
orgIds.addAll(queryParam.getOrgIds());
|
||||
}
|
||||
orgParam.setAssociatedObjectIds(orgIds);
|
||||
List<IsImageStoreAssociated> orgResultList = this.isImageStoreAssociatedMapper.gets(orgParam);
|
||||
if (CollectionUtils.isEmpty(orgImageStoreList) && CollectionUtils.isEmpty(orgResultList)) {
|
||||
return true;
|
||||
}
|
||||
List<String> imageStoreIds = Collections3.extractToList(orgImageStoreList, "imageStoreId");
|
||||
imageStoreIds.addAll(Collections3.extractToList(orgResultList, "imageStoreId"));
|
||||
if (StringUtils.isNotBlank(queryParam.getId())) {
|
||||
if (!imageStoreIds.contains(queryParam.getId())) {
|
||||
return true;
|
||||
}
|
||||
} else if (!CollectionUtils.isEmpty(queryParam.getIds())) {
|
||||
imageStoreIds.retainAll(queryParam.getIds());
|
||||
}
|
||||
if (CollectionUtils.isEmpty(imageStoreIds)) {
|
||||
return true;
|
||||
}
|
||||
queryParam.setIds(imageStoreIds);
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(queryParam.getPersonIds())) {
|
||||
QueryGroupPersonDTO queryGroupPersonDTO = (QueryGroupPersonDTO)BeanCopyUtils.copyProperties(queryParam, QueryGroupPersonDTO.class);
|
||||
queryGroupPersonDTO.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
List<GroupPersonRef> queryResult = this.groupPersonRefMapper.query(queryGroupPersonDTO);
|
||||
if (CollectionUtils.isEmpty(queryResult)) {
|
||||
return true;
|
||||
}
|
||||
List<String> imageStoreIds = Collections3.extractToList(queryResult, "imageStoreId");
|
||||
if (StringUtils.isNotBlank(queryParam.getId())) {
|
||||
if (!imageStoreIds.contains(queryParam.getId())) {
|
||||
return true;
|
||||
}
|
||||
} else if (!CollectionUtils.isEmpty(queryParam.getIds())) {
|
||||
imageStoreIds.retainAll(queryParam.getIds());
|
||||
}
|
||||
if (CollectionUtils.isEmpty(imageStoreIds)) {
|
||||
return true;
|
||||
}
|
||||
queryParam.setIds(imageStoreIds);
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(queryParam.getLabelIds())) {
|
||||
GetsImageStoreAssociatedDTO labelParam = new GetsImageStoreAssociatedDTO();
|
||||
labelParam.setAssociatedObjectIdType(Integer.valueOf(2));
|
||||
labelParam.setAssociatedObjectIds(queryParam.getLabelIds());
|
||||
List<IsImageStoreAssociated> labelResultList = this.isImageStoreAssociatedMapper.gets(labelParam);
|
||||
if (CollectionUtils.isEmpty(labelResultList)) {
|
||||
return true;
|
||||
}
|
||||
List<String> imageStoreIds = Collections3.extractToList(labelResultList, "imageStoreId");
|
||||
if (StringUtils.isNotBlank(queryParam.getId())) {
|
||||
if (!imageStoreIds.contains(queryParam.getId())) {
|
||||
return true;
|
||||
}
|
||||
} else if (!CollectionUtils.isEmpty(queryParam.getIds())) {
|
||||
imageStoreIds.retainAll(queryParam.getIds());
|
||||
}
|
||||
if (CollectionUtils.isEmpty(imageStoreIds)) {
|
||||
return true;
|
||||
}
|
||||
queryParam.setIds(imageStoreIds);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
private List<ImageStoreResult> packageImageStoreResult(Collection<AgImageStoreResult> agDatas, String businessId) throws ServiceException {
|
||||
if (CollectionUtils.isEmpty(agDatas)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
List<String> imageIds = (List<String>)agDatas.stream().map(AgImageStoreResult::getId).collect(Collectors.toList());
|
||||
long startTime = System.currentTimeMillis();
|
||||
List<ImageStoreCountDTO> countByImageStoreIds = Lists.newArrayListWithCapacity(imageIds.size());
|
||||
List<List<String>> partition = Lists.partition(imageIds, this.searchSize);
|
||||
partition.stream().forEach(p -> {
|
||||
List<ImageStoreCountDTO> list = this.groupPersonRefMapper.getCountByImageStoreIds(p);
|
||||
if (!CollectionUtils.isEmpty(list)) {
|
||||
countByImageStoreIds.addAll(list);
|
||||
}
|
||||
});
|
||||
long endTime = System.currentTimeMillis();
|
||||
this.logger.info("图库分页查询耗时:[{}],searchSize:[{}]", Long.valueOf(endTime - startTime), Integer.valueOf(this.searchSize));
|
||||
Map<String, Integer> countMap = (Map<String, Integer>)countByImageStoreIds.stream().filter(imageStoreCountDTO -> (null != imageStoreCountDTO)).collect(Collectors.toMap(ImageStoreCountDTO::getId, ImageStoreCountDTO::getCount, (k1, k2) -> k1));
|
||||
Map<String, String> businessNameMap = getBusinessNameMap();
|
||||
Map<String, String> sourceApplicationNameMap = getSourceApplicationNameMap(businessId);
|
||||
List<ImageStoreResult> resultList = new ArrayList<>(agDatas.size());
|
||||
for (AgImageStoreResult agData : agDatas) {
|
||||
ImageStoreResult temp = (ImageStoreResult)BeanCopyUtils.copyProperties(agData, ImageStoreResult.class);
|
||||
temp.setBusinessName(businessNameMap.get(temp.getBusinessId()));
|
||||
temp.setSourceApplicationName(sourceApplicationNameMap.get(temp.getSourceApplicationId()));
|
||||
temp.setPersonNum(countMap.containsKey(agData.getId()) ? countMap.get(agData.getId()) : Integer.valueOf(0));
|
||||
getAssociated((ImageStoreDetailResult)temp);
|
||||
resultList.add(temp);
|
||||
}
|
||||
return resultList;
|
||||
}
|
||||
private List<PageImageStoreResult> packageCpResult(Collection<AgImageStoreResult> agDatas, String businessId) throws ServiceException {
|
||||
if (CollectionUtils.isEmpty(agDatas)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
List<String> imageIds = (List<String>)agDatas.stream().map(AgImageStoreResult::getId).collect(Collectors.toList());
|
||||
long startTime = System.currentTimeMillis();
|
||||
List<ImageStoreCountDTO> countByImageStoreIds = Lists.newArrayListWithCapacity(imageIds.size());
|
||||
List<List<String>> partition = Lists.partition(imageIds, this.searchSize);
|
||||
partition.stream().forEach(p -> {
|
||||
List<ImageStoreCountDTO> list = this.groupPersonRefMapper.getCountByImageStoreIds(p);
|
||||
if (!CollectionUtils.isEmpty(list)) {
|
||||
countByImageStoreIds.addAll(list);
|
||||
}
|
||||
});
|
||||
long endTime = System.currentTimeMillis();
|
||||
this.logger.info("图库分页查询耗时:[{}],searchSize:[{}]", Long.valueOf(endTime - startTime), Integer.valueOf(this.searchSize));
|
||||
Map<String, Integer> countMap = (Map<String, Integer>)countByImageStoreIds.stream().filter(imageStoreCountDTO -> (null != imageStoreCountDTO)).collect(Collectors.toMap(ImageStoreCountDTO::getId, ImageStoreCountDTO::getCount, (k1, k2) -> k1));
|
||||
Map<String, String> businessNameMap = getBusinessNameMap();
|
||||
Map<String, String> sourceApplicationNameMap = getSourceApplicationNameMap(businessId);
|
||||
List<PageImageStoreResult> resultList = new ArrayList<>(agDatas.size());
|
||||
for (AgImageStoreResult agData : agDatas) {
|
||||
PageImageStoreResult temp = (PageImageStoreResult)BeanCopyUtils.copyProperties(agData, PageImageStoreResult.class);
|
||||
temp.setBusinessName(businessNameMap.get(temp.getBusinessId()));
|
||||
temp.setSourceApplicationName(sourceApplicationNameMap.get(temp.getSourceApplicationId()));
|
||||
temp.setPersonNum(countMap.containsKey(agData.getId()) ? countMap.get(agData.getId()) : Integer.valueOf(0));
|
||||
resultList.add(temp);
|
||||
}
|
||||
return resultList;
|
||||
}
|
||||
private Integer getPersonNum(String id) {
|
||||
List<ImageStoreCountDTO> countByImageStoreIds = this.groupPersonRefMapper.getCountByImageStoreIds(Lists.newArrayList(id ));
|
||||
if (CollectionUtils.isEmpty(countByImageStoreIds) || countByImageStoreIds.get(0) == null) {
|
||||
return Integer.valueOf(0);
|
||||
}
|
||||
return ((ImageStoreCountDTO)countByImageStoreIds.get(0)).getCount();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/CpImageStoreServiceImpl.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+51
-47
@@ -1,63 +1,67 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.aggregate.device.param.DeviceImageStoreSyncParam;
|
||||
import cn.cloudwalk.client.aggregate.device.result.DeviceImageStoreSyncResult;
|
||||
import cn.cloudwalk.client.aggregate.device.service.AggDeviceImageStoreService;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkCallContext;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import javax.annotation.Resource;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class CpImageStoreSyncManager {
|
||||
private Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
@Resource
|
||||
private AggDeviceImageStoreService aggDeviceImageStoreService;
|
||||
|
||||
public void sendChangeToDevice(Set<String> changeGroupIds, boolean validStatusChange) {
|
||||
for (String changeGroupId : changeGroupIds) {
|
||||
DeviceImageStoreSyncParam addParam = new DeviceImageStoreSyncParam();
|
||||
addParam.setImageStoreId(changeGroupId);
|
||||
if (validStatusChange) {
|
||||
addParam.setSupportPersonValidDate(Integer.valueOf(1));
|
||||
} else {
|
||||
addParam.setSupportPersonValidDate(Integer.valueOf(0));
|
||||
}
|
||||
try {
|
||||
CloudwalkResult addSyncResult = this.aggDeviceImageStoreService.sync(addParam, new CloudwalkCallContext());
|
||||
if (addSyncResult.isSuccess()) continue;
|
||||
String message = JSON.toJSONString((Object)addSyncResult);
|
||||
this.logger.warn("addImageStoreSync error,result:[{}]", (Object)message);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.warn("addImageStoreSync exception,imageStoreId:[{}]", (Object)changeGroupId, (Object)e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void sendChangeToDevice(String deviceId, Set<String> changeGroupIds, boolean validStatusChange) {
|
||||
for (String changeGroupId : changeGroupIds) {
|
||||
DeviceImageStoreSyncParam addParam = new DeviceImageStoreSyncParam();
|
||||
addParam.setImageStoreId(changeGroupId);
|
||||
addParam.setDeviceId(deviceId);
|
||||
if (validStatusChange) {
|
||||
addParam.setSupportPersonValidDate(Integer.valueOf(1));
|
||||
} else {
|
||||
addParam.setSupportPersonValidDate(Integer.valueOf(0));
|
||||
}
|
||||
try {
|
||||
CloudwalkResult addSyncResult = this.aggDeviceImageStoreService.sync(addParam, new CloudwalkCallContext());
|
||||
if (addSyncResult.isSuccess()) continue;
|
||||
String message = JSON.toJSONString((Object)addSyncResult);
|
||||
this.logger.warn("addImageStoreSync error,result:[{}]", (Object)message);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.warn("addImageStoreSync exception,imageStoreId:[{}]", (Object)changeGroupId, (Object)e);
|
||||
}
|
||||
}
|
||||
}
|
||||
private Logger logger = LoggerFactory.getLogger(getClass());
|
||||
@Resource
|
||||
private AggDeviceImageStoreService aggDeviceImageStoreService;
|
||||
public void sendChangeToDevice(Set<String> changeGroupIds, boolean validStatusChange) {
|
||||
for (String changeGroupId : changeGroupIds) {
|
||||
DeviceImageStoreSyncParam addParam = new DeviceImageStoreSyncParam();
|
||||
addParam.setImageStoreId(changeGroupId);
|
||||
if (validStatusChange) {
|
||||
addParam.setSupportPersonValidDate(Integer.valueOf(1));
|
||||
} else {
|
||||
addParam.setSupportPersonValidDate(Integer.valueOf(0));
|
||||
}
|
||||
try {
|
||||
CloudwalkResult<List<DeviceImageStoreSyncResult>> addSyncResult = this.aggDeviceImageStoreService.sync(addParam, new CloudwalkCallContext());
|
||||
if (!addSyncResult.isSuccess()) {
|
||||
String message = JSON.toJSONString(addSyncResult);
|
||||
this.logger.warn("addImageStoreSync error,result:[{}]", message);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
this.logger.warn("addImageStoreSync exception,imageStoreId:[{}]", changeGroupId, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
public void sendChangeToDevice(String deviceId, Set<String> changeGroupIds, boolean validStatusChange) {
|
||||
for (String changeGroupId : changeGroupIds) {
|
||||
DeviceImageStoreSyncParam addParam = new DeviceImageStoreSyncParam();
|
||||
addParam.setImageStoreId(changeGroupId);
|
||||
addParam.setDeviceId(deviceId);
|
||||
if (validStatusChange) {
|
||||
addParam.setSupportPersonValidDate(Integer.valueOf(1));
|
||||
} else {
|
||||
addParam.setSupportPersonValidDate(Integer.valueOf(0));
|
||||
}
|
||||
try {
|
||||
CloudwalkResult<List<DeviceImageStoreSyncResult>> addSyncResult = this.aggDeviceImageStoreService.sync(addParam, new CloudwalkCallContext());
|
||||
if (!addSyncResult.isSuccess()) {
|
||||
String message = JSON.toJSONString(addSyncResult);
|
||||
this.logger.warn("addImageStoreSync error,result:[{}]", message);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
this.logger.warn("addImageStoreSync exception,imageStoreId:[{}]", changeGroupId, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/CpImageStoreSyncManager.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+477
-482
@@ -49,6 +49,7 @@ import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -56,490 +57,484 @@ import javax.annotation.Resource;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
@Service
|
||||
public class CpImageStoreToolServiceImpl
|
||||
extends AbstractImagStoreService
|
||||
implements CpImageStoreToolService {
|
||||
@Resource
|
||||
private ImgStorePersonMapper personMapper;
|
||||
@Resource
|
||||
private PineappleEngineClient pineappleClient;
|
||||
@Resource
|
||||
private FileStorageManager fileStorageManager;
|
||||
@Resource
|
||||
private GroupPersonRefMapper groupPersonRefMapper;
|
||||
|
||||
public CloudwalkResult<List<CpFeatureQueryResult>> searchMultiple(CpFeatureQueryParam queryParam) throws ServiceException {
|
||||
String groupId;
|
||||
if (this.logger.isDebugEnabled()) {
|
||||
this.logger.debug("开始查询所有图库topN,参数:{}", (Object)JSON.toJSONString((Object)queryParam));
|
||||
}
|
||||
if (StringUtils.isEmpty((Object)(groupId = queryParam.getImageStoreId())) && !CollectionUtils.isEmpty((Collection)queryParam.getImageStoreIds())) {
|
||||
groupId = String.join((CharSequence)",", queryParam.getImageStoreIds());
|
||||
}
|
||||
if (StringUtils.isEmpty((Object)groupId)) {
|
||||
throw new ServiceException("53060438", this.getMessage("53060438"));
|
||||
}
|
||||
String feature = queryParam.getFeature();
|
||||
if (StringUtils.isEmpty((Object)feature) && !StringUtils.isEmpty((Object)queryParam.getImageBase64())) {
|
||||
AgFeatureExtractParam extractParam = new AgFeatureExtractParam();
|
||||
extractParam.setImageBase64(queryParam.getImageBase64());
|
||||
CloudwalkResult<AgFeatureExtractResult> extractResult = this.extractFeature(extractParam);
|
||||
if (extractResult.isSuccess()) {
|
||||
feature = ((AgFeatureExtractResult)extractResult.getData()).getFeature();
|
||||
}
|
||||
}
|
||||
if (StringUtils.isEmpty((Object)feature)) {
|
||||
throw new ServiceException("53060436", this.getMessage("53060436"));
|
||||
}
|
||||
SearchFaceMutipleParam searchMutipleParam = SearchFaceMutipleParam.builder().groupId(groupId).topN(queryParam.getTopN()).feature(feature).mode("all").bTime(queryParam.getBeginTime()).eTime(queryParam.getEndTime()).build();
|
||||
if (this.logger.isDebugEnabled()) {
|
||||
this.logger.debug("查询所有图库topN,引擎多库检索参数:{}", (Object)JSON.toJSONString((Object)searchMutipleParam));
|
||||
}
|
||||
SearchFaceMutipleResult searchMutipleResult = this.pineappleClient.searchMultiple(searchMutipleParam);
|
||||
if (this.logger.isDebugEnabled()) {
|
||||
this.logger.debug("查询所有图库topN,引擎多库检索结果:{}", (Object)JSON.toJSONString((Object)searchMutipleResult));
|
||||
}
|
||||
if (searchMutipleResult.getResult() != 0) {
|
||||
throw new ServiceException(searchMutipleResult.getResult().toString(), searchMutipleResult.getInfo());
|
||||
}
|
||||
List faceDataList = searchMutipleResult.getFaces();
|
||||
if (CollectionUtils.isEmpty((Collection)faceDataList)) {
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
List<String> userIdList = faceDataList.stream().map(SearchFaceMutipleResult.FaceData::getUserId).collect(Collectors.toList());
|
||||
Map<String, ImgStorePerson> personMap = new HashMap<String, ImgStorePerson>();
|
||||
if (!CollectionUtils.isEmpty(userIdList)) {
|
||||
personMap = this.getPersonMap(userIdList);
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
public CloudwalkResult<Map<String, List<CpFeatureQueryResult>>> searchMultipleEveryGroup(CpFeatureQueryParam queryParam) throws ServiceException {
|
||||
String groupId;
|
||||
if (this.logger.isDebugEnabled()) {
|
||||
this.logger.debug("开始查询每个图库topN,参数:{}", (Object)JSON.toJSONString((Object)queryParam));
|
||||
}
|
||||
if (StringUtils.isEmpty((Object)(groupId = queryParam.getImageStoreId()))) {
|
||||
groupId = String.join((CharSequence)",", queryParam.getImageStoreIds());
|
||||
}
|
||||
if (StringUtils.isEmpty((Object)groupId)) {
|
||||
throw new ServiceException("53060438", this.getMessage("53060438"));
|
||||
}
|
||||
String feature = queryParam.getFeature();
|
||||
if (StringUtils.isEmpty((Object)feature) && !StringUtils.isEmpty((Object)queryParam.getImageBase64())) {
|
||||
AgFeatureExtractParam extractParam = new AgFeatureExtractParam();
|
||||
extractParam.setImageBase64(queryParam.getImageBase64());
|
||||
CloudwalkResult<AgFeatureExtractResult> extractResult = this.extractFeature(extractParam);
|
||||
if (extractResult.isSuccess()) {
|
||||
feature = ((AgFeatureExtractResult)extractResult.getData()).getFeature();
|
||||
}
|
||||
}
|
||||
if (StringUtils.isEmpty((Object)feature)) {
|
||||
throw new ServiceException("53060436", this.getMessage("53060436"));
|
||||
}
|
||||
SearchFaceMutipleParam searchMutipleParam = SearchFaceMutipleParam.builder().groupId(groupId).topN(queryParam.getTopN()).feature(feature).mode("perGroup").bTime(queryParam.getBeginTime()).eTime(queryParam.getEndTime()).build();
|
||||
this.logger.info("查询每个图库topN,引擎多库检索参数:{}", (Object)JSON.toJSONString((Object)searchMutipleParam));
|
||||
SearchFaceMutiplePerGroupResult searchMutiplePerGroupResult = this.pineappleClient.searchMultipleEveryGroup(searchMutipleParam);
|
||||
this.logger.info("查询每个图库topN,引擎多库检索结果:{}", (Object)JSON.toJSONString((Object)searchMutiplePerGroupResult));
|
||||
if (searchMutiplePerGroupResult.getResult() != 0) {
|
||||
throw new ServiceException(searchMutiplePerGroupResult.getResult().toString(), searchMutiplePerGroupResult.getInfo());
|
||||
}
|
||||
List faceGroupDataList = searchMutiplePerGroupResult.getFaces();
|
||||
if (CollectionUtils.isEmpty((Collection)faceGroupDataList)) {
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
HashSet<String> imageIdSet = new HashSet<String>();
|
||||
faceGroupDataList.stream().forEach(faceGroupData -> {
|
||||
if (!CollectionUtils.isEmpty((Collection)faceGroupData.getArray())) {
|
||||
imageIdSet.addAll(faceGroupData.getArray().stream().map(SearchFaceMutiplePerGroupResult.FaceData::getUserId).collect(Collectors.toList()));
|
||||
}
|
||||
});
|
||||
HashMap<String, ImgStorePerson> personMap = new HashMap();
|
||||
if (!imageIdSet.isEmpty()) {
|
||||
personMap = this.getPersonMap(imageIdSet);
|
||||
}
|
||||
HashMap<String, List<CpFeatureQueryResult>> resultMap = new HashMap<String, List<CpFeatureQueryResult>>(faceGroupDataList.size());
|
||||
for (SearchFaceMutiplePerGroupResult.FaceGroupData faceGroupData2 : faceGroupDataList) {
|
||||
resultMap.put(faceGroupData2.getGroupId(), this.transFaceGroupResult(faceGroupData2, personMap));
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
public CloudwalkResult<AgFeatureExtractResult> extractFeature(AgFeatureExtractParam extractParam) throws ServiceException {
|
||||
this.logger.info("开始特征提取,参数:{}", (Object)JSON.toJSONString((Object)extractParam));
|
||||
String img = extractParam.getImageBase64();
|
||||
if (StringUtils.isEmpty((Object)img) && !StringUtils.isEmpty((Object)extractParam.getImageUrl())) {
|
||||
try {
|
||||
byte[] bytes = this.fileStorageManager.fileDownload(extractParam.getImageUrl());
|
||||
img = ImageUtil.encodeByte2Base64(bytes);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("下载图片异常:{}", (Object)e.getMessage());
|
||||
throw new ServiceException("80014016", this.getMessage("80014016"));
|
||||
}
|
||||
}
|
||||
if (StringUtils.isEmpty((Object)img)) {
|
||||
throw new ServiceException("53060434", this.getMessage("53060434"));
|
||||
}
|
||||
ExtractFeatureParam extractFeatureParam = ExtractFeatureParam.builder().img(img).modelVersion(extractParam.getEngineVersionModelId()).build();
|
||||
ExtractFeatureResult extractFeatureResult = null;
|
||||
try {
|
||||
CompletableFuture<ExtractFeatureResult> future = CompletableFuture.supplyAsync(() -> this.pineappleClient.extractFeature(extractFeatureParam));
|
||||
extractFeatureResult = future.get();
|
||||
}
|
||||
catch (ExecutionException e) {
|
||||
this.logger.error("引擎提取特征异常:{}", (Object)e.getMessage());
|
||||
throw new ServiceException("53060435", this.getMessage("53060435"));
|
||||
}
|
||||
catch (InterruptedException e) {
|
||||
this.logger.error("引擎提取特征异常:{}", (Object)e.getMessage());
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
if (null == extractFeatureResult) {
|
||||
throw new ServiceException("53060436", this.getMessage("53060436"));
|
||||
}
|
||||
if (extractFeatureResult.getResult() != 0) {
|
||||
throw new ServiceException(extractFeatureResult.getResult().toString(), extractFeatureResult.getInfo());
|
||||
}
|
||||
List<String> qualityScores = Arrays.asList(extractFeatureResult.getQualityScores().split(","));
|
||||
List quality = qualityScores.stream().map(qualityScore -> Double.valueOf(qualityScore)).collect(Collectors.toList());
|
||||
AgFeatureExtractResult result = new AgFeatureExtractResult();
|
||||
result.setFeature(extractFeatureResult.getFeature());
|
||||
result.setQuality(quality);
|
||||
result.setScore((Double)quality.get(0));
|
||||
result.setAge(Integer.valueOf(new BigDecimal(qualityScores.get(10)).setScale(0, 4).intValue()));
|
||||
result.setGender(Integer.valueOf(new BigDecimal(qualityScores.get(11)).setScale(0).intValue()));
|
||||
this.logger.info("结束特征提取,结果:{}", (Object)JSON.toJSONString((Object)result));
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
public CloudwalkResult<FaceDetectResult> faceDetect(CpFaceDetectParam faceDetectParam) throws ServiceException {
|
||||
this.logger.info("开始人脸检测,参数:{}", (Object)JSON.toJSONString((Object)faceDetectParam));
|
||||
String img = faceDetectParam.getImageBase64();
|
||||
if (StringUtils.isEmpty((Object)img) && !StringUtils.isEmpty((Object)faceDetectParam.getImageUrl())) {
|
||||
try {
|
||||
byte[] bytes = this.fileStorageManager.fileDownload(faceDetectParam.getImageUrl());
|
||||
img = ImageUtil.encodeByte2Base64(bytes);
|
||||
}
|
||||
catch (Exception e) {
|
||||
throw new ServiceException("80014016", this.getMessage("80014016"));
|
||||
}
|
||||
}
|
||||
if (StringUtils.isEmpty((Object)img)) {
|
||||
throw new ServiceException("53060434", this.getMessage("53060434"));
|
||||
}
|
||||
FaceDetectParam param = FaceDetectParam.builder().img(img).build();
|
||||
FaceDetectResult faceDetectResult = null;
|
||||
try {
|
||||
CompletableFuture<FaceDetectResult> future = CompletableFuture.supplyAsync(() -> this.pineappleClient.faceDetect(param));
|
||||
faceDetectResult = future.get();
|
||||
}
|
||||
catch (ExecutionException e) {
|
||||
this.logger.error("引擎人脸检测异常:{}", (Object)e.getMessage());
|
||||
throw new ServiceException("53060439", this.getMessage("53060439"));
|
||||
}
|
||||
catch (InterruptedException e) {
|
||||
this.logger.error("引擎人脸检测异常:{}", (Object)e.getMessage());
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
if (null == faceDetectResult) {
|
||||
throw new ServiceException("53060440", this.getMessage("53060440"));
|
||||
}
|
||||
if (faceDetectResult.getResult() != 0) {
|
||||
throw new ServiceException(faceDetectResult.getResult().toString(), faceDetectResult.getInfo());
|
||||
}
|
||||
this.logger.info("结束人脸检测,结果:{}", (Object)JSON.toJSONString((Object)faceDetectResult));
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
public CloudwalkResult<BatchHandleFaceResult> batchAddFace(CpBatchHandleFaceParam param) throws ServiceException {
|
||||
this.logger.info("开始批量添加人脸,参数:{}", (Object)JSON.toJSONString((Object)param));
|
||||
this.checkBatchHandleFaceParam(param);
|
||||
ArrayList items = Lists.newArrayListWithCapacity((int)param.getImageIds().size());
|
||||
BatchAddFaceParam batchAddFaceParam = BatchAddFaceParam.builder().items((List)items).build();
|
||||
Map<String, ImgStorePerson> personMap = this.getPersonMap(param.getImageIds());
|
||||
AgFeatureExtractParam extractParam = null;
|
||||
for (String imageId : param.getImageIds()) {
|
||||
try {
|
||||
extractParam = new AgFeatureExtractParam();
|
||||
extractParam.setImageUrl(personMap.get(imageId).getComparePicture());
|
||||
CloudwalkResult<AgFeatureExtractResult> extractResult = this.extractFeature(extractParam);
|
||||
if (!extractResult.isSuccess()) continue;
|
||||
BatchAddFaceParam.Item item = new BatchAddFaceParam.Item(batchAddFaceParam);
|
||||
item.setGroupId(param.getImageStoreId());
|
||||
item.setUserId(imageId);
|
||||
item.setFeature(((AgFeatureExtractResult)extractResult.getData()).getFeature());
|
||||
List qualityScoreList = ((AgFeatureExtractResult)extractResult.getData()).getQuality().stream().map(x -> x + "").collect(Collectors.toList());
|
||||
item.setQualityScore(String.join((CharSequence)",", qualityScoreList));
|
||||
items.add(item);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("提取特征异常:{}", (Object)e.getMessage());
|
||||
}
|
||||
}
|
||||
batchAddFaceParam.setItems((List)items);
|
||||
BatchHandleFaceResult batchHandleFaceResult = this.pineappleClient.batchAddFace(batchAddFaceParam);
|
||||
if (batchHandleFaceResult.getResult() != 0) {
|
||||
throw new ServiceException(batchHandleFaceResult.getResult().toString(), batchHandleFaceResult.getInfo());
|
||||
}
|
||||
this.logger.info("结束批量添加人脸");
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
public CloudwalkResult<BatchHandleFaceResult> batchRemoveFace(CpBatchHandleFaceParam param) throws ServiceException {
|
||||
this.logger.info("开始批量删除人脸,参数:{}", (Object)JSON.toJSONString((Object)param));
|
||||
this.checkBatchHandleFaceParam(param);
|
||||
ArrayList items = Lists.newArrayListWithCapacity((int)param.getImageIds().size());
|
||||
BatchRemoveFaceParam batchRemoveFaceParam = BatchRemoveFaceParam.builder().items((List)items).build();
|
||||
param.getImageIds().stream().forEach(imageId -> {
|
||||
BatchRemoveFaceParam.Item item = new BatchRemoveFaceParam.Item(batchRemoveFaceParam);
|
||||
item.setGroupId(param.getImageStoreId());
|
||||
item.setUserId(imageId);
|
||||
items.add(item);
|
||||
});
|
||||
batchRemoveFaceParam.setItems((List)items);
|
||||
BatchHandleFaceResult batchHandleFaceResult = this.pineappleClient.batchRemoveFace(batchRemoveFaceParam);
|
||||
if (batchHandleFaceResult.getResult() != 0) {
|
||||
throw new ServiceException(batchHandleFaceResult.getResult().toString(), batchHandleFaceResult.getInfo());
|
||||
}
|
||||
this.logger.info("结束批量删除人脸");
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
public CloudwalkResult<Boolean> addFace(CpBatchHandleFaceParam param) throws ServiceException {
|
||||
this.logger.info("开始添加人脸,参数:{}", (Object)JSON.toJSONString((Object)param));
|
||||
this.checkBatchHandleFaceParam(param);
|
||||
Map<String, ImgStorePerson> personMap = this.getPersonMap(param.getImageIds());
|
||||
AddFaceParam addFaceParam = AddFaceParam.builder().groupId(param.getImageStoreId()).build();
|
||||
AgFeatureExtractParam extractParam = null;
|
||||
int successCount = 0;
|
||||
for (String imageId : param.getImageIds()) {
|
||||
try {
|
||||
extractParam = new AgFeatureExtractParam();
|
||||
extractParam.setImageUrl(personMap.get(imageId).getComparePicture());
|
||||
CloudwalkResult<AgFeatureExtractResult> extractResult = this.extractFeature(extractParam);
|
||||
if (!extractResult.isSuccess()) continue;
|
||||
addFaceParam.setUserId(imageId);
|
||||
addFaceParam.setFeature(((AgFeatureExtractResult)extractResult.getData()).getFeature());
|
||||
List qualityScoreList = ((AgFeatureExtractResult)extractResult.getData()).getQuality().stream().map(x -> x + "").collect(Collectors.toList());
|
||||
addFaceParam.setQualityScore(String.join((CharSequence)",", qualityScoreList));
|
||||
PineappleBaseResult result = this.pineappleClient.addFace(addFaceParam);
|
||||
if (result.getResult() != 0) {
|
||||
this.logger.warn("图库[{}]添加人脸[{}]失败:{}", new Object[]{param.getImageStoreId(), imageId, result.getInfo()});
|
||||
continue;
|
||||
}
|
||||
++successCount;
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("图库[{}]添加人脸[{}]异常:{}", new Object[]{param.getImageStoreId(), imageId, e.getMessage()});
|
||||
}
|
||||
}
|
||||
this.logger.info("结束添加人脸");
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
public CloudwalkResult<HandleFaceResult> addFace(CpHandleFaceParam param) throws ServiceException {
|
||||
this.logger.info("开始添加人脸,参数:{}", (Object)JSON.toJSONString((Object)param));
|
||||
this.checkHandleFaceParam(param);
|
||||
HandleFaceResult handleFaceResult = new HandleFaceResult();
|
||||
try {
|
||||
ImgStorePersonQueryDto personQueryDto = new ImgStorePersonQueryDto();
|
||||
personQueryDto.setImageId(param.getImageId());
|
||||
List personList = this.personMapper.gets(personQueryDto);
|
||||
ImgStorePerson imgStorePerson = CollectionUtils.isEmpty((Collection)personList) ? new ImgStorePerson() : (ImgStorePerson)personList.get(0);
|
||||
this.logger.debug("addFace根据ImageId[{}]查询person:[{}]", (Object)param.getImageId(), (Object)JSON.toJSONString((Object)imgStorePerson));
|
||||
AgFeatureExtractParam extractParam = new AgFeatureExtractParam();
|
||||
extractParam.setImageUrl(imgStorePerson.getComparePicture());
|
||||
CloudwalkResult<AgFeatureExtractResult> extractResult = this.extractFeature(extractParam);
|
||||
List<Object> qualityScoreList = new ArrayList();
|
||||
if (extractResult.isSuccess()) {
|
||||
qualityScoreList = ((AgFeatureExtractResult)extractResult.getData()).getQuality().stream().map(x -> x + "").collect(Collectors.toList());
|
||||
}
|
||||
CpSearchFaceParam searchFaceParam = new CpSearchFaceParam();
|
||||
searchFaceParam.setImageStoreId(param.getImageStoreId());
|
||||
searchFaceParam.setImageIds(param.getImageId());
|
||||
CloudwalkResult<SearchFaceResult> searchFaceResult = this.searchFace(searchFaceParam);
|
||||
if (searchFaceResult.isSuccess() && ((SearchFaceResult)searchFaceResult.getData()).getResult() == 0) {
|
||||
handleFaceResult.setResult(Integer.valueOf(0));
|
||||
handleFaceResult.setInfo("success");
|
||||
handleFaceResult.setImageStoreId(param.getImageStoreId());
|
||||
handleFaceResult.setImageId(param.getImageId());
|
||||
handleFaceResult.setPersonId(Optional.ofNullable(imgStorePerson).map(p -> p.getId()).orElse(""));
|
||||
handleFaceResult.setAge(CollectionUtils.isEmpty(qualityScoreList) ? null : Integer.valueOf(new BigDecimal((String)qualityScoreList.get(10)).setScale(2, 3).intValue()));
|
||||
handleFaceResult.setGender(CollectionUtils.isEmpty(qualityScoreList) ? null : Short.valueOf(new BigDecimal((String)qualityScoreList.get(11)).shortValue()));
|
||||
this.logger.info("图库[{}]人脸[{}]已存在", (Object)param.getImageStoreId(), (Object)param.getImageId());
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
if (extractResult.isSuccess()) {
|
||||
AddFaceParam addFaceParam = AddFaceParam.builder().groupId(param.getImageStoreId()).userId(param.getImageId()).feature(((AgFeatureExtractResult)extractResult.getData()).getFeature()).qualityScore(String.join((CharSequence)",", qualityScoreList)).build();
|
||||
PineappleBaseResult result = this.pineappleClient.addFace(addFaceParam);
|
||||
this.logger.info("添加图库[{}]人脸[{}]引擎返回结果[{}]", new Object[]{param.getImageStoreId(), param.getImageId(), JSON.toJSONString((Object)result)});
|
||||
if (result.getResult() == 0) {
|
||||
handleFaceResult = (HandleFaceResult)BeanCopyUtils.copyProperties((Object)result, (Object)handleFaceResult);
|
||||
handleFaceResult.setImageStoreId(param.getImageStoreId());
|
||||
handleFaceResult.setImageId(param.getImageId());
|
||||
handleFaceResult.setPersonId(Optional.ofNullable(imgStorePerson).map(p -> p.getId()).orElse(""));
|
||||
handleFaceResult.setAge(Integer.valueOf(new BigDecimal((String)qualityScoreList.get(10)).setScale(2, 3).intValue()));
|
||||
handleFaceResult.setGender(Short.valueOf(new BigDecimal((String)qualityScoreList.get(11)).shortValue()));
|
||||
this.logger.info("结束添加图库[{}]人脸[{}]", (Object)param.getImageStoreId(), (Object)param.getImageId());
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
this.logger.warn("图库[{}]添加人脸[{}]失败:{}", new Object[]{param.getImageStoreId(), param.getImageId(), result.getInfo()});
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("图库[{}]添加人脸[{}]异常:{}", new Object[]{param.getImageStoreId(), param.getImageId(), e.getMessage()});
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
|
||||
public CloudwalkResult<HandleFaceResult> removeFace(CpHandleFaceParam param) throws ServiceException {
|
||||
this.logger.info("开始删除人脸,参数:{}", (Object)JSON.toJSONString((Object)param));
|
||||
this.checkHandleFaceParam(param);
|
||||
try {
|
||||
ImgStorePersonQueryDto personQueryDto = new ImgStorePersonQueryDto();
|
||||
personQueryDto.setImageId(param.getImageId());
|
||||
List personList = this.personMapper.gets(personQueryDto);
|
||||
ImgStorePerson imgStorePerson = CollectionUtils.isEmpty((Collection)personList) ? null : (ImgStorePerson)personList.get(0);
|
||||
RemoveFaceParam removeFaceParam = RemoveFaceParam.builder().groupId(param.getImageStoreId()).userId(param.getImageId()).build();
|
||||
PineappleBaseResult result = this.pineappleClient.removeFace(removeFaceParam);
|
||||
this.logger.info("删除图库[{}]人脸[{}]引擎返回结果[{}]", new Object[]{param.getImageStoreId(), param.getImageId(), JSON.toJSONString((Object)result)});
|
||||
if (result.getResult() == 0) {
|
||||
HandleFaceResult handleFaceResult = (HandleFaceResult)BeanCopyUtils.copyProperties((Object)result, HandleFaceResult.class);
|
||||
handleFaceResult.setPersonId(Optional.ofNullable(imgStorePerson).map(p -> p.getId()).orElse(""));
|
||||
this.logger.info("结束删除图库[{}]人脸[{}]", (Object)param.getImageStoreId(), (Object)param.getImageId());
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
this.logger.warn("图库[{}]删除人脸[{}]失败", (Object)param.getImageStoreId(), (Object)param.getImageId());
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("图库[{}]删除人脸[{}]异常:{}", new Object[]{param.getImageStoreId(), param.getImageId(), e.getMessage()});
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
|
||||
public CloudwalkResult<SearchFaceResult> searchFace(CpSearchFaceParam param) {
|
||||
if (StringUtils.isEmpty((Object)param.getImageStoreId())) {
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
if (StringUtils.isEmpty((Object)param.getImageIds())) {
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
SearchFaceParam searchFaceParam = SearchFaceParam.builder().groupId(param.getImageStoreId()).userId(String.join((CharSequence)",", param.getImageIds())).build();
|
||||
String resultStr = this.pineappleClient.searchFace(searchFaceParam);
|
||||
if (StringUtils.isEmpty((Object)resultStr)) {
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
SearchFaceResult result = (SearchFaceResult)JSON.parseObject((String)resultStr, SearchFaceResult.class);
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
public CloudwalkResult<BatchSearchFaceResult> batchSearchFace(CpSearchFaceParam param) {
|
||||
if (StringUtils.isEmpty((Object)param.getImageStoreId())) {
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
if (StringUtils.isEmpty((Object)param.getImageIds())) {
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
SearchFaceParam searchFaceParam = SearchFaceParam.builder().groupId(param.getImageStoreId()).userId(param.getImageIds()).build();
|
||||
String resultStr = this.pineappleClient.searchFace(searchFaceParam);
|
||||
if (StringUtils.isEmpty((Object)resultStr)) {
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
BatchSearchFaceResult result = (BatchSearchFaceResult)JSON.parseObject((String)resultStr, BatchSearchFaceResult.class);
|
||||
if (result.getResult() != 0) {
|
||||
this.logger.warn("批量查询图库[]人脸[]失败", (Object)param.getImageStoreId(), (Object)String.join((CharSequence)",", param.getImageIds()));
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
private void checkBatchHandleFaceParam(CpBatchHandleFaceParam param) throws ServiceException {
|
||||
if (StringUtils.isEmpty((Object)param.getImageStoreId())) {
|
||||
throw new ServiceException("53060438", this.getMessage("53060438"));
|
||||
}
|
||||
if (CollectionUtils.isEmpty((Collection)param.getImageIds())) {
|
||||
throw new ServiceException("53014025", this.getMessage("53014025"));
|
||||
}
|
||||
}
|
||||
|
||||
private void checkHandleFaceParam(CpHandleFaceParam param) throws ServiceException {
|
||||
if (StringUtils.isEmpty((Object)param.getImageStoreId())) {
|
||||
throw new ServiceException("53060438", this.getMessage("53060438"));
|
||||
}
|
||||
if (StringUtils.isEmpty((Object)param.getImageId())) {
|
||||
throw new ServiceException("53014026", this.getMessage("53014026"));
|
||||
}
|
||||
}
|
||||
|
||||
private List<CpFeatureQueryResult> transFaceResult(List<SearchFaceMutipleResult.FaceData> faceDataList, Map<String, ImgStorePerson> personMap) {
|
||||
ArrayList resultList = Lists.newArrayListWithCapacity((int)faceDataList.size());
|
||||
Map<String, List<SearchFaceMutipleResult.FaceData>> faceDataMap = faceDataList.stream().collect(Collectors.groupingBy(SearchFaceMutipleResult.FaceData::getGroupId));
|
||||
ArrayList groupPersonRefList = new ArrayList();
|
||||
for (Map.Entry<String, List<SearchFaceMutipleResult.FaceData>> entry : faceDataMap.entrySet()) {
|
||||
if (CollectionUtils.isEmpty((Collection)entry.getValue())) continue;
|
||||
GroupPersonRef groupPersonRef = new GroupPersonRef();
|
||||
groupPersonRef.setImageStoreId(entry.getKey());
|
||||
List personIdList = entry.getValue().stream().map(x -> ((ImgStorePerson)personMap.get(x.getUserId())).getId()).collect(Collectors.toList());
|
||||
List tempList = this.groupPersonRefMapper.selectByCondition(groupPersonRef, personIdList);
|
||||
if (CollectionUtils.isEmpty((Collection)tempList)) continue;
|
||||
groupPersonRefList.addAll(tempList);
|
||||
}
|
||||
Map<String, GroupPersonRef> groupPersonRefMap = groupPersonRefList.stream().collect(Collectors.toMap(GroupPersonRef::getPersonId, a -> a, (k1, k2) -> k1));
|
||||
for (SearchFaceMutipleResult.FaceData faceData : faceDataList) {
|
||||
CpFeatureQueryResult result = new CpFeatureQueryResult();
|
||||
result.setImageStoreId(faceData.getGroupId());
|
||||
result.setImageId(faceData.getUserId());
|
||||
result.setScore(Double.valueOf(faceData.getScore().toString()));
|
||||
ImgStorePerson imgStorePerson = personMap.get(faceData.getUserId());
|
||||
if (imgStorePerson == null) continue;
|
||||
result.setPersonId(imgStorePerson.getId());
|
||||
result.setName(imgStorePerson.getName());
|
||||
result.setPersonCode(imgStorePerson.getPersonCode());
|
||||
result.setComparePicture(imgStorePerson.getComparePicture());
|
||||
result.setAge((Integer)Optional.ofNullable(groupPersonRefMap.get(imgStorePerson.getId())).map(p -> p.getAge()).orElse(null));
|
||||
result.setGender((Short)Optional.ofNullable(groupPersonRefMap.get(imgStorePerson.getId())).map(p -> p.getGender()).orElse(null));
|
||||
resultList.add(result);
|
||||
}
|
||||
return resultList;
|
||||
}
|
||||
|
||||
private List<CpFeatureQueryResult> transFaceGroupResult(SearchFaceMutiplePerGroupResult.FaceGroupData faceGroupData, Map<String, ImgStorePerson> personMap) {
|
||||
ArrayList resultList = Lists.newArrayListWithCapacity((int)faceGroupData.getArray().size());
|
||||
GroupPersonRef groupPersonRef = new GroupPersonRef();
|
||||
groupPersonRef.setImageStoreId(faceGroupData.getGroupId());
|
||||
List personIdList = faceGroupData.getArray().stream().map(x -> ((ImgStorePerson)personMap.get(x.getUserId())).getId()).collect(Collectors.toList());
|
||||
List groupPersonRefList = this.groupPersonRefMapper.selectByCondition(groupPersonRef, personIdList);
|
||||
Map<String, GroupPersonRef> groupPersonRefMap = groupPersonRefList.stream().collect(Collectors.toMap(GroupPersonRef::getPersonId, a -> a, (k1, k2) -> k1));
|
||||
for (SearchFaceMutiplePerGroupResult.FaceData faceData : faceGroupData.getArray()) {
|
||||
CpFeatureQueryResult result = new CpFeatureQueryResult();
|
||||
result.setImageStoreId(faceGroupData.getGroupId());
|
||||
result.setImageId(faceData.getUserId());
|
||||
result.setScore(Double.valueOf(faceData.getScore().toString()));
|
||||
ImgStorePerson imgStorePerson = personMap.get(faceData.getUserId());
|
||||
if (imgStorePerson == null) continue;
|
||||
result.setPersonId(imgStorePerson.getId());
|
||||
result.setName(imgStorePerson.getName());
|
||||
result.setPersonCode(imgStorePerson.getPersonCode());
|
||||
result.setComparePicture(imgStorePerson.getComparePicture());
|
||||
result.setAge((Integer)Optional.ofNullable(groupPersonRefMap.get(imgStorePerson.getId())).map(p -> p.getAge()).orElse(null));
|
||||
result.setGender((Short)Optional.ofNullable(groupPersonRefMap.get(imgStorePerson.getId())).map(p -> p.getGender()).orElse(null));
|
||||
resultList.add(result);
|
||||
}
|
||||
return resultList;
|
||||
}
|
||||
|
||||
private Map<String, ImgStorePerson> getPersonMap(Collection<String> imageIds) {
|
||||
ImgStorePersonQueryDto personQueryDto = new ImgStorePersonQueryDto();
|
||||
personQueryDto.setImageIds(imageIds);
|
||||
List personList = this.personMapper.gets(personQueryDto);
|
||||
HashMap<String, ImgStorePerson> personMap = new HashMap<String, ImgStorePerson>(personList.size());
|
||||
for (ImgStorePerson imgStorePerson : personList) {
|
||||
personMap.put(imgStorePerson.getImageId(), imgStorePerson);
|
||||
}
|
||||
return personMap;
|
||||
}
|
||||
implements CpImageStoreToolService
|
||||
{
|
||||
@Resource
|
||||
private ImgStorePersonMapper personMapper;
|
||||
@Resource
|
||||
private PineappleEngineClient pineappleClient;
|
||||
@Resource
|
||||
private FileStorageManager fileStorageManager;
|
||||
@Resource
|
||||
private GroupPersonRefMapper groupPersonRefMapper;
|
||||
public CloudwalkResult<List<CpFeatureQueryResult>> searchMultiple(CpFeatureQueryParam queryParam) throws ServiceException {
|
||||
if (this.logger.isDebugEnabled()) {
|
||||
this.logger.debug("开始查询所有图库topN,参数:{}", JSON.toJSONString(queryParam));
|
||||
}
|
||||
String groupId = queryParam.getImageStoreId();
|
||||
if (StringUtils.isEmpty(groupId) && !CollectionUtils.isEmpty(queryParam.getImageStoreIds())) {
|
||||
groupId = String.join(",", queryParam.getImageStoreIds());
|
||||
}
|
||||
if (StringUtils.isEmpty(groupId)) {
|
||||
throw new ServiceException("53060438", getMessage("53060438"));
|
||||
}
|
||||
String feature = queryParam.getFeature();
|
||||
if (StringUtils.isEmpty(feature) && !StringUtils.isEmpty(queryParam.getImageBase64())) {
|
||||
AgFeatureExtractParam extractParam = new AgFeatureExtractParam();
|
||||
extractParam.setImageBase64(queryParam.getImageBase64());
|
||||
CloudwalkResult<AgFeatureExtractResult> extractResult = extractFeature(extractParam);
|
||||
if (extractResult.isSuccess()) {
|
||||
feature = ((AgFeatureExtractResult)extractResult.getData()).getFeature();
|
||||
}
|
||||
}
|
||||
if (StringUtils.isEmpty(feature)) {
|
||||
throw new ServiceException("53060436", getMessage("53060436"));
|
||||
}
|
||||
SearchFaceMutipleParam searchMutipleParam = SearchFaceMutipleParam.builder().groupId(groupId).topN(queryParam.getTopN()).feature(feature).mode("all").bTime(queryParam.getBeginTime()).eTime(queryParam.getEndTime()).build();
|
||||
if (this.logger.isDebugEnabled()) {
|
||||
this.logger.debug("查询所有图库topN,引擎多库检索参数:{}", JSON.toJSONString(searchMutipleParam));
|
||||
}
|
||||
SearchFaceMutipleResult searchMutipleResult = this.pineappleClient.searchMultiple(searchMutipleParam);
|
||||
if (this.logger.isDebugEnabled()) {
|
||||
this.logger.debug("查询所有图库topN,引擎多库检索结果:{}", JSON.toJSONString(searchMutipleResult));
|
||||
}
|
||||
if (searchMutipleResult.getResult().intValue() != 0) {
|
||||
throw new ServiceException(searchMutipleResult.getResult().toString(), searchMutipleResult.getInfo());
|
||||
}
|
||||
List<SearchFaceMutipleResult.FaceData> faceDataList = searchMutipleResult.getFaces();
|
||||
if (CollectionUtils.isEmpty(faceDataList)) {
|
||||
return CloudwalkResult.success(new ArrayList());
|
||||
}
|
||||
List<String> userIdList = (List<String>)faceDataList.stream().map(SearchFaceMutipleResult.FaceData::getUserId).collect(
|
||||
Collectors.toList());
|
||||
Map<String, ImgStorePerson> personMap = new HashMap<>();
|
||||
if (!CollectionUtils.isEmpty(userIdList))
|
||||
{
|
||||
personMap = getPersonMap(userIdList);
|
||||
}
|
||||
return CloudwalkResult.success(transFaceResult(faceDataList, personMap));
|
||||
}
|
||||
public CloudwalkResult<Map<String, List<CpFeatureQueryResult>>> searchMultipleEveryGroup(CpFeatureQueryParam queryParam) throws ServiceException {
|
||||
if (this.logger.isDebugEnabled()) {
|
||||
this.logger.debug("开始查询每个图库topN,参数:{}", JSON.toJSONString(queryParam));
|
||||
}
|
||||
String groupId = queryParam.getImageStoreId();
|
||||
if (StringUtils.isEmpty(groupId)) {
|
||||
groupId = String.join(",", queryParam.getImageStoreIds());
|
||||
}
|
||||
if (StringUtils.isEmpty(groupId)) {
|
||||
throw new ServiceException("53060438", getMessage("53060438"));
|
||||
}
|
||||
String feature = queryParam.getFeature();
|
||||
if (StringUtils.isEmpty(feature) && !StringUtils.isEmpty(queryParam.getImageBase64())) {
|
||||
AgFeatureExtractParam extractParam = new AgFeatureExtractParam();
|
||||
extractParam.setImageBase64(queryParam.getImageBase64());
|
||||
CloudwalkResult<AgFeatureExtractResult> extractResult = extractFeature(extractParam);
|
||||
if (extractResult.isSuccess()) {
|
||||
feature = ((AgFeatureExtractResult)extractResult.getData()).getFeature();
|
||||
}
|
||||
}
|
||||
if (StringUtils.isEmpty(feature)) {
|
||||
throw new ServiceException("53060436", getMessage("53060436"));
|
||||
}
|
||||
SearchFaceMutipleParam searchMutipleParam = SearchFaceMutipleParam.builder().groupId(groupId).topN(queryParam.getTopN()).feature(feature).mode("perGroup").bTime(queryParam.getBeginTime()).eTime(queryParam.getEndTime()).build();
|
||||
this.logger.info("查询每个图库topN,引擎多库检索参数:{}", JSON.toJSONString(searchMutipleParam));
|
||||
SearchFaceMutiplePerGroupResult searchMutiplePerGroupResult = this.pineappleClient.searchMultipleEveryGroup(searchMutipleParam);
|
||||
this.logger.info("查询每个图库topN,引擎多库检索结果:{}", JSON.toJSONString(searchMutiplePerGroupResult));
|
||||
if (searchMutiplePerGroupResult.getResult().intValue() != 0) {
|
||||
throw new ServiceException(searchMutiplePerGroupResult.getResult().toString(), searchMutiplePerGroupResult.getInfo());
|
||||
}
|
||||
List<SearchFaceMutiplePerGroupResult.FaceGroupData> faceGroupDataList = searchMutiplePerGroupResult.getFaces();
|
||||
if (CollectionUtils.isEmpty(faceGroupDataList)) {
|
||||
return CloudwalkResult.success(new HashMap<>());
|
||||
}
|
||||
Set<String> imageIdSet = new HashSet<>();
|
||||
faceGroupDataList.stream().forEach(faceGroupData -> {
|
||||
if (!CollectionUtils.isEmpty(faceGroupData.getArray())) {
|
||||
imageIdSet.addAll((Collection)faceGroupData.getArray().stream().map(SearchFaceMutiplePerGroupResult.FaceData::getUserId).collect(Collectors.toList()));
|
||||
}
|
||||
});
|
||||
Map<String, ImgStorePerson> personMap = new HashMap<>();
|
||||
if (!imageIdSet.isEmpty())
|
||||
{
|
||||
personMap = getPersonMap(imageIdSet);
|
||||
}
|
||||
Map<String, List<CpFeatureQueryResult>> resultMap = new HashMap<>(faceGroupDataList.size());
|
||||
for (SearchFaceMutiplePerGroupResult.FaceGroupData faceGroupData : faceGroupDataList) {
|
||||
resultMap.put(faceGroupData.getGroupId(), transFaceGroupResult(faceGroupData, personMap));
|
||||
}
|
||||
return CloudwalkResult.success(resultMap);
|
||||
}
|
||||
public CloudwalkResult<AgFeatureExtractResult> extractFeature(AgFeatureExtractParam extractParam) throws ServiceException {
|
||||
this.logger.info("开始特征提取,参数:{}", JSON.toJSONString(extractParam));
|
||||
String img = extractParam.getImageBase64();
|
||||
if (StringUtils.isEmpty(img) && !StringUtils.isEmpty(extractParam.getImageUrl())) {
|
||||
try {
|
||||
byte[] bytes = this.fileStorageManager.fileDownload(extractParam.getImageUrl());
|
||||
img = ImageUtil.encodeByte2Base64(bytes);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("下载图片异常:{}", e.getMessage());
|
||||
throw new ServiceException("80014016", getMessage("80014016"));
|
||||
}
|
||||
}
|
||||
if (StringUtils.isEmpty(img)) {
|
||||
throw new ServiceException("53060434", getMessage("53060434"));
|
||||
}
|
||||
ExtractFeatureParam extractFeatureParam = ExtractFeatureParam.builder().img(img).modelVersion(extractParam.getEngineVersionModelId()).build();
|
||||
ExtractFeatureResult extractFeatureResult = null;
|
||||
try {
|
||||
CompletableFuture<ExtractFeatureResult> future = CompletableFuture.supplyAsync(() -> this.pineappleClient.extractFeature(extractFeatureParam));
|
||||
extractFeatureResult = future.get();
|
||||
} catch (ExecutionException e) {
|
||||
this.logger.error("引擎提取特征异常:{}", e.getMessage());
|
||||
throw new ServiceException("53060435", getMessage("53060435"));
|
||||
} catch (InterruptedException e) {
|
||||
this.logger.error("引擎提取特征异常:{}", e.getMessage());
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
if (null == extractFeatureResult) {
|
||||
throw new ServiceException("53060436", getMessage("53060436"));
|
||||
}
|
||||
if (extractFeatureResult.getResult().intValue() != 0) {
|
||||
throw new ServiceException(extractFeatureResult.getResult().toString(), extractFeatureResult.getInfo());
|
||||
}
|
||||
List<String> qualityScores = Arrays.asList(extractFeatureResult.getQualityScores().split(","));
|
||||
List<Double> quality = (List<Double>)qualityScores.stream().map(qualityScore -> Double.valueOf(qualityScore)).collect(Collectors.toList());
|
||||
AgFeatureExtractResult result = new AgFeatureExtractResult();
|
||||
result.setFeature(extractFeatureResult.getFeature());
|
||||
result.setQuality(quality);
|
||||
result.setScore(quality.get(0));
|
||||
result.setAge(Integer.valueOf((new BigDecimal(qualityScores.get(10))).setScale(0, 4).intValue()));
|
||||
result.setGender(Integer.valueOf((new BigDecimal(qualityScores.get(11))).setScale(0).intValue()));
|
||||
this.logger.info("结束特征提取,结果:{}", JSON.toJSONString(result));
|
||||
return CloudwalkResult.success(result);
|
||||
}
|
||||
public CloudwalkResult<FaceDetectResult> faceDetect(CpFaceDetectParam faceDetectParam) throws ServiceException {
|
||||
this.logger.info("开始人脸检测,参数:{}", JSON.toJSONString(faceDetectParam));
|
||||
String img = faceDetectParam.getImageBase64();
|
||||
if (StringUtils.isEmpty(img) && !StringUtils.isEmpty(faceDetectParam.getImageUrl())) {
|
||||
try {
|
||||
byte[] bytes = this.fileStorageManager.fileDownload(faceDetectParam.getImageUrl());
|
||||
img = ImageUtil.encodeByte2Base64(bytes);
|
||||
} catch (Exception e) {
|
||||
throw new ServiceException("80014016", getMessage("80014016"));
|
||||
}
|
||||
}
|
||||
if (StringUtils.isEmpty(img)) {
|
||||
throw new ServiceException("53060434", getMessage("53060434"));
|
||||
}
|
||||
FaceDetectParam param = FaceDetectParam.builder().img(img).build();
|
||||
FaceDetectResult faceDetectResult = null;
|
||||
try {
|
||||
CompletableFuture<FaceDetectResult> future = CompletableFuture.supplyAsync(() -> this.pineappleClient.faceDetect(param));
|
||||
faceDetectResult = future.get();
|
||||
} catch (ExecutionException e) {
|
||||
this.logger.error("引擎人脸检测异常:{}", e.getMessage());
|
||||
throw new ServiceException("53060439", getMessage("53060439"));
|
||||
} catch (InterruptedException e) {
|
||||
this.logger.error("引擎人脸检测异常:{}", e.getMessage());
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
if (null == faceDetectResult) {
|
||||
throw new ServiceException("53060440", getMessage("53060440"));
|
||||
}
|
||||
if (faceDetectResult.getResult().intValue() != 0) {
|
||||
throw new ServiceException(faceDetectResult.getResult().toString(), faceDetectResult.getInfo());
|
||||
}
|
||||
this.logger.info("结束人脸检测,结果:{}", JSON.toJSONString(faceDetectResult));
|
||||
return CloudwalkResult.success(faceDetectResult);
|
||||
}
|
||||
public CloudwalkResult<BatchHandleFaceResult> batchAddFace(CpBatchHandleFaceParam param) throws ServiceException {
|
||||
this.logger.info("开始批量添加人脸,参数:{}", JSON.toJSONString(param));
|
||||
checkBatchHandleFaceParam(param);
|
||||
List<BatchAddFaceParam.Item> items = Lists.newArrayListWithCapacity(param.getImageIds().size());
|
||||
BatchAddFaceParam batchAddFaceParam = BatchAddFaceParam.builder().items(items).build();
|
||||
Map<String, ImgStorePerson> personMap = getPersonMap(param.getImageIds());
|
||||
AgFeatureExtractParam extractParam = null;
|
||||
for (String imageId : param.getImageIds()) {
|
||||
try {
|
||||
extractParam = new AgFeatureExtractParam();
|
||||
extractParam.setImageUrl(((ImgStorePerson)personMap.get(imageId)).getComparePicture());
|
||||
CloudwalkResult<AgFeatureExtractResult> extractResult = extractFeature(extractParam);
|
||||
if (extractResult.isSuccess()) {
|
||||
batchAddFaceParam.getClass(); BatchAddFaceParam.Item item = new BatchAddFaceParam.Item(batchAddFaceParam);
|
||||
item.setGroupId(param.getImageStoreId());
|
||||
item.setUserId(imageId);
|
||||
item.setFeature(((AgFeatureExtractResult)extractResult.getData()).getFeature());
|
||||
List<String> qualityScoreList = (List<String>)((AgFeatureExtractResult)extractResult.getData()).getQuality().stream().map(x -> x + "").collect(
|
||||
Collectors.toList());
|
||||
item.setQualityScore(String.join(",", (Iterable)qualityScoreList));
|
||||
items.add(item);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
this.logger.error("提取特征异常:{}", e.getMessage());
|
||||
}
|
||||
}
|
||||
batchAddFaceParam.setItems(items);
|
||||
BatchHandleFaceResult batchHandleFaceResult = this.pineappleClient.batchAddFace(batchAddFaceParam);
|
||||
if (batchHandleFaceResult.getResult().intValue() != 0) {
|
||||
throw new ServiceException(batchHandleFaceResult.getResult().toString(), batchHandleFaceResult.getInfo());
|
||||
}
|
||||
this.logger.info("结束批量添加人脸");
|
||||
return CloudwalkResult.success(batchHandleFaceResult);
|
||||
}
|
||||
public CloudwalkResult<BatchHandleFaceResult> batchRemoveFace(CpBatchHandleFaceParam param) throws ServiceException {
|
||||
this.logger.info("开始批量删除人脸,参数:{}", JSON.toJSONString(param));
|
||||
checkBatchHandleFaceParam(param);
|
||||
List<BatchRemoveFaceParam.Item> items = Lists.newArrayListWithCapacity(param.getImageIds().size());
|
||||
BatchRemoveFaceParam batchRemoveFaceParam = BatchRemoveFaceParam.builder().items(items).build();
|
||||
param.getImageIds().stream().forEach(imageId -> {
|
||||
batchRemoveFaceParam.getClass(); BatchRemoveFaceParam.Item item = new BatchRemoveFaceParam.Item(batchRemoveFaceParam);
|
||||
item.setGroupId(param.getImageStoreId());
|
||||
item.setUserId(imageId);
|
||||
items.add(item);
|
||||
});
|
||||
batchRemoveFaceParam.setItems(items);
|
||||
BatchHandleFaceResult batchHandleFaceResult = this.pineappleClient.batchRemoveFace(batchRemoveFaceParam);
|
||||
if (batchHandleFaceResult.getResult().intValue() != 0) {
|
||||
throw new ServiceException(batchHandleFaceResult.getResult().toString(), batchHandleFaceResult.getInfo());
|
||||
}
|
||||
this.logger.info("结束批量删除人脸");
|
||||
return CloudwalkResult.success(batchHandleFaceResult);
|
||||
}
|
||||
public CloudwalkResult<Boolean> addFace(CpBatchHandleFaceParam param) throws ServiceException {
|
||||
this.logger.info("开始添加人脸,参数:{}", JSON.toJSONString(param));
|
||||
checkBatchHandleFaceParam(param);
|
||||
Map<String, ImgStorePerson> personMap = getPersonMap(param.getImageIds());
|
||||
AddFaceParam addFaceParam = AddFaceParam.builder().groupId(param.getImageStoreId()).build();
|
||||
AgFeatureExtractParam extractParam = null;
|
||||
int successCount = 0;
|
||||
for (String imageId : param.getImageIds()) {
|
||||
try {
|
||||
extractParam = new AgFeatureExtractParam();
|
||||
extractParam.setImageUrl(((ImgStorePerson)personMap.get(imageId)).getComparePicture());
|
||||
CloudwalkResult<AgFeatureExtractResult> extractResult = extractFeature(extractParam);
|
||||
if (extractResult.isSuccess()) {
|
||||
addFaceParam.setUserId(imageId);
|
||||
addFaceParam.setFeature(((AgFeatureExtractResult)extractResult.getData()).getFeature());
|
||||
List<String> qualityScoreList = (List<String>)((AgFeatureExtractResult)extractResult.getData()).getQuality().stream().map(x -> x + "").collect(
|
||||
Collectors.toList());
|
||||
addFaceParam.setQualityScore(String.join(",", (Iterable)qualityScoreList));
|
||||
PineappleBaseResult result = this.pineappleClient.addFace(addFaceParam);
|
||||
if (result.getResult().intValue() != 0) {
|
||||
this.logger.warn("图库[{}]添加人脸[{}]失败:{}", new Object[] { param.getImageStoreId(), imageId, result.getInfo() });
|
||||
continue;
|
||||
}
|
||||
successCount++;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
this.logger.error("图库[{}]添加人脸[{}]异常:{}", new Object[] { param.getImageStoreId(), imageId, e.getMessage() });
|
||||
}
|
||||
}
|
||||
this.logger.info("结束添加人脸");
|
||||
return CloudwalkResult.success(Boolean.valueOf((successCount > 0)));
|
||||
}
|
||||
public CloudwalkResult<HandleFaceResult> addFace(CpHandleFaceParam param) throws ServiceException {
|
||||
this.logger.info("开始添加人脸,参数:{}", JSON.toJSONString(param));
|
||||
checkHandleFaceParam(param);
|
||||
HandleFaceResult handleFaceResult = new HandleFaceResult();
|
||||
try {
|
||||
ImgStorePersonQueryDto personQueryDto = new ImgStorePersonQueryDto();
|
||||
personQueryDto.setImageId(param.getImageId());
|
||||
List<ImgStorePerson> personList = this.personMapper.gets(personQueryDto);
|
||||
ImgStorePerson imgStorePerson = CollectionUtils.isEmpty(personList) ? new ImgStorePerson() : personList.get(0);
|
||||
this.logger.debug("addFace根据ImageId[{}]查询person:[{}]", param.getImageId(), JSON.toJSONString(imgStorePerson));
|
||||
AgFeatureExtractParam extractParam = new AgFeatureExtractParam();
|
||||
extractParam.setImageUrl(imgStorePerson.getComparePicture());
|
||||
CloudwalkResult<AgFeatureExtractResult> extractResult = extractFeature(extractParam);
|
||||
List<String> qualityScoreList = new ArrayList<>();
|
||||
if (extractResult.isSuccess()) {
|
||||
qualityScoreList = (List<String>)((AgFeatureExtractResult)extractResult.getData()).getQuality().stream().map(x -> x + "").collect(
|
||||
Collectors.toList());
|
||||
}
|
||||
CpSearchFaceParam searchFaceParam = new CpSearchFaceParam();
|
||||
searchFaceParam.setImageStoreId(param.getImageStoreId());
|
||||
searchFaceParam.setImageIds(param.getImageId());
|
||||
CloudwalkResult<SearchFaceResult> searchFaceResult = searchFace(searchFaceParam);
|
||||
if (searchFaceResult.isSuccess() && ((SearchFaceResult)searchFaceResult.getData()).getResult().intValue() == 0) {
|
||||
handleFaceResult.setResult(Integer.valueOf(0));
|
||||
handleFaceResult.setInfo("success");
|
||||
handleFaceResult.setImageStoreId(param.getImageStoreId());
|
||||
handleFaceResult.setImageId(param.getImageId());
|
||||
handleFaceResult.setPersonId(Optional.<ImgStorePerson>ofNullable(imgStorePerson).map(p -> p.getId()).orElse(""));
|
||||
handleFaceResult.setAge(CollectionUtils.isEmpty(qualityScoreList) ? null : Integer.valueOf((new BigDecimal(qualityScoreList.get(10))).setScale(2, 3).intValue()));
|
||||
handleFaceResult.setGender(CollectionUtils.isEmpty(qualityScoreList) ? null : Short.valueOf((new BigDecimal(qualityScoreList.get(11))).shortValue()));
|
||||
this.logger.info("图库[{}]人脸[{}]已存在", param.getImageStoreId(), param.getImageId());
|
||||
return CloudwalkResult.success(handleFaceResult);
|
||||
}
|
||||
if (extractResult.isSuccess())
|
||||
{
|
||||
AddFaceParam addFaceParam = AddFaceParam.builder().groupId(param.getImageStoreId()).userId(param.getImageId()).feature(((AgFeatureExtractResult)extractResult.getData()).getFeature()).qualityScore(String.join(",", (Iterable)qualityScoreList)).build();
|
||||
PineappleBaseResult result = this.pineappleClient.addFace(addFaceParam);
|
||||
this.logger.info("添加图库[{}]人脸[{}]引擎返回结果[{}]", new Object[] { param.getImageStoreId(), param.getImageId(), JSON.toJSONString(result) });
|
||||
if (result.getResult().intValue() == 0) {
|
||||
handleFaceResult = (HandleFaceResult)BeanCopyUtils.copyProperties(result, handleFaceResult);
|
||||
handleFaceResult.setImageStoreId(param.getImageStoreId());
|
||||
handleFaceResult.setImageId(param.getImageId());
|
||||
handleFaceResult.setPersonId(Optional.<ImgStorePerson>ofNullable(imgStorePerson).map(p -> p.getId()).orElse(""));
|
||||
handleFaceResult.setAge(Integer.valueOf((new BigDecimal(qualityScoreList.get(10))).setScale(2, 3).intValue()));
|
||||
handleFaceResult.setGender(Short.valueOf((new BigDecimal(qualityScoreList.get(11))).shortValue()));
|
||||
this.logger.info("结束添加图库[{}]人脸[{}]", param.getImageStoreId(), param.getImageId());
|
||||
return CloudwalkResult.success(handleFaceResult);
|
||||
}
|
||||
this.logger.warn("图库[{}]添加人脸[{}]失败:{}", new Object[] { param.getImageStoreId(), param.getImageId(), result.getInfo() });
|
||||
}
|
||||
} catch (Exception e) {
|
||||
this.logger.error("图库[{}]添加人脸[{}]异常:{}", new Object[] { param.getImageStoreId(), param.getImageId(), e.getMessage() });
|
||||
}
|
||||
return CloudwalkResult.fail("53060447", getMessage("53060447"));
|
||||
}
|
||||
public CloudwalkResult<HandleFaceResult> removeFace(CpHandleFaceParam param) throws ServiceException {
|
||||
this.logger.info("开始删除人脸,参数:{}", JSON.toJSONString(param));
|
||||
checkHandleFaceParam(param);
|
||||
try {
|
||||
ImgStorePersonQueryDto personQueryDto = new ImgStorePersonQueryDto();
|
||||
personQueryDto.setImageId(param.getImageId());
|
||||
List<ImgStorePerson> personList = this.personMapper.gets(personQueryDto);
|
||||
ImgStorePerson imgStorePerson = CollectionUtils.isEmpty(personList) ? null : personList.get(0);
|
||||
RemoveFaceParam removeFaceParam = RemoveFaceParam.builder().groupId(param.getImageStoreId()).userId(param.getImageId()).build();
|
||||
PineappleBaseResult result = this.pineappleClient.removeFace(removeFaceParam);
|
||||
this.logger.info("删除图库[{}]人脸[{}]引擎返回结果[{}]", new Object[] { param.getImageStoreId(), param.getImageId(), JSON.toJSONString(result) });
|
||||
if (result.getResult().intValue() == 0) {
|
||||
HandleFaceResult handleFaceResult = (HandleFaceResult)BeanCopyUtils.copyProperties(result, HandleFaceResult.class);
|
||||
handleFaceResult.setPersonId(Optional.<ImgStorePerson>ofNullable(imgStorePerson).map(p -> p.getId()).orElse(""));
|
||||
this.logger.info("结束删除图库[{}]人脸[{}]", param.getImageStoreId(), param.getImageId());
|
||||
return CloudwalkResult.success(handleFaceResult);
|
||||
}
|
||||
this.logger.warn("图库[{}]删除人脸[{}]失败", param.getImageStoreId(), param.getImageId());
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("图库[{}]删除人脸[{}]异常:{}", new Object[] { param.getImageStoreId(), param.getImageId(), e.getMessage() });
|
||||
}
|
||||
return CloudwalkResult.fail("53060448", getMessage("53060448"));
|
||||
}
|
||||
public CloudwalkResult<SearchFaceResult> searchFace(CpSearchFaceParam param) {
|
||||
if (StringUtils.isEmpty(param.getImageStoreId())) {
|
||||
return CloudwalkResult.fail("53060438", getMessage("53060438"));
|
||||
}
|
||||
if (StringUtils.isEmpty(param.getImageIds())) {
|
||||
return CloudwalkResult.fail("53014025", getMessage("53014025"));
|
||||
}
|
||||
SearchFaceParam searchFaceParam = SearchFaceParam.builder().groupId(param.getImageStoreId()).userId(String.join(",", new CharSequence[] { param.getImageIds() })).build();
|
||||
String resultStr = this.pineappleClient.searchFace(searchFaceParam);
|
||||
if (StringUtils.isEmpty(resultStr)) {
|
||||
return CloudwalkResult.fail("53060443", getMessage("53060443"));
|
||||
}
|
||||
SearchFaceResult result = (SearchFaceResult)JSON.parseObject(resultStr, SearchFaceResult.class);
|
||||
return CloudwalkResult.success(result);
|
||||
}
|
||||
public CloudwalkResult<BatchSearchFaceResult> batchSearchFace(CpSearchFaceParam param) {
|
||||
if (StringUtils.isEmpty(param.getImageStoreId())) {
|
||||
return CloudwalkResult.fail("53060438", getMessage("53060438"));
|
||||
}
|
||||
if (StringUtils.isEmpty(param.getImageIds())) {
|
||||
return CloudwalkResult.fail("53014025", getMessage("53014025"));
|
||||
}
|
||||
SearchFaceParam searchFaceParam = SearchFaceParam.builder().groupId(param.getImageStoreId()).userId(param.getImageIds()).build();
|
||||
String resultStr = this.pineappleClient.searchFace(searchFaceParam);
|
||||
if (StringUtils.isEmpty(resultStr)) {
|
||||
return CloudwalkResult.fail("53060443", getMessage("53060443"));
|
||||
}
|
||||
BatchSearchFaceResult result = (BatchSearchFaceResult)JSON.parseObject(resultStr, BatchSearchFaceResult.class);
|
||||
if (result.getResult().intValue() != 0) {
|
||||
this.logger.warn("批量查询图库[]人脸[]失败", param.getImageStoreId(), String.join(",", new CharSequence[] { param.getImageIds() }));
|
||||
return CloudwalkResult.fail("53060444", getMessage("53060444"));
|
||||
}
|
||||
return CloudwalkResult.success(result);
|
||||
}
|
||||
private void checkBatchHandleFaceParam(CpBatchHandleFaceParam param) throws ServiceException {
|
||||
if (StringUtils.isEmpty(param.getImageStoreId())) {
|
||||
throw new ServiceException("53060438", getMessage("53060438"));
|
||||
}
|
||||
if (CollectionUtils.isEmpty(param.getImageIds())) {
|
||||
throw new ServiceException("53014025", getMessage("53014025"));
|
||||
}
|
||||
}
|
||||
private void checkHandleFaceParam(CpHandleFaceParam param) throws ServiceException {
|
||||
if (StringUtils.isEmpty(param.getImageStoreId())) {
|
||||
throw new ServiceException("53060438", getMessage("53060438"));
|
||||
}
|
||||
if (StringUtils.isEmpty(param.getImageId())) {
|
||||
throw new ServiceException("53014026", getMessage("53014026"));
|
||||
}
|
||||
}
|
||||
private List<CpFeatureQueryResult> transFaceResult(List<SearchFaceMutipleResult.FaceData> faceDataList, Map<String, ImgStorePerson> personMap) {
|
||||
List<CpFeatureQueryResult> resultList = Lists.newArrayListWithCapacity(faceDataList.size());
|
||||
Map<String, List<SearchFaceMutipleResult.FaceData>> faceDataMap = (Map<String, List<SearchFaceMutipleResult.FaceData>>)faceDataList.stream().collect(Collectors.groupingBy(SearchFaceMutipleResult.FaceData::getGroupId));
|
||||
List<GroupPersonRef> groupPersonRefList = new ArrayList<>();
|
||||
for (Map.Entry<String, List<SearchFaceMutipleResult.FaceData>> entry : faceDataMap.entrySet()) {
|
||||
if (!CollectionUtils.isEmpty(entry.getValue())) {
|
||||
GroupPersonRef groupPersonRef = new GroupPersonRef();
|
||||
groupPersonRef.setImageStoreId(entry.getKey());
|
||||
List<String> personIdList = (List<String>)((List)entry.getValue()).stream().map(x -> ((ImgStorePerson)personMap.get(x.getUserId())).getId()).collect(Collectors.toList());
|
||||
List<GroupPersonRef> tempList = this.groupPersonRefMapper.selectByCondition(groupPersonRef, personIdList);
|
||||
if (!CollectionUtils.isEmpty(tempList)) {
|
||||
groupPersonRefList.addAll(tempList);
|
||||
}
|
||||
}
|
||||
}
|
||||
Map<String, GroupPersonRef> groupPersonRefMap = (Map<String, GroupPersonRef>)groupPersonRefList.stream().collect(Collectors.toMap(GroupPersonRef::getPersonId, a -> a, (k1, k2) -> k1));
|
||||
for (SearchFaceMutipleResult.FaceData faceData : faceDataList) {
|
||||
CpFeatureQueryResult result = new CpFeatureQueryResult();
|
||||
result.setImageStoreId(faceData.getGroupId());
|
||||
result.setImageId(faceData.getUserId());
|
||||
result.setScore(Double.valueOf(faceData.getScore().toString()));
|
||||
ImgStorePerson imgStorePerson = personMap.get(faceData.getUserId());
|
||||
if (imgStorePerson != null) {
|
||||
result.setPersonId(imgStorePerson.getId());
|
||||
result.setName(imgStorePerson.getName());
|
||||
result.setPersonCode(imgStorePerson.getPersonCode());
|
||||
result.setComparePicture(imgStorePerson.getComparePicture());
|
||||
result.setAge(Optional.ofNullable(groupPersonRefMap.get(imgStorePerson.getId())).map(p -> p.getAge()).orElse(null));
|
||||
result.setGender(Optional.ofNullable(groupPersonRefMap.get(imgStorePerson.getId())).map(p -> p.getGender()).orElse(null));
|
||||
resultList.add(result);
|
||||
}
|
||||
}
|
||||
return resultList;
|
||||
}
|
||||
private List<CpFeatureQueryResult> transFaceGroupResult(SearchFaceMutiplePerGroupResult.FaceGroupData faceGroupData, Map<String, ImgStorePerson> personMap) {
|
||||
List<CpFeatureQueryResult> resultList = Lists.newArrayListWithCapacity(faceGroupData.getArray().size());
|
||||
GroupPersonRef groupPersonRef = new GroupPersonRef();
|
||||
groupPersonRef.setImageStoreId(faceGroupData.getGroupId());
|
||||
List<String> personIdList = (List<String>)faceGroupData.getArray().stream().map(x -> ((ImgStorePerson)personMap.get(x.getUserId())).getId()).collect(Collectors.toList());
|
||||
List<GroupPersonRef> groupPersonRefList = this.groupPersonRefMapper.selectByCondition(groupPersonRef, personIdList);
|
||||
Map<String, GroupPersonRef> groupPersonRefMap = (Map<String, GroupPersonRef>)groupPersonRefList.stream().collect(Collectors.toMap(GroupPersonRef::getPersonId, a -> a, (k1, k2) -> k1));
|
||||
for (SearchFaceMutiplePerGroupResult.FaceData faceData : faceGroupData.getArray()) {
|
||||
CpFeatureQueryResult result = new CpFeatureQueryResult();
|
||||
result.setImageStoreId(faceGroupData.getGroupId());
|
||||
result.setImageId(faceData.getUserId());
|
||||
result.setScore(Double.valueOf(faceData.getScore().toString()));
|
||||
ImgStorePerson imgStorePerson = personMap.get(faceData.getUserId());
|
||||
if (imgStorePerson != null) {
|
||||
result.setPersonId(imgStorePerson.getId());
|
||||
result.setName(imgStorePerson.getName());
|
||||
result.setPersonCode(imgStorePerson.getPersonCode());
|
||||
result.setComparePicture(imgStorePerson.getComparePicture());
|
||||
result.setAge(Optional.ofNullable(groupPersonRefMap.get(imgStorePerson.getId())).map(p -> p.getAge()).orElse(null));
|
||||
result.setGender(Optional.ofNullable(groupPersonRefMap.get(imgStorePerson.getId())).map(p -> p.getGender()).orElse(null));
|
||||
resultList.add(result);
|
||||
}
|
||||
}
|
||||
return resultList;
|
||||
}
|
||||
private Map<String, ImgStorePerson> getPersonMap(Collection<String> imageIds) {
|
||||
ImgStorePersonQueryDto personQueryDto = new ImgStorePersonQueryDto();
|
||||
personQueryDto.setImageIds(imageIds);
|
||||
List<ImgStorePerson> personList = this.personMapper.gets(personQueryDto);
|
||||
Map<String, ImgStorePerson> personMap = new HashMap<>(personList.size());
|
||||
for (ImgStorePerson imgStorePerson : personList)
|
||||
{
|
||||
personMap.put(imgStorePerson.getImageId(), imgStorePerson);
|
||||
}
|
||||
return personMap;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/CpImageStoreToolServiceImpl.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+624
-613
File diff suppressed because it is too large
Load Diff
+54
-52
@@ -20,66 +20,68 @@ import cn.cloudwalk.data.organization.mapper.OrganizationImageStoreMapper;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import com.github.pagehelper.Page;
|
||||
import com.github.pagehelper.PageHelper;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
@Service
|
||||
public class CpOrgImageStoreServiceImpl
|
||||
extends AbstractImagStoreService
|
||||
implements CpOrgImageStoreService {
|
||||
@Autowired
|
||||
private OrganizationImageStoreMapper organizationImageStoreMapper;
|
||||
@Autowired
|
||||
private ApplicationImageStoreService applicationImageStoreService;
|
||||
|
||||
@CloudwalkParamsValidate
|
||||
@Transactional(rollbackFor={Exception.class})
|
||||
public CloudwalkResult<Boolean> add(BaseOrgImageStoreParam addParam, CloudwalkCallContext context) throws ServiceException {
|
||||
this.organizationImageStoreMapper.insert((OrganizationImageStore)BeanCopyUtils.copyProperties((Object)addParam, OrganizationImageStore.class));
|
||||
try {
|
||||
this.applicationImageStoreService.add((ApplicationImageStoreAddParam)BeanCopyUtils.copyProperties((Object)addParam, ApplicationImageStoreAddParam.class), context);
|
||||
}
|
||||
catch (DuplicateKeyException e) {
|
||||
this.logger.warn("已关联应用");
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("新增图库应用关联异常", e);
|
||||
throw new ServiceException("53013522", this.getMessage("53013522"));
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
@CloudwalkParamsValidate
|
||||
@Transactional(rollbackFor={Exception.class})
|
||||
public CloudwalkResult<Boolean> delete(BaseOrgImageStoreParam deleteParam, CloudwalkCallContext context) {
|
||||
this.organizationImageStoreMapper.deleteByPrimaryKey((OrganizationImageStore)BeanCopyUtils.copyProperties((Object)deleteParam, OrganizationImageStore.class));
|
||||
OrganizationImageStoreQueryDTO queryDTO = new OrganizationImageStoreQueryDTO();
|
||||
queryDTO.setApplicationId(deleteParam.getApplicationId());
|
||||
queryDTO.setImageStoreId(deleteParam.getImageStoreId());
|
||||
List queryResult = this.organizationImageStoreMapper.query(queryDTO);
|
||||
if (CollectionUtils.isEmpty((Collection)queryResult)) {
|
||||
this.applicationImageStoreService.delete((ApplicationImageStoreDeleteParam)BeanCopyUtils.copyProperties((Object)deleteParam, ApplicationImageStoreDeleteParam.class), context);
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<List<OrgImageStoreResult>> query(QueryOrgImageStoreParam queryParam, CloudwalkCallContext context) {
|
||||
List queryResult = this.organizationImageStoreMapper.query((OrganizationImageStoreQueryDTO)BeanCopyUtils.copyProperties((Object)queryParam, OrganizationImageStoreQueryDTO.class));
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<CloudwalkPageAble<OrgImageStoreResult>> page(QueryOrgImageStoreParam queryParam, CloudwalkCallContext context) {
|
||||
Page pageInfo = PageHelper.startPage((int)queryParam.getCurrentPage(), (int)queryParam.getRowsOfPage());
|
||||
List queryResult = this.organizationImageStoreMapper.query((OrganizationImageStoreQueryDTO)BeanCopyUtils.copyProperties((Object)queryParam, OrganizationImageStoreQueryDTO.class));
|
||||
List resultList = BeanCopyUtils.copy((Collection)queryResult, OrgImageStoreResult.class);
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
implements CpOrgImageStoreService
|
||||
{
|
||||
@Autowired
|
||||
private OrganizationImageStoreMapper organizationImageStoreMapper;
|
||||
@Autowired
|
||||
private ApplicationImageStoreService applicationImageStoreService;
|
||||
@CloudwalkParamsValidate
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
public CloudwalkResult<Boolean> add(BaseOrgImageStoreParam addParam, CloudwalkCallContext context) throws ServiceException {
|
||||
this.organizationImageStoreMapper.insert((OrganizationImageStore)BeanCopyUtils.copyProperties(addParam, OrganizationImageStore.class));
|
||||
try {
|
||||
this.applicationImageStoreService.add((ApplicationImageStoreAddParam)BeanCopyUtils.copyProperties(addParam, ApplicationImageStoreAddParam.class), context);
|
||||
} catch (DuplicateKeyException e) {
|
||||
this.logger.warn("已关联应用");
|
||||
} catch (Exception e) {
|
||||
this.logger.error("新增图库应用关联异常", e);
|
||||
throw new ServiceException("53013522",
|
||||
getMessage("53013522"));
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.valueOf(true));
|
||||
}
|
||||
@CloudwalkParamsValidate
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
public CloudwalkResult<Boolean> delete(BaseOrgImageStoreParam deleteParam, CloudwalkCallContext context) {
|
||||
this.organizationImageStoreMapper.deleteByPrimaryKey((OrganizationImageStore)BeanCopyUtils.copyProperties(deleteParam, OrganizationImageStore.class));
|
||||
OrganizationImageStoreQueryDTO queryDTO = new OrganizationImageStoreQueryDTO();
|
||||
queryDTO.setApplicationId(deleteParam.getApplicationId());
|
||||
queryDTO.setImageStoreId(deleteParam.getImageStoreId());
|
||||
List<OrganizationImageStore> queryResult = this.organizationImageStoreMapper.query(queryDTO);
|
||||
if (CollectionUtils.isEmpty(queryResult))
|
||||
{
|
||||
this.applicationImageStoreService.delete((ApplicationImageStoreDeleteParam)BeanCopyUtils.copyProperties(deleteParam, ApplicationImageStoreDeleteParam.class), context);
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.valueOf(true));
|
||||
}
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<List<OrgImageStoreResult>> query(QueryOrgImageStoreParam queryParam, CloudwalkCallContext context) {
|
||||
List<OrganizationImageStore> queryResult = this.organizationImageStoreMapper.query((OrganizationImageStoreQueryDTO)BeanCopyUtils.copyProperties(queryParam, OrganizationImageStoreQueryDTO.class));
|
||||
return CloudwalkResult.success(BeanCopyUtils.copy(queryResult, OrgImageStoreResult.class));
|
||||
}
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<CloudwalkPageAble<OrgImageStoreResult>> page(QueryOrgImageStoreParam queryParam, CloudwalkCallContext context) {
|
||||
Page<Object> pageInfo = PageHelper.startPage(queryParam.getCurrentPage(), queryParam.getRowsOfPage());
|
||||
List<OrganizationImageStore> queryResult = this.organizationImageStoreMapper.query((OrganizationImageStoreQueryDTO)BeanCopyUtils.copyProperties(queryParam, OrganizationImageStoreQueryDTO.class));
|
||||
List<OrgImageStoreResult> resultList = BeanCopyUtils.copy(queryResult, OrgImageStoreResult.class);
|
||||
return CloudwalkResult.success(new CloudwalkPageAble(resultList, new CloudwalkPageInfo(queryParam
|
||||
.getCurrentPage(), queryParam.getCurrentPage()), pageInfo
|
||||
.getTotal()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/CpOrgImageStoreServiceImpl.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+194
-195
@@ -3,6 +3,7 @@ package cn.cloudwalk.service.organization.service;
|
||||
import cn.cloudwalk.client.aggregate.device.param.DeviceImageStoreQueryParam;
|
||||
import cn.cloudwalk.client.aggregate.device.param.DeviceImageStoreReSyncParam;
|
||||
import cn.cloudwalk.client.aggregate.device.result.DeviceImageStoreQueryResult;
|
||||
import cn.cloudwalk.client.aggregate.device.result.DeviceImageStoreReSyncResult;
|
||||
import cn.cloudwalk.client.aggregate.device.service.AggDeviceImageStoreService;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.param.AtomicDeviceCommonParam;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.result.CoreDeviceDetailResult;
|
||||
@@ -20,12 +21,10 @@ import cn.cloudwalk.data.organization.mapper.DeviceImageStoreMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.DevicePersonSyncLogMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.GroupPersonRefMapper;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import cn.cloudwalk.service.organization.service.CpImageStoreSyncManager;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Sets;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
@@ -36,200 +35,200 @@ import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
@Component
|
||||
public class DeviceGroupRefChangeEventHandler
|
||||
extends AbstractImagStoreService {
|
||||
@Resource
|
||||
private AggDeviceImageStoreService aggDeviceImageStoreService;
|
||||
@Resource
|
||||
private AtomicDeviceService atomicDeviceService;
|
||||
@Resource
|
||||
private CpImageStoreSyncManager cpImageStoreSyncManager;
|
||||
@Resource
|
||||
private DevicePersonSyncLogMapper devicePersonSyncLogMapper;
|
||||
@Resource
|
||||
private DeviceImageStoreMapper deviceImageStoreMapper;
|
||||
@Resource
|
||||
private GroupPersonRefMapper groupPersonRefMapper;
|
||||
@Resource
|
||||
private UUIDSerial uuidSerial;
|
||||
@Value(value="${person.partition.size:100}")
|
||||
private Integer personPartitionSize;
|
||||
|
||||
@Async(value="deviceGroupChangeTaskExecutor")
|
||||
public void handler(DeviceGroupRefChangeEvent event) {
|
||||
if (null == event) {
|
||||
return;
|
||||
}
|
||||
if (StringUtils.isBlank((CharSequence)event.getDeviceId()) || StringUtils.isBlank((CharSequence)event.getGroupId())) {
|
||||
this.logger.warn("设备[{}]或者图库[{}]为空", (Object)event.getDeviceId(), (Object)event.getGroupId());
|
||||
return;
|
||||
}
|
||||
this.logger.debug("Kafka消费设备图库变更数据:[{}]", (Object)JSON.toJSONString((Object)event));
|
||||
try {
|
||||
AtomicDeviceCommonParam queryDevice = new AtomicDeviceCommonParam();
|
||||
queryDevice.setId(event.getDeviceId());
|
||||
CloudwalkResult deviceResult = this.atomicDeviceService.detail(queryDevice, this.getCloudwalkContext());
|
||||
if (!deviceResult.isSuccess() || null == deviceResult.getData()) {
|
||||
this.logger.warn("查询设备[{}]失败", (Object)event.getDeviceId());
|
||||
return;
|
||||
}
|
||||
CoreDeviceDetailResult device = (CoreDeviceDetailResult)deviceResult.getData();
|
||||
if (device.getIdentifyType() != 0) {
|
||||
this.logger.warn("设备[{}]非前端识别", (Object)device.getId());
|
||||
return;
|
||||
}
|
||||
this.saveDeviceImageStoreChange(event);
|
||||
this.unbindDeviceImageStore(event, device);
|
||||
this.bindDeviceImageStore(event);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("执行报错 {}: {}", (Object)e.getClass().getName(), (Object)e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private int saveDeviceImageStoreChange(DeviceGroupRefChangeEvent event) {
|
||||
Long time = System.currentTimeMillis();
|
||||
DeviceImageStore query = new DeviceImageStore();
|
||||
query.setDeviceId(event.getDeviceId());
|
||||
query.setImageStoreId(event.getGroupId());
|
||||
query.setType(Integer.valueOf(event.getType().shortValue()));
|
||||
query.setLastUpdateTime(time);
|
||||
List result = this.deviceImageStoreMapper.select(query);
|
||||
if (CollectionUtils.isEmpty((Collection)result)) {
|
||||
this.logger.debug("根据设备[{}]图库[{}]未查询到变更记录,新增", (Object)event.getDeviceId(), (Object)event.getGroupId());
|
||||
query.setId(this.uuidSerial.uuid());
|
||||
query.setCreateTime(time);
|
||||
return this.deviceImageStoreMapper.insertSelective(query);
|
||||
}
|
||||
this.logger.debug("根据设备[{}]图库[{}]查询到变更记录[{}],修改", new Object[]{event.getDeviceId(), event.getGroupId(), ((DeviceImageStore)result.get(0)).getId()});
|
||||
query.setFinishPullTime(null);
|
||||
query.setStatus(StatusEnum.UNNOTIFY.getValue());
|
||||
return this.deviceImageStoreMapper.update(query);
|
||||
}
|
||||
|
||||
private void unbindDeviceImageStore(DeviceGroupRefChangeEvent event, CoreDeviceDetailResult device) {
|
||||
if (event.getType() != 2) {
|
||||
return;
|
||||
}
|
||||
this.logger.debug("开始处理设备[{}]图库[{}]解绑", (Object)event.getDeviceId(), (Object)event.getGroupId());
|
||||
try {
|
||||
DeviceImageStoreQueryParam storeQueryParam = new DeviceImageStoreQueryParam();
|
||||
storeQueryParam.setDeviceId(event.getDeviceId());
|
||||
CloudwalkResult imageStoreResult = this.aggDeviceImageStoreService.query(storeQueryParam, this.getCloudwalkContext());
|
||||
if (imageStoreResult.isSuccess() && !CollectionUtils.isEmpty((Collection)((Collection)imageStoreResult.getData()))) {
|
||||
this.logger.debug("设备[{}]仍绑定其他图库", (Object)event.getDeviceId());
|
||||
String deviceCode = device.getDeviceCode();
|
||||
if (null == device.getSupportMultiPersonGroup() || Objects.equals(device.getSupportMultiPersonGroup().intValue(), DeviceAbilityEnum.NOT_SUPPORT_MULTI_PERSON_GROUP.getCode())) {
|
||||
this.logger.debug("设备[{}]code[{}]不支持多图库,下发50009", (Object)event.getDeviceId(), (Object)deviceCode);
|
||||
List<String> imageStoreIds = ((List)imageStoreResult.getData()).stream().map(DeviceImageStoreQueryResult::getImageStoreId).collect(Collectors.toList());
|
||||
this.updateSyncLog(event, imageStoreIds);
|
||||
HashSet changeGroupIdSet = Sets.newHashSet();
|
||||
changeGroupIdSet.add(event.getGroupId());
|
||||
((List)imageStoreResult.getData()).stream().forEach(imageStore -> changeGroupIdSet.add(imageStore.getImageStoreId()));
|
||||
this.cpImageStoreSyncManager.sendChangeToDevice(event.getDeviceId(), changeGroupIdSet, false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
this.notify50010(event);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("设备[{}]图库[{}]解绑执行异常:{}", new Object[]{event.getDeviceId(), event.getGroupId(), e.getMessage()});
|
||||
}
|
||||
}
|
||||
|
||||
private void updateSyncLog(DeviceGroupRefChangeEvent event, List<String> imageStoreIds) {
|
||||
DevicePersonSyncLogDTO query = new DevicePersonSyncLogDTO();
|
||||
query.setDeviceId(event.getDeviceId());
|
||||
query.setImageStoreId(event.getGroupId());
|
||||
List dbSyncLogList = this.devicePersonSyncLogMapper.query(query);
|
||||
Set personIdSet = dbSyncLogList.stream().map(DevicePersonSyncLog::getPersonId).collect(Collectors.toSet());
|
||||
List personIdPartition = Lists.partition((List)Lists.newArrayList(personIdSet), (int)this.personPartitionSize);
|
||||
for (List personIds : personIdPartition) {
|
||||
query.setImageStoreIds(imageStoreIds);
|
||||
query.setPersonIds(personIds);
|
||||
List personIdList = this.devicePersonSyncLogMapper.findPersonIds(query);
|
||||
Long currentTime = System.currentTimeMillis();
|
||||
if (!CollectionUtils.isEmpty((Collection)personIdList)) {
|
||||
this.logger.info("移除在其他图库中的人员:[{}]", (Object)personIdList);
|
||||
personIdSet.removeAll(personIdList);
|
||||
query.setPersonIds(personIdList);
|
||||
query.setLastUpdateTime(currentTime);
|
||||
this.devicePersonSyncLogMapper.updateLastTimeOfGroupPerson(query);
|
||||
query.setLastUpdateTime(null);
|
||||
query.setIsDel(Integer.valueOf(StatusEnum.INVALID.getValue()));
|
||||
query.setStatus(Integer.valueOf(SyncStatusEnum.NOT_PULL.getValue()));
|
||||
int res = this.devicePersonSyncLogMapper.updateIsDel(query);
|
||||
this.logger.info("设备[{}]图库[{}]更新[{}]条人员存在其他图库中", new Object[]{event.getDeviceId(), event.getGroupId(), res});
|
||||
}
|
||||
this.groupPersonRefMapper.updateLastUpdateTimeByPersonIds(event.getGroupId(), personIds, currentTime);
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(personIdSet)) {
|
||||
personIdPartition = Lists.partition((List)Lists.newArrayList(personIdSet), (int)this.personPartitionSize);
|
||||
query = new DevicePersonSyncLogDTO();
|
||||
query.setDeviceId(event.getDeviceId());
|
||||
query.setImageStoreId(event.getGroupId());
|
||||
for (List personIds : personIdPartition) {
|
||||
query.setPersonIds(personIds);
|
||||
query.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
query.setIsDel(Integer.valueOf(StatusEnum.INVALID.getValue()));
|
||||
query.setStatus(Integer.valueOf(SyncStatusEnum.NOT_PULL.getValue()));
|
||||
int res = this.devicePersonSyncLogMapper.updateIsDel(query);
|
||||
this.logger.info("设备[{}]图库[{}]更新[{}]条人员不存在其他图库中", new Object[]{event.getDeviceId(), event.getGroupId(), res});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void notify50010(DeviceGroupRefChangeEvent event) {
|
||||
try {
|
||||
DevicePersonSyncLogDTO query = new DevicePersonSyncLogDTO();
|
||||
query.setDeviceId(event.getDeviceId());
|
||||
query.setImageStoreId(event.getGroupId());
|
||||
query.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
query.setIsDel(Integer.valueOf(StatusEnum.INVALID.getValue()));
|
||||
query.setStatus(Integer.valueOf(SyncStatusEnum.NOT_PULL.getValue()));
|
||||
int res = this.devicePersonSyncLogMapper.updateIsDel(query);
|
||||
this.logger.debug("设备[{}]图库[{}]解绑,逻辑删除[{}]条同步记录", new Object[]{event.getDeviceId(), event.getGroupId(), res});
|
||||
this.logger.debug("设备[{}]图库[{}]下发50010", (Object)event.getDeviceId(), (Object)event.getGroupId());
|
||||
DeviceImageStoreReSyncParam deviceImageStoreReSyncParam = new DeviceImageStoreReSyncParam();
|
||||
deviceImageStoreReSyncParam.setDeviceId(event.getDeviceId());
|
||||
deviceImageStoreReSyncParam.setImageStoreId(event.getGroupId());
|
||||
CloudwalkResult result = this.aggDeviceImageStoreService.reSync(deviceImageStoreReSyncParam, this.getCloudwalkContext());
|
||||
if (result.isSuccess()) {
|
||||
DeviceImageStore notify = new DeviceImageStore();
|
||||
notify.setDeviceId(event.getDeviceId());
|
||||
notify.setImageStoreId(event.getGroupId());
|
||||
List deviceImageStoreList = this.deviceImageStoreMapper.select(notify);
|
||||
if (!CollectionUtils.isEmpty((Collection)deviceImageStoreList)) {
|
||||
notify = (DeviceImageStore)deviceImageStoreList.get(0);
|
||||
notify.setStatus(StatusEnum.NOTIFY.getValue());
|
||||
notify.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.deviceImageStoreMapper.update(notify);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("设备[{}]图库[{}]解绑执行异常:{}", new Object[]{event.getDeviceId(), event.getGroupId(), e.getMessage()});
|
||||
}
|
||||
}
|
||||
|
||||
private void bindDeviceImageStore(DeviceGroupRefChangeEvent event) {
|
||||
if (event.getType() != 1) {
|
||||
return;
|
||||
}
|
||||
this.logger.debug("开始处理设备[{}]图库[{}]绑定", (Object)event.getDeviceId(), (Object)event.getGroupId());
|
||||
DevicePersonSyncLogDTO query = new DevicePersonSyncLogDTO();
|
||||
query.setDeviceId(event.getDeviceId());
|
||||
query.setImageStoreId(event.getGroupId());
|
||||
query.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
query.setIsDel(Integer.valueOf(StatusEnum.VALID.getValue()));
|
||||
query.setStatus(Integer.valueOf(SyncStatusEnum.NOT_PULL.getValue()));
|
||||
int res = this.devicePersonSyncLogMapper.updateIsDel(query);
|
||||
this.logger.debug("设备[{}]图库[{}]绑定,更新[{}]条同步记录", new Object[]{event.getDeviceId(), event.getGroupId(), res});
|
||||
HashSet changeGroupIdSet = Sets.newHashSet();
|
||||
changeGroupIdSet.add(event.getGroupId());
|
||||
this.cpImageStoreSyncManager.sendChangeToDevice(event.getDeviceId(), changeGroupIdSet, false);
|
||||
}
|
||||
extends AbstractImagStoreService
|
||||
{
|
||||
@Resource
|
||||
private AggDeviceImageStoreService aggDeviceImageStoreService;
|
||||
@Resource
|
||||
private AtomicDeviceService atomicDeviceService;
|
||||
@Resource
|
||||
private CpImageStoreSyncManager cpImageStoreSyncManager;
|
||||
@Resource
|
||||
private DevicePersonSyncLogMapper devicePersonSyncLogMapper;
|
||||
@Resource
|
||||
private DeviceImageStoreMapper deviceImageStoreMapper;
|
||||
@Resource
|
||||
private GroupPersonRefMapper groupPersonRefMapper;
|
||||
@Resource
|
||||
private UUIDSerial uuidSerial;
|
||||
@Value("${person.partition.size:100}")
|
||||
private Integer personPartitionSize;
|
||||
@Async("deviceGroupChangeTaskExecutor")
|
||||
public void handler(DeviceGroupRefChangeEvent event) {
|
||||
if (null == event) {
|
||||
return;
|
||||
}
|
||||
if (StringUtils.isBlank(event.getDeviceId()) || StringUtils.isBlank(event.getGroupId())) {
|
||||
this.logger.warn("设备[{}]或者图库[{}]为空", event.getDeviceId(), event.getGroupId());
|
||||
return;
|
||||
}
|
||||
this.logger.debug("Kafka消费设备图库变更数据:[{}]", JSON.toJSONString(event));
|
||||
try {
|
||||
AtomicDeviceCommonParam queryDevice = new AtomicDeviceCommonParam();
|
||||
queryDevice.setId(event.getDeviceId());
|
||||
CloudwalkResult<CoreDeviceDetailResult> deviceResult = this.atomicDeviceService.detail(queryDevice, getCloudwalkContext());
|
||||
if (!deviceResult.isSuccess() || null == deviceResult.getData()) {
|
||||
this.logger.warn("查询设备[{}]失败", event.getDeviceId());
|
||||
return;
|
||||
}
|
||||
CoreDeviceDetailResult device = (CoreDeviceDetailResult)deviceResult.getData();
|
||||
if (device.getIdentifyType().shortValue() != 0) {
|
||||
this.logger.warn("设备[{}]非前端识别", device.getId());
|
||||
return;
|
||||
}
|
||||
saveDeviceImageStoreChange(event);
|
||||
unbindDeviceImageStore(event, device);
|
||||
bindDeviceImageStore(event);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("执行报错 {}: {}", e.getClass().getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
private int saveDeviceImageStoreChange(DeviceGroupRefChangeEvent event) {
|
||||
Long time = Long.valueOf(System.currentTimeMillis());
|
||||
DeviceImageStore query = new DeviceImageStore();
|
||||
query.setDeviceId(event.getDeviceId());
|
||||
query.setImageStoreId(event.getGroupId());
|
||||
query.setType(Integer.valueOf(event.getType().shortValue()));
|
||||
query.setLastUpdateTime(time);
|
||||
List<DeviceImageStore> result = this.deviceImageStoreMapper.select(query);
|
||||
if (CollectionUtils.isEmpty(result)) {
|
||||
this.logger.debug("根据设备[{}]图库[{}]未查询到变更记录,新增", event.getDeviceId(), event.getGroupId());
|
||||
query.setId(this.uuidSerial.uuid());
|
||||
query.setCreateTime(time);
|
||||
return this.deviceImageStoreMapper.insertSelective(query);
|
||||
}
|
||||
this.logger.debug("根据设备[{}]图库[{}]查询到变更记录[{}],修改", new Object[] { event.getDeviceId(), event.getGroupId(), ((DeviceImageStore)result.get(0)).getId() });
|
||||
query.setFinishPullTime(null);
|
||||
query.setStatus(StatusEnum.UNNOTIFY.getValue());
|
||||
return this.deviceImageStoreMapper.update(query);
|
||||
}
|
||||
private void unbindDeviceImageStore(DeviceGroupRefChangeEvent event, CoreDeviceDetailResult device) {
|
||||
if (event.getType().shortValue() != 2) {
|
||||
return;
|
||||
}
|
||||
this.logger.debug("开始处理设备[{}]图库[{}]解绑", event.getDeviceId(), event.getGroupId());
|
||||
try {
|
||||
DeviceImageStoreQueryParam storeQueryParam = new DeviceImageStoreQueryParam();
|
||||
storeQueryParam.setDeviceId(event.getDeviceId());
|
||||
CloudwalkResult<List<DeviceImageStoreQueryResult>> imageStoreResult = this.aggDeviceImageStoreService.query(storeQueryParam, getCloudwalkContext());
|
||||
if (imageStoreResult.isSuccess() && !CollectionUtils.isEmpty((Collection)imageStoreResult.getData())) {
|
||||
this.logger.debug("设备[{}]仍绑定其他图库", event.getDeviceId());
|
||||
String deviceCode = device.getDeviceCode();
|
||||
if (null == device.getSupportMultiPersonGroup() ||
|
||||
Objects.equals(Integer.valueOf(device.getSupportMultiPersonGroup().intValue()),
|
||||
Integer.valueOf(DeviceAbilityEnum.NOT_SUPPORT_MULTI_PERSON_GROUP.getCode()))) {
|
||||
this.logger.debug("设备[{}]code[{}]不支持多图库,下发50009", event.getDeviceId(), deviceCode);
|
||||
List<String> imageStoreIds = (List<String>)((List)imageStoreResult.getData()).stream().map(DeviceImageStoreQueryResult::getImageStoreId).collect(
|
||||
Collectors.toList());
|
||||
updateSyncLog(event, imageStoreIds);
|
||||
Set<String> changeGroupIdSet = Sets.newHashSet();
|
||||
changeGroupIdSet.add(event.getGroupId());
|
||||
((List)imageStoreResult.getData()).stream().forEach(imageStore -> changeGroupIdSet.add(imageStore.getImageStoreId()));
|
||||
this.cpImageStoreSyncManager.sendChangeToDevice(event.getDeviceId(), changeGroupIdSet, false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
notify50010(event);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("设备[{}]图库[{}]解绑执行异常:{}", new Object[] { event.getDeviceId(), event.getGroupId(), e.getMessage() });
|
||||
}
|
||||
}
|
||||
private void updateSyncLog(DeviceGroupRefChangeEvent event, List<String> imageStoreIds) {
|
||||
DevicePersonSyncLogDTO query = new DevicePersonSyncLogDTO();
|
||||
query.setDeviceId(event.getDeviceId());
|
||||
query.setImageStoreId(event.getGroupId());
|
||||
List<DevicePersonSyncLog> dbSyncLogList = this.devicePersonSyncLogMapper.query(query);
|
||||
Set<String> personIdSet = (Set<String>)dbSyncLogList.stream().map(DevicePersonSyncLog::getPersonId).collect(
|
||||
Collectors.toSet());
|
||||
List<List<String>> personIdPartition = Lists.partition(Lists.newArrayList(personIdSet), this.personPartitionSize.intValue());
|
||||
for (List<String> personIds : personIdPartition) {
|
||||
query.setImageStoreIds(imageStoreIds);
|
||||
query.setPersonIds(personIds);
|
||||
List<String> personIdList = this.devicePersonSyncLogMapper.findPersonIds(query);
|
||||
Long currentTime = Long.valueOf(System.currentTimeMillis());
|
||||
if (!CollectionUtils.isEmpty(personIdList)) {
|
||||
this.logger.info("移除在其他图库中的人员:[{}]", personIdList);
|
||||
personIdSet.removeAll(personIdList);
|
||||
query.setPersonIds(personIdList);
|
||||
query.setLastUpdateTime(currentTime);
|
||||
this.devicePersonSyncLogMapper.updateLastTimeOfGroupPerson(query);
|
||||
query.setLastUpdateTime(null);
|
||||
query.setIsDel(Integer.valueOf(StatusEnum.INVALID.getValue().intValue()));
|
||||
query.setStatus(Integer.valueOf(SyncStatusEnum.NOT_PULL.getValue()));
|
||||
int res = this.devicePersonSyncLogMapper.updateIsDel(query);
|
||||
this.logger.info("设备[{}]图库[{}]更新[{}]条人员存在其他图库中", new Object[] { event.getDeviceId(), event.getGroupId(), Integer.valueOf(res) });
|
||||
}
|
||||
this.groupPersonRefMapper.updateLastUpdateTimeByPersonIds(event.getGroupId(), personIds, currentTime);
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(personIdSet)) {
|
||||
personIdPartition = Lists.partition(Lists.newArrayList(personIdSet), this.personPartitionSize.intValue());
|
||||
query = new DevicePersonSyncLogDTO();
|
||||
query.setDeviceId(event.getDeviceId());
|
||||
query.setImageStoreId(event.getGroupId());
|
||||
for (List<String> personIds : personIdPartition) {
|
||||
query.setPersonIds(personIds);
|
||||
query.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
query.setIsDel(Integer.valueOf(StatusEnum.INVALID.getValue().intValue()));
|
||||
query.setStatus(Integer.valueOf(SyncStatusEnum.NOT_PULL.getValue()));
|
||||
int res = this.devicePersonSyncLogMapper.updateIsDel(query);
|
||||
this.logger.info("设备[{}]图库[{}]更新[{}]条人员不存在其他图库中", new Object[] { event.getDeviceId(), event.getGroupId(), Integer.valueOf(res) });
|
||||
}
|
||||
}
|
||||
}
|
||||
private void notify50010(DeviceGroupRefChangeEvent event) {
|
||||
try {
|
||||
DevicePersonSyncLogDTO query = new DevicePersonSyncLogDTO();
|
||||
query.setDeviceId(event.getDeviceId());
|
||||
query.setImageStoreId(event.getGroupId());
|
||||
query.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
query.setIsDel(Integer.valueOf(StatusEnum.INVALID.getValue().intValue()));
|
||||
query.setStatus(Integer.valueOf(SyncStatusEnum.NOT_PULL.getValue()));
|
||||
int res = this.devicePersonSyncLogMapper.updateIsDel(query);
|
||||
this.logger.debug("设备[{}]图库[{}]解绑,逻辑删除[{}]条同步记录", new Object[] { event.getDeviceId(), event.getGroupId(), Integer.valueOf(res) });
|
||||
this.logger.debug("设备[{}]图库[{}]下发50010", event.getDeviceId(), event.getGroupId());
|
||||
DeviceImageStoreReSyncParam deviceImageStoreReSyncParam = new DeviceImageStoreReSyncParam();
|
||||
deviceImageStoreReSyncParam.setDeviceId(event.getDeviceId());
|
||||
deviceImageStoreReSyncParam.setImageStoreId(event.getGroupId());
|
||||
CloudwalkResult<List<DeviceImageStoreReSyncResult>> result = this.aggDeviceImageStoreService.reSync(deviceImageStoreReSyncParam, getCloudwalkContext());
|
||||
if (result.isSuccess()) {
|
||||
DeviceImageStore notify = new DeviceImageStore();
|
||||
notify.setDeviceId(event.getDeviceId());
|
||||
notify.setImageStoreId(event.getGroupId());
|
||||
List<DeviceImageStore> deviceImageStoreList = this.deviceImageStoreMapper.select(notify);
|
||||
if (!CollectionUtils.isEmpty(deviceImageStoreList)) {
|
||||
notify = deviceImageStoreList.get(0);
|
||||
notify.setStatus(StatusEnum.NOTIFY.getValue());
|
||||
notify.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.deviceImageStoreMapper.update(notify);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
this.logger.error("设备[{}]图库[{}]解绑执行异常:{}", new Object[] { event.getDeviceId(), event.getGroupId(), e.getMessage() });
|
||||
}
|
||||
}
|
||||
private void bindDeviceImageStore(DeviceGroupRefChangeEvent event) {
|
||||
if (event.getType().shortValue() != 1) {
|
||||
return;
|
||||
}
|
||||
this.logger.debug("开始处理设备[{}]图库[{}]绑定", event.getDeviceId(), event.getGroupId());
|
||||
DevicePersonSyncLogDTO query = new DevicePersonSyncLogDTO();
|
||||
query.setDeviceId(event.getDeviceId());
|
||||
query.setImageStoreId(event.getGroupId());
|
||||
query.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
query.setIsDel(Integer.valueOf(StatusEnum.VALID.getValue().intValue()));
|
||||
query.setStatus(Integer.valueOf(SyncStatusEnum.NOT_PULL.getValue()));
|
||||
int res = this.devicePersonSyncLogMapper.updateIsDel(query);
|
||||
this.logger.debug("设备[{}]图库[{}]绑定,更新[{}]条同步记录", new Object[] { event.getDeviceId(), event.getGroupId(), Integer.valueOf(res) });
|
||||
Set<String> changeGroupIdSet = Sets.newHashSet();
|
||||
changeGroupIdSet.add(event.getGroupId());
|
||||
this.cpImageStoreSyncManager.sendChangeToDevice(event.getDeviceId(), changeGroupIdSet, false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/DeviceGroupRefChangeEventHandler.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+144
-151
@@ -3,6 +3,7 @@ package cn.cloudwalk.service.organization.service;
|
||||
import cn.cloudwalk.client.aggregate.device.param.DeviceImageStoreQueryParam;
|
||||
import cn.cloudwalk.client.aggregate.device.param.DeviceImageStoreReSyncParam;
|
||||
import cn.cloudwalk.client.aggregate.device.result.DeviceImageStoreQueryResult;
|
||||
import cn.cloudwalk.client.aggregate.device.result.DeviceImageStoreReSyncResult;
|
||||
import cn.cloudwalk.client.aggregate.device.service.AggDeviceImageStoreService;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.param.AtomicDeviceCommonParam;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.param.CoreDeviceQueryParam;
|
||||
@@ -20,11 +21,9 @@ import cn.cloudwalk.data.organization.mapper.DeviceImageStoreMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.DevicePersonSyncLogMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.GroupPersonRefMapper;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import cn.cloudwalk.service.organization.service.CpImageStoreSyncManager;
|
||||
import com.google.common.collect.Sets;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
@@ -35,156 +34,150 @@ import org.apache.commons.collections4.CollectionUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class DevicePersonSyncManager
|
||||
extends AbstractImagStoreService {
|
||||
@Resource
|
||||
private CpImageStoreSyncManager cpImageStoreSyncManager;
|
||||
@Resource
|
||||
private AtomicDeviceService atomicDeviceService;
|
||||
@Resource
|
||||
private AggDeviceImageStoreService aggDeviceImageStoreService;
|
||||
@Resource
|
||||
private DevicePersonSyncLogMapper devicePersonSyncLogMapper;
|
||||
@Resource
|
||||
private GroupPersonRefMapper groupPersonRefMapper;
|
||||
@Resource
|
||||
private DeviceImageStoreMapper deviceImageStoreMapper;
|
||||
@Value(value="${device.person.sync.time.diff.minutes:60}")
|
||||
private int beforeNowMinutes;
|
||||
@Value(value="${group-person.delete.keep.days:7}")
|
||||
private int keepDays;
|
||||
@Value(value="${device.group.pull.time.diff.minutes:10}")
|
||||
private int finishPullTimeBeforeNowMinutes;
|
||||
|
||||
public void executeResyncTask() {
|
||||
DevicePersonSyncLogDTO dto = new DevicePersonSyncLogDTO();
|
||||
Long lastReportTime = System.currentTimeMillis() - (long)(this.beforeNowMinutes * 60 * 1000);
|
||||
dto.setLastReportTime(lastReportTime);
|
||||
List list = this.devicePersonSyncLogMapper.queryException(dto);
|
||||
if (CollectionUtils.isEmpty((Collection)list)) {
|
||||
return;
|
||||
}
|
||||
HashSet changeGroupIdSet = Sets.newHashSet();
|
||||
list.forEach(syncLog -> {
|
||||
try {
|
||||
changeGroupIdSet.add(syncLog.getImageStoreId());
|
||||
DevicePersonSyncLog devicePersonSyncLog = new DevicePersonSyncLog();
|
||||
devicePersonSyncLog.setDeviceId(syncLog.getDeviceId());
|
||||
devicePersonSyncLog.setImageStoreId(syncLog.getImageStoreId());
|
||||
devicePersonSyncLog.setPersonId(syncLog.getPersonId());
|
||||
devicePersonSyncLog.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.devicePersonSyncLogMapper.resetSyncLog(devicePersonSyncLog);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("设备-人员同步定时器任务执行报错:{}", (Object)e.getMessage());
|
||||
}
|
||||
});
|
||||
this.cpImageStoreSyncManager.sendChangeToDevice(changeGroupIdSet, false);
|
||||
}
|
||||
|
||||
public void excuteDeleteDevicePerson() {
|
||||
Long lastUpdateTime = System.currentTimeMillis() - (long)(this.keepDays * 24 * 60 * 60) * 1000L;
|
||||
int res = this.devicePersonSyncLogMapper.deleteByTime(lastUpdateTime);
|
||||
this.logger.info("定时删除lastUpdateTime < {}的同步记录{}条", (Object)lastUpdateTime, (Object)res);
|
||||
lastUpdateTime = System.currentTimeMillis() - 2592000000L;
|
||||
res = this.groupPersonRefMapper.deleteByTime(lastUpdateTime);
|
||||
this.logger.info("定时删除status为删除,lastUpdateTime < {}图库人员记录{}条", (Object)lastUpdateTime, (Object)res);
|
||||
}
|
||||
|
||||
public void excuteNotifyDevice() throws ServiceException {
|
||||
CoreDeviceQueryParam deviceQueryParam = new CoreDeviceQueryParam();
|
||||
deviceQueryParam.setIdentifyType("0");
|
||||
CloudwalkResult result = this.atomicDeviceService.list(deviceQueryParam, this.getCloudwalkContext());
|
||||
if (!result.isSuccess()) {
|
||||
this.logger.debug("通知设备拉取,获取前端设备失败");
|
||||
throw new ServiceException(result.getCode(), result.getMessage());
|
||||
}
|
||||
List deviceList = (List)result.getData();
|
||||
if (CollectionUtils.isEmpty((Collection)deviceList)) {
|
||||
this.logger.debug("通知设备拉取,获取前端设备为空");
|
||||
return;
|
||||
}
|
||||
deviceList = deviceList.stream().filter(device -> StringUtils.isEmpty((CharSequence)device.getParentCode())).collect(Collectors.toList());
|
||||
HashMap deviceGroupsMap = new HashMap();
|
||||
for (AtomicDeviceGetResult atomicDeviceGetResult : deviceList) {
|
||||
DeviceImageStoreQueryParam storeQueryParam = new DeviceImageStoreQueryParam();
|
||||
storeQueryParam.setDeviceId(atomicDeviceGetResult.getId());
|
||||
CloudwalkResult imageStoreResult = this.aggDeviceImageStoreService.query(storeQueryParam, this.getCloudwalkContext());
|
||||
if (!imageStoreResult.isSuccess()) {
|
||||
this.logger.debug("通知设备拉取,根据设备[{}]获取关联图库失败", (Object)atomicDeviceGetResult.getId());
|
||||
continue;
|
||||
}
|
||||
List imageStoreList = (List)imageStoreResult.getData();
|
||||
if (CollectionUtils.isEmpty((Collection)imageStoreList)) {
|
||||
this.logger.debug("通知设备拉取,根据设备[{}]获取关联图库为空", (Object)atomicDeviceGetResult.getId());
|
||||
continue;
|
||||
}
|
||||
Set imageStoreIds = imageStoreList.stream().map(DeviceImageStoreQueryResult::getImageStoreId).collect(Collectors.toSet());
|
||||
deviceGroupsMap.put(atomicDeviceGetResult.getId(), imageStoreIds);
|
||||
}
|
||||
for (Map.Entry entry : deviceGroupsMap.entrySet()) {
|
||||
this.logger.debug("通知设备拉取,设备[{}]拉取图库[{}]", entry.getKey(), entry.getValue());
|
||||
this.cpImageStoreSyncManager.sendChangeToDevice((String)entry.getKey(), (Set)entry.getValue(), false);
|
||||
}
|
||||
}
|
||||
|
||||
public void executeUnbindDeviceImageStore() throws ServiceException {
|
||||
DeviceImageStore entity = new DeviceImageStore();
|
||||
entity.setLastUpdateTime(Long.valueOf(System.currentTimeMillis() - (long)(this.finishPullTimeBeforeNowMinutes * 60 * 1000)));
|
||||
List waitNotifyList = this.deviceImageStoreMapper.findNotifyList(entity);
|
||||
if (CollectionUtils.isEmpty((Collection)waitNotifyList)) {
|
||||
return;
|
||||
}
|
||||
HashMap deviceMap = new HashMap();
|
||||
AtomicDeviceCommonParam queryDevice = new AtomicDeviceCommonParam();
|
||||
DeviceImageStoreQueryParam storeQueryParam = new DeviceImageStoreQueryParam();
|
||||
waitNotifyList.stream().forEach(notify -> {
|
||||
try {
|
||||
if (!deviceMap.containsKey(notify.getDeviceId())) {
|
||||
queryDevice.setId(notify.getDeviceId());
|
||||
CloudwalkResult deviceResult = this.atomicDeviceService.detail(queryDevice, this.getCloudwalkContext());
|
||||
if (!deviceResult.isSuccess() || null == deviceResult.getData()) {
|
||||
this.logger.warn("查询设备[{}]失败", (Object)notify.getDeviceId());
|
||||
return;
|
||||
}
|
||||
deviceMap.put(notify.getDeviceId(), deviceResult.getData());
|
||||
}
|
||||
storeQueryParam.setDeviceId(notify.getDeviceId());
|
||||
CloudwalkResult imageStoreResult = this.aggDeviceImageStoreService.query(storeQueryParam, this.getCloudwalkContext());
|
||||
if (imageStoreResult.isSuccess() && !CollectionUtils.isEmpty((Collection)((Collection)imageStoreResult.getData()))) {
|
||||
this.logger.debug("设备[{}]仍绑定其他图库", (Object)notify.getDeviceId());
|
||||
CoreDeviceDetailResult device = (CoreDeviceDetailResult)deviceMap.get(notify.getDeviceId());
|
||||
if (null == device.getSupportMultiPersonGroup() || Objects.equals(device.getSupportMultiPersonGroup().intValue(), DeviceAbilityEnum.NOT_SUPPORT_MULTI_PERSON_GROUP.getCode())) {
|
||||
this.logger.debug("设备[{}]code[{}]不支持多图库,下发50009", (Object)notify.getDeviceId(), (Object)device.getDeviceCode());
|
||||
HashSet changeGroupIdSet = Sets.newHashSet();
|
||||
changeGroupIdSet.add(notify.getImageStoreId());
|
||||
((List)imageStoreResult.getData()).stream().forEach(imageStore -> {
|
||||
if (imageStore.getImageStoreId().equals(notify.getImageStoreId())) {
|
||||
return;
|
||||
}
|
||||
changeGroupIdSet.add(imageStore.getImageStoreId());
|
||||
});
|
||||
this.cpImageStoreSyncManager.sendChangeToDevice(notify.getDeviceId(), changeGroupIdSet, false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
this.logger.debug("设备[{}]图库[{}]下发50010", (Object)notify.getDeviceId(), (Object)notify.getImageStoreId());
|
||||
DeviceImageStoreReSyncParam deviceImageStoreReSyncParam = new DeviceImageStoreReSyncParam();
|
||||
deviceImageStoreReSyncParam.setDeviceId(notify.getDeviceId());
|
||||
deviceImageStoreReSyncParam.setImageStoreId(notify.getImageStoreId());
|
||||
CloudwalkResult result = this.aggDeviceImageStoreService.reSync(deviceImageStoreReSyncParam, this.getCloudwalkContext());
|
||||
if (result.isSuccess()) {
|
||||
notify.setStatus(StatusEnum.NOTIFY.getValue());
|
||||
notify.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.deviceImageStoreMapper.update(notify);
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("设备[{}]图库[{}]解绑异常:{}", new Object[]{notify.getDeviceId(), notify.getImageStoreId(), e.getMessage()});
|
||||
}
|
||||
});
|
||||
}
|
||||
extends AbstractImagStoreService
|
||||
{
|
||||
@Resource
|
||||
private CpImageStoreSyncManager cpImageStoreSyncManager;
|
||||
@Resource
|
||||
private AtomicDeviceService atomicDeviceService;
|
||||
@Resource
|
||||
private AggDeviceImageStoreService aggDeviceImageStoreService;
|
||||
@Resource
|
||||
private DevicePersonSyncLogMapper devicePersonSyncLogMapper;
|
||||
@Resource
|
||||
private GroupPersonRefMapper groupPersonRefMapper;
|
||||
@Resource
|
||||
private DeviceImageStoreMapper deviceImageStoreMapper;
|
||||
@Value("${device.person.sync.time.diff.minutes:60}")
|
||||
private int beforeNowMinutes;
|
||||
@Value("${group-person.delete.keep.days:7}")
|
||||
private int keepDays;
|
||||
@Value("${device.group.pull.time.diff.minutes:10}")
|
||||
private int finishPullTimeBeforeNowMinutes;
|
||||
public void executeResyncTask() {
|
||||
DevicePersonSyncLogDTO dto = new DevicePersonSyncLogDTO();
|
||||
Long lastReportTime = Long.valueOf(System.currentTimeMillis() - (this.beforeNowMinutes * 60 * 1000));
|
||||
dto.setLastReportTime(lastReportTime);
|
||||
List<DevicePersonSyncLog> list = this.devicePersonSyncLogMapper.queryException(dto);
|
||||
if (CollectionUtils.isEmpty(list)) {
|
||||
return;
|
||||
}
|
||||
Set<String> changeGroupIdSet = Sets.newHashSet();
|
||||
list.forEach(syncLog -> {
|
||||
try {
|
||||
changeGroupIdSet.add(syncLog.getImageStoreId());
|
||||
DevicePersonSyncLog devicePersonSyncLog = new DevicePersonSyncLog();
|
||||
devicePersonSyncLog.setDeviceId(syncLog.getDeviceId());
|
||||
devicePersonSyncLog.setImageStoreId(syncLog.getImageStoreId());
|
||||
devicePersonSyncLog.setPersonId(syncLog.getPersonId());
|
||||
devicePersonSyncLog.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.devicePersonSyncLogMapper.resetSyncLog(devicePersonSyncLog);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("设备-人员同步定时器任务执行报错:{}", e.getMessage());
|
||||
}
|
||||
});
|
||||
this.cpImageStoreSyncManager.sendChangeToDevice(changeGroupIdSet, false);
|
||||
}
|
||||
public void excuteDeleteDevicePerson() {
|
||||
Long lastUpdateTime = Long.valueOf(System.currentTimeMillis() - (this.keepDays * 24 * 60 * 60) * 1000L);
|
||||
int res = this.devicePersonSyncLogMapper.deleteByTime(lastUpdateTime);
|
||||
this.logger.info("定时删除lastUpdateTime < {}的同步记录{}条", lastUpdateTime, Integer.valueOf(res));
|
||||
lastUpdateTime = Long.valueOf(System.currentTimeMillis() - 2592000000L);
|
||||
res = this.groupPersonRefMapper.deleteByTime(lastUpdateTime);
|
||||
this.logger.info("定时删除status为删除,lastUpdateTime < {}图库人员记录{}条", lastUpdateTime, Integer.valueOf(res));
|
||||
}
|
||||
public void excuteNotifyDevice() throws ServiceException {
|
||||
CoreDeviceQueryParam deviceQueryParam = new CoreDeviceQueryParam();
|
||||
deviceQueryParam.setIdentifyType("0");
|
||||
CloudwalkResult<List<AtomicDeviceGetResult>> result = this.atomicDeviceService.list(deviceQueryParam, getCloudwalkContext());
|
||||
if (!result.isSuccess()) {
|
||||
this.logger.debug("通知设备拉取,获取前端设备失败");
|
||||
throw new ServiceException(result.getCode(), result.getMessage());
|
||||
}
|
||||
List<AtomicDeviceGetResult> deviceList = (List<AtomicDeviceGetResult>)result.getData();
|
||||
if (CollectionUtils.isEmpty(deviceList)) {
|
||||
this.logger.debug("通知设备拉取,获取前端设备为空");
|
||||
return;
|
||||
}
|
||||
deviceList = (List<AtomicDeviceGetResult>)deviceList.stream().filter(device -> StringUtils.isEmpty(device.getParentCode())).collect(Collectors.toList());
|
||||
Map<String, Set<String>> deviceGroupsMap = new HashMap<>();
|
||||
for (AtomicDeviceGetResult device : deviceList) {
|
||||
DeviceImageStoreQueryParam storeQueryParam = new DeviceImageStoreQueryParam();
|
||||
storeQueryParam.setDeviceId(device.getId());
|
||||
CloudwalkResult<List<DeviceImageStoreQueryResult>> imageStoreResult = this.aggDeviceImageStoreService.query(storeQueryParam, getCloudwalkContext());
|
||||
if (!imageStoreResult.isSuccess()) {
|
||||
this.logger.debug("通知设备拉取,根据设备[{}]获取关联图库失败", device.getId());
|
||||
continue;
|
||||
}
|
||||
List<DeviceImageStoreQueryResult> imageStoreList = (List<DeviceImageStoreQueryResult>)imageStoreResult.getData();
|
||||
if (CollectionUtils.isEmpty(imageStoreList)) {
|
||||
this.logger.debug("通知设备拉取,根据设备[{}]获取关联图库为空", device.getId());
|
||||
continue;
|
||||
}
|
||||
Set<String> imageStoreIds = (Set<String>)imageStoreList.stream().map(DeviceImageStoreQueryResult::getImageStoreId).collect(Collectors.toSet());
|
||||
deviceGroupsMap.put(device.getId(), imageStoreIds);
|
||||
}
|
||||
for (Map.Entry<String, Set<String>> entry : deviceGroupsMap.entrySet()) {
|
||||
this.logger.debug("通知设备拉取,设备[{}]拉取图库[{}]", entry.getKey(), entry.getValue());
|
||||
this.cpImageStoreSyncManager.sendChangeToDevice(entry.getKey(), entry.getValue(), false);
|
||||
}
|
||||
}
|
||||
public void executeUnbindDeviceImageStore() throws ServiceException {
|
||||
DeviceImageStore entity = new DeviceImageStore();
|
||||
entity.setLastUpdateTime(Long.valueOf(System.currentTimeMillis() - (this.finishPullTimeBeforeNowMinutes * 60 * 1000)));
|
||||
List<DeviceImageStore> waitNotifyList = this.deviceImageStoreMapper.findNotifyList(entity);
|
||||
if (CollectionUtils.isEmpty(waitNotifyList)) {
|
||||
return;
|
||||
}
|
||||
Map<String, CoreDeviceDetailResult> deviceMap = new HashMap<>();
|
||||
AtomicDeviceCommonParam queryDevice = new AtomicDeviceCommonParam();
|
||||
DeviceImageStoreQueryParam storeQueryParam = new DeviceImageStoreQueryParam();
|
||||
waitNotifyList.stream().forEach(notify -> {
|
||||
try {
|
||||
if (!deviceMap.containsKey(notify.getDeviceId())) {
|
||||
queryDevice.setId(notify.getDeviceId());
|
||||
CloudwalkResult<CoreDeviceDetailResult> deviceResult = this.atomicDeviceService.detail(queryDevice, getCloudwalkContext());
|
||||
if (!deviceResult.isSuccess() || null == deviceResult.getData()) {
|
||||
this.logger.warn("查询设备[{}]失败", notify.getDeviceId());
|
||||
return;
|
||||
}
|
||||
deviceMap.put(notify.getDeviceId(), deviceResult.getData());
|
||||
}
|
||||
storeQueryParam.setDeviceId(notify.getDeviceId());
|
||||
CloudwalkResult<List<DeviceImageStoreQueryResult>> imageStoreResult = this.aggDeviceImageStoreService.query(storeQueryParam, getCloudwalkContext());
|
||||
if (imageStoreResult.isSuccess() && !CollectionUtils.isEmpty((Collection)imageStoreResult.getData())) {
|
||||
this.logger.debug("设备[{}]仍绑定其他图库", notify.getDeviceId());
|
||||
CoreDeviceDetailResult device = (CoreDeviceDetailResult)deviceMap.get(notify.getDeviceId());
|
||||
if (null == device.getSupportMultiPersonGroup() || Objects.equals(Integer.valueOf(device.getSupportMultiPersonGroup().intValue()), Integer.valueOf(DeviceAbilityEnum.NOT_SUPPORT_MULTI_PERSON_GROUP.getCode()))) {
|
||||
this.logger.debug("设备[{}]code[{}]不支持多图库,下发50009", notify.getDeviceId(), device.getDeviceCode());
|
||||
Set<String> changeGroupIdSet = Sets.newHashSet();
|
||||
changeGroupIdSet.add(notify.getImageStoreId());
|
||||
((List)imageStoreResult.getData()).stream().forEach(imageStore -> changeGroupIdSet.add(((DeviceImageStoreQueryResult)imageStore).getImageStoreId()));
|
||||
this.cpImageStoreSyncManager.sendChangeToDevice(notify.getDeviceId(), changeGroupIdSet, false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
this.logger.debug("设备[{}]图库[{}]下发50010", notify.getDeviceId(), notify.getImageStoreId());
|
||||
DeviceImageStoreReSyncParam deviceImageStoreReSyncParam = new DeviceImageStoreReSyncParam();
|
||||
deviceImageStoreReSyncParam.setDeviceId(notify.getDeviceId());
|
||||
deviceImageStoreReSyncParam.setImageStoreId(notify.getImageStoreId());
|
||||
CloudwalkResult<List<DeviceImageStoreReSyncResult>> result = this.aggDeviceImageStoreService.reSync(deviceImageStoreReSyncParam, getCloudwalkContext());
|
||||
if (result.isSuccess()) {
|
||||
notify.setStatus(StatusEnum.NOTIFY.getValue());
|
||||
notify.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.deviceImageStoreMapper.update(notify);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
this.logger.error("设备[{}]图库[{}]解绑异常:{}", new Object[] { notify.getDeviceId(), notify.getImageStoreId(), e.getMessage() });
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/DevicePersonSyncManager.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+301
-287
@@ -38,6 +38,7 @@ import cn.cloudwalk.data.organization.entity.ImgStorePerson;
|
||||
import cn.cloudwalk.data.organization.mapper.DevicePersonSyncLogMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.GroupPersonRefMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonMapper;
|
||||
import cn.cloudwalk.data.organization.vo.DevicePersonSyncLogVO;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import cn.cloudwalk.service.organization.service.feign.ImageStoreSyncClient;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
@@ -48,7 +49,6 @@ import com.google.common.collect.Maps;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
@@ -60,294 +60,308 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springside.modules.utils.Collections3;
|
||||
|
||||
@Service
|
||||
public class DevicePersonSyncServiceImpl
|
||||
extends AbstractImagStoreService
|
||||
implements DevicePersonSyncService {
|
||||
@Resource
|
||||
private ImageStoreSyncClient imageStoreSyncClient;
|
||||
@Resource
|
||||
private AtomicDeviceService atomicDeviceService;
|
||||
@Resource
|
||||
private AggDeviceImageStoreService aggDeviceImageStoreService;
|
||||
@Resource
|
||||
private DeviceVersionService deviceVersionService;
|
||||
@Resource
|
||||
private ImgStorePersonMapper imgStorePersonMapper;
|
||||
@Resource
|
||||
private GroupPersonRefMapper groupPersonRefMapper;
|
||||
@Resource
|
||||
private DevicePersonSyncLogMapper devicePersonSyncLogMapper;
|
||||
@Value(value="${group-person.delete.keep.days:7}")
|
||||
private int keepDays;
|
||||
|
||||
public CloudwalkResult<CloudwalkPageAble<DeviceImageStoreSynLogQueryResult>> page(DeviceImageStoreSynLogQueryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
this.logger.info("图库同步记录详情分页查询参数:[{}]", (Object)JSON.toJSONString((Object)param));
|
||||
CloudwalkResult<CloudwalkPageAble<DeviceImageStoreSynLogQueryResult>> result = this.imageStoreSyncClient.page(param);
|
||||
this.logger.debug("图库同步记录详情分页查询结果:[{}]", (Object)JSON.toJSONString(result));
|
||||
if (!result.isSuccess()) {
|
||||
this.logger.warn("获取图库同步记录详情分页查询失败");
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
CloudwalkPageAble pageAble = (CloudwalkPageAble)result.getData();
|
||||
if (null != pageAble && !CollectionUtils.isEmpty((Collection)pageAble.getDatas())) {
|
||||
List queryList = (List)pageAble.getDatas();
|
||||
List resultList = BeanCopyUtils.copy((Collection)queryList, DeviceImageStoreSynLogResult.class);
|
||||
List personIdList = queryList.stream().map(DeviceImageStoreSynLogQueryResult::getPersonId).collect(Collectors.toList());
|
||||
ImgStorePersonQueryDto queryDto = new ImgStorePersonQueryDto();
|
||||
queryDto.setIds(personIdList);
|
||||
queryDto.setBusinessId(context.getCompany().getCompanyId());
|
||||
this.logger.debug("人员列表查询参数:[{}]", (Object)JSON.toJSONString((Object)queryDto));
|
||||
List personList = this.imgStorePersonMapper.gets(queryDto);
|
||||
this.logger.debug("人员列表查询结果:[{}]", (Object)JSON.toJSONString((Object)personList));
|
||||
Map<String, ImgStorePerson> personMap = personList.stream().collect(Collectors.toMap(ImgStorePerson::getId, a -> a, (k1, k2) -> k1));
|
||||
this.logger.debug("人员列表查询结果Map:[{}]", (Object)JSON.toJSONString(personMap));
|
||||
resultList.forEach(synLogResult -> {
|
||||
synLogResult.setImageUrl(((ImgStorePerson)personMap.get(synLogResult.getPersonId())).getComparePicture());
|
||||
synLogResult.setName(((ImgStorePerson)personMap.get(synLogResult.getPersonId())).getName());
|
||||
});
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public CloudwalkResult<CloudwalkPageAble<AtomicDeviceGetResult>> devicePage(QueryDevicePersonSyncParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
long start = System.currentTimeMillis();
|
||||
CloudwalkPageInfo page = new CloudwalkPageInfo(param.getCurrentPage(), param.getRowsOfPage());
|
||||
String businessId = param.getBusinessId();
|
||||
if (StringUtils.isEmpty((Object)businessId)) {
|
||||
businessId = this.getCloudwalkContext().getCompany().getCompanyId();
|
||||
}
|
||||
CoreDeviceQueryParam deviceQueryParam = new CoreDeviceQueryParam();
|
||||
deviceQueryParam.setBusinessId(businessId);
|
||||
deviceQueryParam.setDeviceCode(param.getDeviceCode());
|
||||
deviceQueryParam.setDeviceName(param.getDeviceName());
|
||||
deviceQueryParam.setIdentifyType("0");
|
||||
deviceQueryParam.setCurrentPage(param.getCurrentPage());
|
||||
deviceQueryParam.setRowsOfPage(param.getRowsOfPage());
|
||||
CloudwalkResult deviceListResult = this.atomicDeviceService.list(deviceQueryParam, this.getCloudwalkContext());
|
||||
List<Object> deviceList = new ArrayList<AtomicDeviceGetResult>();
|
||||
if (deviceListResult.isSuccess()) {
|
||||
deviceList = ((List)deviceListResult.getData()).stream().filter(device -> StringUtils.isEmpty((Object)device.getParentCode())).collect(Collectors.toList());
|
||||
}
|
||||
long totalCount = deviceList.size();
|
||||
if (!CollectionUtils.isEmpty(deviceList)) {
|
||||
deviceList = DevicePersonSyncServiceImpl.pageBySubList(deviceList, param.getRowsOfPage(), param.getCurrentPage());
|
||||
}
|
||||
CloudwalkPageAble pageAble = new CloudwalkPageAble(deviceList, page, totalCount);
|
||||
long end = System.currentTimeMillis();
|
||||
this.logger.debug("查询当前租户设备列表耗时[{}]", (Object)(end - start));
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
public static List<AtomicDeviceGetResult> pageBySubList(List<AtomicDeviceGetResult> list, int pagesize, int currentPage) {
|
||||
int totalcount = list.size();
|
||||
int pagecount = 0;
|
||||
int m = totalcount % pagesize;
|
||||
pagecount = m > 0 ? totalcount / pagesize + 1 : totalcount / pagesize;
|
||||
List<AtomicDeviceGetResult> subList = m == 0 ? list.subList((currentPage - 1) * pagesize, pagesize * currentPage) : (currentPage == pagecount ? list.subList((currentPage - 1) * pagesize, totalcount) : list.subList((currentPage - 1) * pagesize, pagesize * currentPage));
|
||||
return subList;
|
||||
}
|
||||
|
||||
public CloudwalkResult<List<DeviceImageStoreQueryResult>> deviceImageStoreList(String deviceId, CloudwalkCallContext context) throws ServiceException {
|
||||
DeviceImageStoreQueryParam storeQueryParam = new DeviceImageStoreQueryParam();
|
||||
storeQueryParam.setDeviceId(deviceId);
|
||||
CloudwalkResult imageStoreResult = this.aggDeviceImageStoreService.query(storeQueryParam, this.getCloudwalkContext());
|
||||
if (!imageStoreResult.isSuccess()) {
|
||||
this.logger.warn("获取设备关联的图库失败");
|
||||
throw new ServiceException("53013551", this.getMessage("53013551"));
|
||||
}
|
||||
return imageStoreResult;
|
||||
}
|
||||
|
||||
public Map<String, DeviceImageStoreRefResult> deviceImageStoreMap(List<AtomicDeviceGetResult> deviceList) throws ServiceException {
|
||||
long start = System.currentTimeMillis();
|
||||
HashMap deviceStoreMap = Maps.newHashMap();
|
||||
deviceList.forEach(device -> {
|
||||
DeviceImageStoreQueryParam storeQueryParam = new DeviceImageStoreQueryParam();
|
||||
storeQueryParam.setDeviceId(device.getId());
|
||||
CloudwalkResult imageStoreResult = this.aggDeviceImageStoreService.query(storeQueryParam, this.getCloudwalkContext());
|
||||
DeviceImageStoreRefResult deviceImageStoreRef = new DeviceImageStoreRefResult();
|
||||
deviceImageStoreRef.setDevice(device);
|
||||
if (null != imageStoreResult && !CollectionUtils.isEmpty((Collection)((Collection)imageStoreResult.getData()))) {
|
||||
deviceImageStoreRef.setImageStoreList((List)imageStoreResult.getData());
|
||||
if (!deviceStoreMap.containsKey(device.getId())) {
|
||||
deviceStoreMap.put(device.getId(), deviceImageStoreRef);
|
||||
}
|
||||
} else {
|
||||
deviceStoreMap.put(device.getId(), deviceImageStoreRef);
|
||||
}
|
||||
});
|
||||
long end = System.currentTimeMillis();
|
||||
this.logger.debug("组装成设备-图库Map耗时[{}]", (Object)(end - start));
|
||||
return deviceStoreMap;
|
||||
}
|
||||
|
||||
public List<DevicePersonSyncResult> deviceSyncList(List<String> deviceIds, Map<String, DeviceImageStoreRefResult> deviceStoreMap) throws ServiceException {
|
||||
Map<String, Integer> syncFailMap = deviceIds.stream().collect(Collectors.toMap(deviceId -> deviceId, deviceId -> 0, (k1, k2) -> k1));
|
||||
long s1 = System.currentTimeMillis();
|
||||
List syncFailList = this.devicePersonSyncLogMapper.deviceSyncCount(deviceIds, Arrays.asList(SyncStatusEnum.SYNC_FAIL.getValue()));
|
||||
long e1 = System.currentTimeMillis();
|
||||
this.logger.debug("查询设备同步失败数耗时[{}]", (Object)(e1 - s1));
|
||||
syncFailList.forEach(syncFail -> {
|
||||
if (syncFailMap.containsKey(syncFail.getDeviceId())) {
|
||||
syncFailMap.put(syncFail.getDeviceId(), syncFail.getCount());
|
||||
}
|
||||
});
|
||||
ArrayList list = Lists.newArrayListWithCapacity((int)deviceIds.size());
|
||||
for (Map.Entry<String, DeviceImageStoreRefResult> entry : deviceStoreMap.entrySet()) {
|
||||
DevicePersonSyncResult result = new DevicePersonSyncResult();
|
||||
result.setDeviceId(entry.getValue().getDevice().getId());
|
||||
result.setDeviceCode(entry.getValue().getDevice().getDeviceCode());
|
||||
result.setDeviceName(entry.getValue().getDevice().getDeviceName());
|
||||
int validCount = 0;
|
||||
int failureCount = 0;
|
||||
if (!CollectionUtils.isEmpty((Collection)entry.getValue().getImageStoreList())) {
|
||||
long s2 = System.currentTimeMillis();
|
||||
List imageStoreIds = Collections3.extractToList((Collection)entry.getValue().getImageStoreList(), (String)"imageStoreId");
|
||||
validCount = this.groupPersonRefMapper.imageStoreCount(imageStoreIds, Arrays.asList((int)StatusEnum.PERSON_NORMAL.getValue()));
|
||||
failureCount = syncFailMap.get(result.getDeviceId());
|
||||
long e2 = System.currentTimeMillis();
|
||||
this.logger.debug("查询设备[{}]关联图库正常人员数耗时[{}]", (Object)entry.getKey(), (Object)(e2 - s2));
|
||||
}
|
||||
result.setValidCount(validCount);
|
||||
result.setFailureCount(failureCount);
|
||||
list.add(result);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public List<DevicePersonSyncDetailResult> imageStoreSyncList(String deviceId, List<String> imageStoreIds, Map<String, DeviceImageStoreQueryResult> imageStoreMap) throws ServiceException {
|
||||
Map<String, Integer> syncFailMap = imageStoreIds.stream().collect(Collectors.toMap(imageStoreId -> imageStoreId, imageStoreId -> 0));
|
||||
List syncFailList = this.devicePersonSyncLogMapper.imageStoreSyncCount(deviceId, imageStoreIds, Arrays.asList(SyncStatusEnum.SYNC_FAIL.getValue()));
|
||||
syncFailList.forEach(syncFail -> {
|
||||
if (syncFailMap.containsKey(syncFail.getImageStoreId())) {
|
||||
syncFailMap.put(syncFail.getImageStoreId(), syncFail.getCount());
|
||||
}
|
||||
});
|
||||
ArrayList list = Lists.newArrayListWithCapacity((int)imageStoreIds.size());
|
||||
for (Map.Entry<String, DeviceImageStoreQueryResult> entry : imageStoreMap.entrySet()) {
|
||||
DevicePersonSyncDetailResult result = new DevicePersonSyncDetailResult();
|
||||
result.setImageStoreId(entry.getKey());
|
||||
result.setImageStoreName(entry.getValue().getImageStoreName());
|
||||
int validCount = this.groupPersonRefMapper.imageStoreCount(Arrays.asList(entry.getKey()), Arrays.asList((int)StatusEnum.PERSON_NORMAL.getValue()));
|
||||
result.setValidCount(validCount);
|
||||
result.setFailureCount(syncFailMap.get(result.getImageStoreId()).intValue());
|
||||
list.add(result);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public CloudwalkResult<CloudwalkPageAble<DevicePersonSyncLogResult>> logPage(QueryDevicePersonSyncLogParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
CloudwalkPageAble pageAble = null;
|
||||
CloudwalkPageInfo page = new CloudwalkPageInfo(param.getCurrentPage(), param.getRowsOfPage());
|
||||
QueryDevicePersonSyncLogParam queryDevicePersonSyncLogParam = new QueryDevicePersonSyncLogParam();
|
||||
queryDevicePersonSyncLogParam.setDeviceId(param.getDeviceId());
|
||||
Map<String, String> imageStoreMap = this.deviceImageStoreMap(queryDevicePersonSyncLogParam, context);
|
||||
List imageStoreIds = imageStoreMap.entrySet().stream().map(e -> (String)e.getKey()).collect(Collectors.toList());
|
||||
if (CollectionUtils.isEmpty(imageStoreIds)) {
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
boolean supportValidDate = false;
|
||||
CoreDeviceQueryParam coreDeviceQueryParam = new CoreDeviceQueryParam();
|
||||
coreDeviceQueryParam.setId(param.getDeviceId());
|
||||
CloudwalkResult deviceQueryResult = this.atomicDeviceService.list(coreDeviceQueryParam, context);
|
||||
if (deviceQueryResult.isSuccess() && !CollectionUtils.isEmpty((Collection)((Collection)deviceQueryResult.getData()))) {
|
||||
DeviceVersionGetsParam deviceVersionGetsParam = new DeviceVersionGetsParam();
|
||||
deviceVersionGetsParam.setDeviceCodes(Arrays.asList(((AtomicDeviceGetResult)((List)deviceQueryResult.getData()).get(0)).getDeviceCode()));
|
||||
CloudwalkResult deviceVersionResult = this.deviceVersionService.gets(deviceVersionGetsParam, context);
|
||||
if (deviceQueryResult.isSuccess() && !CollectionUtils.isEmpty((Collection)((Collection)deviceVersionResult.getData())) && !StringUtils.isEmpty((Object)((DeviceVersionResult)((List)deviceVersionResult.getData()).get(0)).getSupportAbility()) && ((DeviceVersionResult)((List)deviceVersionResult.getData()).get(0)).getSupportAbility().equals("PERSON_VALIDDATE")) {
|
||||
supportValidDate = true;
|
||||
}
|
||||
}
|
||||
PageHelper.startPage((int)param.getCurrentPage(), (int)param.getRowsOfPage());
|
||||
DevicePersonSyncLogQueryDTO queryDTO = (DevicePersonSyncLogQueryDTO)BeanCopyUtils.copyProperties((Object)param, DevicePersonSyncLogQueryDTO.class);
|
||||
queryDTO.setDeviceId(param.getDeviceId());
|
||||
queryDTO.setImageStoreIds(imageStoreIds);
|
||||
queryDTO.setLastUpdateTime(System.currentTimeMillis() - (long)(this.keepDays * 24 * 60 * 60 * 1000));
|
||||
queryDTO.setSupportValidDate(supportValidDate);
|
||||
Page pageResult = (Page)this.devicePersonSyncLogMapper.syncLogList(queryDTO);
|
||||
List list = BeanCopyUtils.copy((Collection)pageResult.getResult(), DevicePersonSyncLogResult.class);
|
||||
for (DevicePersonSyncLogResult result : list) {
|
||||
result.setDeviceId(param.getDeviceId());
|
||||
result.setImageStoreName(imageStoreMap.get(result.getImageStoreId()));
|
||||
if (!supportValidDate) continue;
|
||||
result.setPersonStatus(Integer.valueOf(StatusEnum.INVALID.getValue()));
|
||||
if (!Objects.equals(result.getValidStatus(), (int)StatusEnum.PERSON_NORMAL.getValue()) && !Objects.equals(result.getValidStatus(), (int)StatusEnum.PERSON_INVALID.getValue())) continue;
|
||||
result.setPersonStatus(Integer.valueOf(StatusEnum.VALID.getValue()));
|
||||
}
|
||||
pageAble = new CloudwalkPageAble((Collection)list, page, pageResult.getTotal());
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor={Exception.class})
|
||||
public boolean deviceResync(DevicePersonResyncParam param, CloudwalkCallContext context) {
|
||||
DeviceImageStoreQueryParam storeQueryParam = new DeviceImageStoreQueryParam();
|
||||
storeQueryParam.setDeviceId(param.getDeviceId());
|
||||
CloudwalkResult imageStoreResult = this.aggDeviceImageStoreService.query(storeQueryParam, context);
|
||||
if (!imageStoreResult.isSuccess()) {
|
||||
this.logger.warn("获取设备关联的图库失败");
|
||||
}
|
||||
if (!CollectionUtils.isEmpty((Collection)((Collection)imageStoreResult.getData()))) {
|
||||
List imageStoreIds = ((List)imageStoreResult.getData()).stream().map(DeviceImageStoreQueryResult::getImageStoreId).collect(Collectors.toList());
|
||||
DevicePersonSyncLogDTO dto = new DevicePersonSyncLogDTO();
|
||||
dto.setDeviceId(param.getDeviceId());
|
||||
dto.setImageStoreIds(imageStoreIds);
|
||||
int updateLogRes = this.devicePersonSyncLogMapper.resetSyncLogByIds(dto);
|
||||
if (updateLogRes > 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor={Exception.class})
|
||||
public boolean devicePersonResync(DevicePersonResyncParam param) {
|
||||
Long currentTime = System.currentTimeMillis();
|
||||
DevicePersonSyncLog devicePersonSyncLog = new DevicePersonSyncLog();
|
||||
devicePersonSyncLog.setDeviceId(param.getDeviceId());
|
||||
devicePersonSyncLog.setImageStoreId(param.getImageStoreId());
|
||||
devicePersonSyncLog.setPersonId(param.getPersonId());
|
||||
devicePersonSyncLog.setLastUpdateTime(currentTime);
|
||||
int updateLogRes = this.devicePersonSyncLogMapper.resetSyncLog(devicePersonSyncLog);
|
||||
if (updateLogRes > 0) {
|
||||
this.groupPersonRefMapper.updateLastUpdateTimeByPersonIds(param.getImageStoreId(), Arrays.asList(param.getPersonId()), currentTime);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public Map<String, String> deviceImageStoreMap(QueryDevicePersonSyncLogParam param, CloudwalkCallContext context) {
|
||||
Map<Object, Object> imageStoreMap = Maps.newHashMap();
|
||||
DeviceImageStoreQueryParam storeQueryParam = new DeviceImageStoreQueryParam();
|
||||
storeQueryParam.setDeviceId(param.getDeviceId());
|
||||
CloudwalkResult imageStoreResult = this.aggDeviceImageStoreService.query(storeQueryParam, context);
|
||||
if (!imageStoreResult.isSuccess()) {
|
||||
this.logger.warn("获取设备关联的图库失败");
|
||||
}
|
||||
if (!CollectionUtils.isEmpty((Collection)((Collection)imageStoreResult.getData()))) {
|
||||
imageStoreMap = ((List)imageStoreResult.getData()).stream().collect(Collectors.toMap(result -> result.getImageStoreId(), result -> result.getImageStoreName()));
|
||||
}
|
||||
return imageStoreMap;
|
||||
}
|
||||
|
||||
public List<PersonGroupRelationsResult> personGroupRelations(PersonGroupRelationsRequestParam param) {
|
||||
List resultList = null;
|
||||
ImgStorePersonQueryDto queryPerson = new ImgStorePersonQueryDto();
|
||||
queryPerson.setImageIds((Collection)param.getImageIds());
|
||||
List personList = this.imgStorePersonMapper.getByImageId(queryPerson);
|
||||
if (CollectionUtils.isEmpty((Collection)personList)) {
|
||||
return resultList;
|
||||
}
|
||||
List personIds = personList.stream().map(ImgStorePerson::getId).collect(Collectors.toList());
|
||||
DevicePersonSyncLogDTO queryDTO = new DevicePersonSyncLogDTO();
|
||||
queryDTO.setPersonIds(personIds);
|
||||
List list = this.groupPersonRefMapper.personGroupRelations(queryDTO);
|
||||
if (!CollectionUtils.isEmpty((Collection)list)) {
|
||||
resultList = BeanCopyUtils.copy((Collection)list, PersonGroupRelationsResult.class);
|
||||
}
|
||||
return resultList;
|
||||
}
|
||||
implements DevicePersonSyncService
|
||||
{
|
||||
@Resource
|
||||
private ImageStoreSyncClient imageStoreSyncClient;
|
||||
@Resource
|
||||
private AtomicDeviceService atomicDeviceService;
|
||||
@Resource
|
||||
private AggDeviceImageStoreService aggDeviceImageStoreService;
|
||||
@Resource
|
||||
private DeviceVersionService deviceVersionService;
|
||||
@Resource
|
||||
private ImgStorePersonMapper imgStorePersonMapper;
|
||||
@Resource
|
||||
private GroupPersonRefMapper groupPersonRefMapper;
|
||||
@Resource
|
||||
private DevicePersonSyncLogMapper devicePersonSyncLogMapper;
|
||||
@Value("${group-person.delete.keep.days:7}")
|
||||
private int keepDays;
|
||||
public CloudwalkResult<CloudwalkPageAble<DeviceImageStoreSynLogQueryResult>> page(DeviceImageStoreSynLogQueryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
this.logger.info("图库同步记录详情分页查询参数:[{}]", JSON.toJSONString(param));
|
||||
CloudwalkResult<CloudwalkPageAble<DeviceImageStoreSynLogQueryResult>> result = this.imageStoreSyncClient.page(param);
|
||||
this.logger.debug("图库同步记录详情分页查询结果:[{}]", JSON.toJSONString(result));
|
||||
if (!result.isSuccess()) {
|
||||
this.logger.warn("获取图库同步记录详情分页查询失败");
|
||||
return CloudwalkResult.fail("53013549", getMessage("53013549"));
|
||||
}
|
||||
CloudwalkPageAble<DeviceImageStoreSynLogQueryResult> pageAble = (CloudwalkPageAble<DeviceImageStoreSynLogQueryResult>)result.getData();
|
||||
if (null != pageAble && !CollectionUtils.isEmpty(pageAble.getDatas())) {
|
||||
List<DeviceImageStoreSynLogQueryResult> queryList = (List<DeviceImageStoreSynLogQueryResult>)pageAble.getDatas();
|
||||
List<DeviceImageStoreSynLogResult> resultList = BeanCopyUtils.copy(queryList, DeviceImageStoreSynLogResult.class);
|
||||
List<String> personIdList = (List<String>)queryList.stream().map(DeviceImageStoreSynLogQueryResult::getPersonId).collect(Collectors.toList());
|
||||
ImgStorePersonQueryDto queryDto = new ImgStorePersonQueryDto();
|
||||
queryDto.setIds(personIdList);
|
||||
queryDto.setBusinessId(context.getCompany().getCompanyId());
|
||||
this.logger.debug("人员列表查询参数:[{}]", JSON.toJSONString(queryDto));
|
||||
List<ImgStorePerson> personList = this.imgStorePersonMapper.gets(queryDto);
|
||||
this.logger.debug("人员列表查询结果:[{}]", JSON.toJSONString(personList));
|
||||
Map<String, ImgStorePerson> personMap = (Map<String, ImgStorePerson>)personList.stream().collect(Collectors.toMap(ImgStorePerson::getId, a -> a, (k1, k2) -> k1));
|
||||
this.logger.debug("人员列表查询结果Map:[{}]", JSON.toJSONString(personMap));
|
||||
resultList.forEach(synLogResult -> {
|
||||
synLogResult.setImageUrl(((ImgStorePerson)personMap.get(synLogResult.getPersonId())).getComparePicture());
|
||||
synLogResult.setName(((ImgStorePerson)personMap.get(synLogResult.getPersonId())).getName());
|
||||
});
|
||||
return CloudwalkResult.success(new CloudwalkPageAble(resultList, new CloudwalkPageInfo(param.getCurrentPage(), param.getRowsOfPage()), pageAble.getTotalRows()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
public CloudwalkResult<CloudwalkPageAble<AtomicDeviceGetResult>> devicePage(QueryDevicePersonSyncParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
long start = System.currentTimeMillis();
|
||||
CloudwalkPageInfo page = new CloudwalkPageInfo(param.getCurrentPage(), param.getRowsOfPage());
|
||||
String businessId = param.getBusinessId();
|
||||
if (StringUtils.isEmpty(businessId)) {
|
||||
businessId = getCloudwalkContext().getCompany().getCompanyId();
|
||||
}
|
||||
CoreDeviceQueryParam deviceQueryParam = new CoreDeviceQueryParam();
|
||||
deviceQueryParam.setBusinessId(businessId);
|
||||
deviceQueryParam.setDeviceCode(param.getDeviceCode());
|
||||
deviceQueryParam.setDeviceName(param.getDeviceName());
|
||||
deviceQueryParam.setIdentifyType("0");
|
||||
deviceQueryParam.setCurrentPage(param.getCurrentPage());
|
||||
deviceQueryParam.setRowsOfPage(param.getRowsOfPage());
|
||||
CloudwalkResult<List<AtomicDeviceGetResult>> deviceListResult = this.atomicDeviceService.list(deviceQueryParam, getCloudwalkContext());
|
||||
List<AtomicDeviceGetResult> deviceList = new ArrayList<>();
|
||||
if (deviceListResult.isSuccess()) {
|
||||
deviceList = (List<AtomicDeviceGetResult>)((List)deviceListResult.getData()).stream().filter(device -> StringUtils.isEmpty(device.getParentCode())).collect(
|
||||
Collectors.toList());
|
||||
}
|
||||
long totalCount = deviceList.size();
|
||||
if (!CollectionUtils.isEmpty(deviceList)) {
|
||||
deviceList = pageBySubList(deviceList, param.getRowsOfPage(), param.getCurrentPage());
|
||||
}
|
||||
CloudwalkPageAble<AtomicDeviceGetResult> pageAble = new CloudwalkPageAble(deviceList, page, totalCount);
|
||||
long end = System.currentTimeMillis();
|
||||
this.logger.debug("查询当前租户设备列表耗时[{}]", Long.valueOf(end - start));
|
||||
return CloudwalkResult.success(pageAble);
|
||||
}
|
||||
public static List<AtomicDeviceGetResult> pageBySubList(List<AtomicDeviceGetResult> list, int pagesize, int currentPage) {
|
||||
List<AtomicDeviceGetResult> subList;
|
||||
int totalcount = list.size();
|
||||
int pagecount = 0;
|
||||
int m = totalcount % pagesize;
|
||||
if (m > 0) {
|
||||
pagecount = totalcount / pagesize + 1;
|
||||
} else {
|
||||
pagecount = totalcount / pagesize;
|
||||
}
|
||||
if (m == 0) {
|
||||
subList = list.subList((currentPage - 1) * pagesize, pagesize * currentPage);
|
||||
}
|
||||
else if (currentPage == pagecount) {
|
||||
subList = list.subList((currentPage - 1) * pagesize, totalcount);
|
||||
} else {
|
||||
subList = list.subList((currentPage - 1) * pagesize, pagesize * currentPage);
|
||||
}
|
||||
return subList;
|
||||
}
|
||||
public CloudwalkResult<List<DeviceImageStoreQueryResult>> deviceImageStoreList(String deviceId, CloudwalkCallContext context) throws ServiceException {
|
||||
DeviceImageStoreQueryParam storeQueryParam = new DeviceImageStoreQueryParam();
|
||||
storeQueryParam.setDeviceId(deviceId);
|
||||
CloudwalkResult<List<DeviceImageStoreQueryResult>> imageStoreResult = this.aggDeviceImageStoreService.query(storeQueryParam, getCloudwalkContext());
|
||||
if (!imageStoreResult.isSuccess()) {
|
||||
this.logger.warn("获取设备关联的图库失败");
|
||||
throw new ServiceException("53013551", getMessage("53013551"));
|
||||
}
|
||||
return imageStoreResult;
|
||||
}
|
||||
public Map<String, DeviceImageStoreRefResult> deviceImageStoreMap(List<AtomicDeviceGetResult> deviceList) throws ServiceException {
|
||||
long start = System.currentTimeMillis();
|
||||
Map<String, DeviceImageStoreRefResult> deviceStoreMap = Maps.newHashMap();
|
||||
deviceList.forEach(device -> {
|
||||
DeviceImageStoreQueryParam storeQueryParam = new DeviceImageStoreQueryParam();
|
||||
storeQueryParam.setDeviceId(device.getId());
|
||||
CloudwalkResult<List<DeviceImageStoreQueryResult>> imageStoreResult = this.aggDeviceImageStoreService.query(storeQueryParam, getCloudwalkContext());
|
||||
DeviceImageStoreRefResult deviceImageStoreRef = new DeviceImageStoreRefResult();
|
||||
deviceImageStoreRef.setDevice(device);
|
||||
if (null != imageStoreResult && !CollectionUtils.isEmpty((Collection)imageStoreResult.getData())) {
|
||||
deviceImageStoreRef.setImageStoreList((List)imageStoreResult.getData());
|
||||
if (!deviceStoreMap.containsKey(device.getId())) {
|
||||
deviceStoreMap.put(device.getId(), deviceImageStoreRef);
|
||||
}
|
||||
} else {
|
||||
deviceStoreMap.put(device.getId(), deviceImageStoreRef);
|
||||
}
|
||||
});
|
||||
long end = System.currentTimeMillis();
|
||||
this.logger.debug("组装成设备-图库Map耗时[{}]", Long.valueOf(end - start));
|
||||
return deviceStoreMap;
|
||||
}
|
||||
public List<DevicePersonSyncResult> deviceSyncList(List<String> deviceIds, Map<String, DeviceImageStoreRefResult> deviceStoreMap) throws ServiceException {
|
||||
Map<String, Integer> syncFailMap = (Map<String, Integer>)deviceIds.stream().collect(Collectors.toMap(deviceId -> deviceId, deviceId -> Integer.valueOf(0), (k1, k2) -> k1));
|
||||
long s1 = System.currentTimeMillis();
|
||||
List<DevicePersonSyncLogVO> syncFailList = this.devicePersonSyncLogMapper.deviceSyncCount(deviceIds, Arrays.asList(new Integer[] {
|
||||
Integer.valueOf(SyncStatusEnum.SYNC_FAIL.getValue()) }));
|
||||
long e1 = System.currentTimeMillis();
|
||||
this.logger.debug("查询设备同步失败数耗时[{}]", Long.valueOf(e1 - s1));
|
||||
syncFailList.forEach(syncFail -> {
|
||||
if (syncFailMap.containsKey(syncFail.getDeviceId())) {
|
||||
syncFailMap.put(syncFail.getDeviceId(), Integer.valueOf(syncFail.getCount()));
|
||||
}
|
||||
});
|
||||
List<DevicePersonSyncResult> list = Lists.newArrayListWithCapacity(deviceIds.size());
|
||||
for (Map.Entry<String, DeviceImageStoreRefResult> entry : deviceStoreMap.entrySet()) {
|
||||
DevicePersonSyncResult result = new DevicePersonSyncResult();
|
||||
result.setDeviceId(((DeviceImageStoreRefResult)entry.getValue()).getDevice().getId());
|
||||
result.setDeviceCode(((DeviceImageStoreRefResult)entry.getValue()).getDevice().getDeviceCode());
|
||||
result.setDeviceName(((DeviceImageStoreRefResult)entry.getValue()).getDevice().getDeviceName());
|
||||
int validCount = 0;
|
||||
int failureCount = 0;
|
||||
if (!CollectionUtils.isEmpty(((DeviceImageStoreRefResult)entry.getValue()).getImageStoreList())) {
|
||||
long s2 = System.currentTimeMillis();
|
||||
List<String> imageStoreIds = Collections3.extractToList(((DeviceImageStoreRefResult)entry.getValue()).getImageStoreList(), "imageStoreId");
|
||||
validCount = this.groupPersonRefMapper.imageStoreCount(imageStoreIds, Arrays.asList(new Integer[] { Integer.valueOf(StatusEnum.PERSON_NORMAL.getValue().intValue()) }));
|
||||
failureCount = ((Integer)syncFailMap.get(result.getDeviceId())).intValue();
|
||||
long e2 = System.currentTimeMillis();
|
||||
this.logger.debug("查询设备[{}]关联图库正常人员数耗时[{}]", entry.getKey(), Long.valueOf(e2 - s2));
|
||||
}
|
||||
result.setValidCount(validCount);
|
||||
result.setFailureCount(failureCount);
|
||||
list.add(result);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
public List<DevicePersonSyncDetailResult> imageStoreSyncList(String deviceId, List<String> imageStoreIds, Map<String, DeviceImageStoreQueryResult> imageStoreMap) throws ServiceException {
|
||||
Map<String, Integer> syncFailMap = (Map<String, Integer>)imageStoreIds.stream().collect(Collectors.toMap(imageStoreId -> imageStoreId, imageStoreId -> Integer.valueOf(0)));
|
||||
List<DevicePersonSyncLogVO> syncFailList = this.devicePersonSyncLogMapper.imageStoreSyncCount(deviceId, imageStoreIds, Arrays.asList(new Integer[] {
|
||||
Integer.valueOf(SyncStatusEnum.SYNC_FAIL.getValue()) }));
|
||||
syncFailList.forEach(syncFail -> {
|
||||
if (syncFailMap.containsKey(syncFail.getImageStoreId())) {
|
||||
syncFailMap.put(syncFail.getImageStoreId(), Integer.valueOf(syncFail.getCount()));
|
||||
}
|
||||
});
|
||||
List<DevicePersonSyncDetailResult> list = Lists.newArrayListWithCapacity(imageStoreIds.size());
|
||||
for (Map.Entry<String, DeviceImageStoreQueryResult> entry : imageStoreMap.entrySet()) {
|
||||
DevicePersonSyncDetailResult result = new DevicePersonSyncDetailResult();
|
||||
result.setImageStoreId(entry.getKey());
|
||||
result.setImageStoreName(((DeviceImageStoreQueryResult)entry.getValue()).getImageStoreName());
|
||||
int validCount = this.groupPersonRefMapper.imageStoreCount(Arrays.asList(new String[] { entry.getKey() }), Arrays.asList(new Integer[] { Integer.valueOf(StatusEnum.PERSON_NORMAL.getValue().intValue()) }));
|
||||
result.setValidCount(validCount);
|
||||
result.setFailureCount(((Integer)syncFailMap.get(result.getImageStoreId())).intValue());
|
||||
list.add(result);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
public CloudwalkResult<CloudwalkPageAble<DevicePersonSyncLogResult>> logPage(QueryDevicePersonSyncLogParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
CloudwalkPageAble<DevicePersonSyncLogResult> pageAble = null;
|
||||
CloudwalkPageInfo page = new CloudwalkPageInfo(param.getCurrentPage(), param.getRowsOfPage());
|
||||
QueryDevicePersonSyncLogParam queryDevicePersonSyncLogParam = new QueryDevicePersonSyncLogParam();
|
||||
queryDevicePersonSyncLogParam.setDeviceId(param.getDeviceId());
|
||||
Map<String, String> imageStoreMap = deviceImageStoreMap(queryDevicePersonSyncLogParam, context);
|
||||
List<String> imageStoreIds = (List<String>)imageStoreMap.entrySet().stream().map(e -> (String)e.getKey()).collect(Collectors.toList());
|
||||
if (CollectionUtils.isEmpty(imageStoreIds)) {
|
||||
return CloudwalkResult.success(pageAble);
|
||||
}
|
||||
boolean supportValidDate = false;
|
||||
CoreDeviceQueryParam coreDeviceQueryParam = new CoreDeviceQueryParam();
|
||||
coreDeviceQueryParam.setId(param.getDeviceId());
|
||||
CloudwalkResult<List<AtomicDeviceGetResult>> deviceQueryResult = this.atomicDeviceService.list(coreDeviceQueryParam, context);
|
||||
if (deviceQueryResult.isSuccess() && !CollectionUtils.isEmpty((Collection)deviceQueryResult.getData())) {
|
||||
DeviceVersionGetsParam deviceVersionGetsParam = new DeviceVersionGetsParam();
|
||||
deviceVersionGetsParam.setDeviceCodes(Arrays.asList(new String[] { ((AtomicDeviceGetResult)((List<AtomicDeviceGetResult>)deviceQueryResult.getData()).get(0)).getDeviceCode() }));
|
||||
CloudwalkResult<List<DeviceVersionResult>> deviceVersionResult = this.deviceVersionService.gets(deviceVersionGetsParam, context);
|
||||
if (deviceQueryResult.isSuccess() &&
|
||||
!CollectionUtils.isEmpty((Collection)deviceVersionResult.getData()) &&
|
||||
!StringUtils.isEmpty(((DeviceVersionResult)((List<DeviceVersionResult>)deviceVersionResult.getData()).get(0)).getSupportAbility()) && ((DeviceVersionResult)((List<DeviceVersionResult>)deviceVersionResult
|
||||
.getData()).get(0)).getSupportAbility().equals("PERSON_VALIDDATE")) {
|
||||
supportValidDate = true;
|
||||
}
|
||||
}
|
||||
PageHelper.startPage(param.getCurrentPage(), param.getRowsOfPage());
|
||||
DevicePersonSyncLogQueryDTO queryDTO = (DevicePersonSyncLogQueryDTO)BeanCopyUtils.copyProperties(param, DevicePersonSyncLogQueryDTO.class);
|
||||
queryDTO.setDeviceId(param.getDeviceId());
|
||||
queryDTO.setImageStoreIds(imageStoreIds);
|
||||
queryDTO.setLastUpdateTime(System.currentTimeMillis() - (this.keepDays * 24 * 60 * 60 * 1000));
|
||||
queryDTO.setSupportValidDate(supportValidDate);
|
||||
Page<DevicePersonSyncLogVO> pageResult = (Page<DevicePersonSyncLogVO>)this.devicePersonSyncLogMapper.syncLogList(queryDTO);
|
||||
List<DevicePersonSyncLogResult> list = BeanCopyUtils.copy(pageResult.getResult(), DevicePersonSyncLogResult.class);
|
||||
for (DevicePersonSyncLogResult result : list) {
|
||||
result.setDeviceId(param.getDeviceId());
|
||||
result.setImageStoreName(imageStoreMap.get(result.getImageStoreId()));
|
||||
if (supportValidDate) {
|
||||
result.setPersonStatus(Integer.valueOf(StatusEnum.INVALID.getValue().intValue()));
|
||||
if (Objects.equals(Integer.valueOf(result.getValidStatus()), Integer.valueOf(StatusEnum.PERSON_NORMAL.getValue().intValue())) ||
|
||||
Objects.equals(Integer.valueOf(result.getValidStatus()), Integer.valueOf(StatusEnum.PERSON_INVALID.getValue().intValue()))) {
|
||||
result.setPersonStatus(Integer.valueOf(StatusEnum.VALID.getValue().intValue()));
|
||||
}
|
||||
}
|
||||
}
|
||||
pageAble = new CloudwalkPageAble(list, page, pageResult.getTotal());
|
||||
return CloudwalkResult.success(pageAble);
|
||||
}
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
public boolean deviceResync(DevicePersonResyncParam param, CloudwalkCallContext context) {
|
||||
DeviceImageStoreQueryParam storeQueryParam = new DeviceImageStoreQueryParam();
|
||||
storeQueryParam.setDeviceId(param.getDeviceId());
|
||||
CloudwalkResult<List<DeviceImageStoreQueryResult>> imageStoreResult = this.aggDeviceImageStoreService.query(storeQueryParam, context);
|
||||
if (!imageStoreResult.isSuccess()) {
|
||||
this.logger.warn("获取设备关联的图库失败");
|
||||
}
|
||||
if (!CollectionUtils.isEmpty((Collection)imageStoreResult.getData())) {
|
||||
List<String> imageStoreIds = (List<String>)((List)imageStoreResult.getData()).stream().map(DeviceImageStoreQueryResult::getImageStoreId).collect(Collectors.toList());
|
||||
DevicePersonSyncLogDTO dto = new DevicePersonSyncLogDTO();
|
||||
dto.setDeviceId(param.getDeviceId());
|
||||
dto.setImageStoreIds(imageStoreIds);
|
||||
int updateLogRes = this.devicePersonSyncLogMapper.resetSyncLogByIds(dto);
|
||||
if (updateLogRes > 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
public boolean devicePersonResync(DevicePersonResyncParam param) {
|
||||
Long currentTime = Long.valueOf(System.currentTimeMillis());
|
||||
DevicePersonSyncLog devicePersonSyncLog = new DevicePersonSyncLog();
|
||||
devicePersonSyncLog.setDeviceId(param.getDeviceId());
|
||||
devicePersonSyncLog.setImageStoreId(param.getImageStoreId());
|
||||
devicePersonSyncLog.setPersonId(param.getPersonId());
|
||||
devicePersonSyncLog.setLastUpdateTime(currentTime);
|
||||
int updateLogRes = this.devicePersonSyncLogMapper.resetSyncLog(devicePersonSyncLog);
|
||||
if (updateLogRes > 0) {
|
||||
this.groupPersonRefMapper.updateLastUpdateTimeByPersonIds(param.getImageStoreId(), Arrays.asList(new String[] { param.getPersonId() }), currentTime);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public Map<String, String> deviceImageStoreMap(QueryDevicePersonSyncLogParam param, CloudwalkCallContext context) {
|
||||
Map<String, String> imageStoreMap = Maps.newHashMap();
|
||||
DeviceImageStoreQueryParam storeQueryParam = new DeviceImageStoreQueryParam();
|
||||
storeQueryParam.setDeviceId(param.getDeviceId());
|
||||
CloudwalkResult<List<DeviceImageStoreQueryResult>> imageStoreResult = this.aggDeviceImageStoreService.query(storeQueryParam, context);
|
||||
if (!imageStoreResult.isSuccess()) {
|
||||
this.logger.warn("获取设备关联的图库失败");
|
||||
}
|
||||
if (!CollectionUtils.isEmpty((Collection)imageStoreResult.getData())) {
|
||||
imageStoreMap = (Map<String, String>)((List)imageStoreResult.getData()).stream().collect(Collectors.toMap(result -> result.getImageStoreId(), result -> result.getImageStoreName()));
|
||||
}
|
||||
return imageStoreMap;
|
||||
}
|
||||
public List<PersonGroupRelationsResult> personGroupRelations(PersonGroupRelationsRequestParam param) {
|
||||
List<PersonGroupRelationsResult> resultList = null;
|
||||
ImgStorePersonQueryDto queryPerson = new ImgStorePersonQueryDto();
|
||||
queryPerson.setImageIds(param.getImageIds());
|
||||
List<ImgStorePerson> personList = this.imgStorePersonMapper.getByImageId(queryPerson);
|
||||
if (CollectionUtils.isEmpty(personList)) {
|
||||
return resultList;
|
||||
}
|
||||
List<String> personIds = (List<String>)personList.stream().map(ImgStorePerson::getId).collect(Collectors.toList());
|
||||
DevicePersonSyncLogDTO queryDTO = new DevicePersonSyncLogDTO();
|
||||
queryDTO.setPersonIds(personIds);
|
||||
List<DevicePersonSyncLogVO> list = this.groupPersonRefMapper.personGroupRelations(queryDTO);
|
||||
if (!CollectionUtils.isEmpty(list)) {
|
||||
resultList = BeanCopyUtils.copy(list, PersonGroupRelationsResult.class);
|
||||
}
|
||||
return resultList;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/DevicePersonSyncServiceImpl.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.batch.param.BatchDetailInsertBatchParam;
|
||||
import cn.cloudwalk.client.organization.batch.param.BatchDetailQueryParam;
|
||||
import cn.cloudwalk.client.organization.batch.result.BatchDetailResult;
|
||||
import cn.cloudwalk.client.organization.batch.service.ImgPersonBatchDetailService;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkCallContext;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
import cn.cloudwalk.cloud.page.CloudwalkPageAble;
|
||||
import cn.cloudwalk.cloud.page.CloudwalkPageInfo;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.cloud.utils.BeanCopyUtils;
|
||||
import cn.cloudwalk.data.organization.entity.BatchDetail;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgPersonBatchDetailMapper;
|
||||
import com.github.pagehelper.Page;
|
||||
import com.github.pagehelper.PageHelper;
|
||||
import java.util.List;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
@Service
|
||||
public class ImgPersonBatchDetailServiceImpl
|
||||
implements ImgPersonBatchDetailService
|
||||
{
|
||||
private Logger logger = LoggerFactory.getLogger(getClass());
|
||||
@Autowired
|
||||
private ImgPersonBatchDetailMapper imgPersonBatchDetailMapper;
|
||||
public CloudwalkResult<CloudwalkPageAble<BatchDetailResult>> page(BatchDetailQueryParam param, CloudwalkPageInfo page, CloudwalkCallContext context) throws ServiceException {
|
||||
BatchDetail batchDetail = (BatchDetail)BeanCopyUtils.copyProperties(param, new BatchDetail());
|
||||
CloudwalkPageAble<BatchDetail> pageAble = null;
|
||||
try {
|
||||
PageHelper.startPage(page.getCurrentPage(), page.getPageSize());
|
||||
Page<BatchDetail> page1 = (Page<BatchDetail>)this.imgPersonBatchDetailMapper.page(batchDetail);
|
||||
pageAble = new CloudwalkPageAble(page1.getResult(), page, page1.getTotal());
|
||||
} catch (Exception e) {
|
||||
this.logger.error("导入详情查询失败,原因:", e);
|
||||
throw new ServiceException(e);
|
||||
}
|
||||
List<BatchDetailResult> result = BeanCopyUtils.copy(pageAble.getDatas(), BatchDetailResult.class);
|
||||
return CloudwalkResult.success(new CloudwalkPageAble(result, page, pageAble.getTotalRows()));
|
||||
}
|
||||
public CloudwalkResult<Integer> insertBatch(List<BatchDetailInsertBatchParam> batchDetails) {
|
||||
if (!CollectionUtils.isEmpty(batchDetails)) {
|
||||
List<BatchDetail> list = BeanCopyUtils.copy(batchDetails, BatchDetail.class);
|
||||
return CloudwalkResult.success(Integer.valueOf(this.imgPersonBatchDetailMapper.insertBatch(list)));
|
||||
}
|
||||
return CloudwalkResult.success(Integer.valueOf(batchDetails.size()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/ImgPersonBatchDetailServiceImpl.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+544
@@ -0,0 +1,544 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.aggregate.common.enums.DelStatusEnum;
|
||||
import cn.cloudwalk.client.organization.batch.param.BatchDetailInsertBatchParam;
|
||||
import cn.cloudwalk.client.organization.batch.param.BatchImportQueryParam;
|
||||
import cn.cloudwalk.client.organization.batch.result.BatchImportQueryResult;
|
||||
import cn.cloudwalk.client.organization.batch.service.ImgPersonBatchDetailService;
|
||||
import cn.cloudwalk.client.organization.batch.service.ImgPersonBatchService;
|
||||
import cn.cloudwalk.client.organization.common.constant.ImageStoreConstants;
|
||||
import cn.cloudwalk.client.organization.common.enums.CpPersonSourceEnum;
|
||||
import cn.cloudwalk.client.organization.common.exception.ImageStoreException;
|
||||
import cn.cloudwalk.client.organization.personimg.param.AddImgPersonParam;
|
||||
import cn.cloudwalk.client.organization.personimg.param.BatchImportParam;
|
||||
import cn.cloudwalk.client.organization.result.ZoneResult;
|
||||
import cn.cloudwalk.client.organization.service.PersonFileService;
|
||||
import cn.cloudwalk.client.organization.service.PictureRevisionService;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkCallContext;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
import cn.cloudwalk.cloud.page.CloudwalkPageAble;
|
||||
import cn.cloudwalk.cloud.page.CloudwalkPageInfo;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.cloud.serial.UUIDSerial;
|
||||
import cn.cloudwalk.cloud.utils.BeanCopyUtils;
|
||||
import cn.cloudwalk.cloud.utils.CloudwalkDateUtils;
|
||||
import cn.cloudwalk.component.client.resource.ext.user.param.PortalUserAccountBatchAddParam;
|
||||
import cn.cloudwalk.component.client.resource.ext.user.result.PortalUserAccountBatchAddResult;
|
||||
import cn.cloudwalk.component.client.resource.ext.user.service.PortalUserService;
|
||||
import cn.cloudwalk.data.organization.entity.BatchImport;
|
||||
import cn.cloudwalk.data.organization.entity.ImgStorePerson;
|
||||
import cn.cloudwalk.data.organization.entity.ImgStorePersonLabel;
|
||||
import cn.cloudwalk.data.organization.entity.ImgStorePersonOrganization;
|
||||
import cn.cloudwalk.data.organization.entity.ImgStorePersonProperties;
|
||||
import cn.cloudwalk.data.organization.entity.Label;
|
||||
import cn.cloudwalk.data.organization.entity.Organization;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonPropertiesMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.PersonBatchImportMapper;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import cn.cloudwalk.service.organization.common.OpenCvUtils;
|
||||
import cn.cloudwalk.service.organization.schedule.BatchImportContext;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.github.pagehelper.Page;
|
||||
import com.github.pagehelper.PageHelper;
|
||||
import com.google.common.collect.Sets;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Resource;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springside.modules.utils.Collections3;
|
||||
@Service
|
||||
public class ImgPersonBatchServiceImpl
|
||||
extends AbstractImagStoreService
|
||||
implements ImgPersonBatchService
|
||||
{
|
||||
private final String ORG_NAME = "organizationIds";
|
||||
private final String LABEL_NAME = "labelIds";
|
||||
private final String floorName = "floorName";
|
||||
private final String floorNames = "floorNames";
|
||||
private final String COMPARE_PICTURE_NAME = "comparePicture";
|
||||
private final String PHONE_REGEXP = "^[1][3,4,5,6,7,8,9][0-9]{9}$";
|
||||
private final String EMAIL_REGEXP = "^[A-Za-z0-9]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
|
||||
private final String NO_CHINESE_REGEXP = "^[^\\u4e00-\\u9fa5]+$";
|
||||
@Autowired
|
||||
private MessageSource messageSource;
|
||||
@Autowired
|
||||
private PersonBatchImportMapper personBatchImportMapper;
|
||||
@Autowired
|
||||
private ImgPersonBatchDetailService imgPersonBatchDetailService;
|
||||
@Autowired
|
||||
private UUIDSerial uuidSerial;
|
||||
@Autowired
|
||||
private ImgPersonManager imgPersonManager;
|
||||
@Autowired
|
||||
private OpenCvUtils openCvUtils;
|
||||
@Autowired
|
||||
private PictureRevisionService pictureRevisionService;
|
||||
@Autowired
|
||||
private PortalUserService portalUserService;
|
||||
@Autowired
|
||||
private CpImageStorePersonSynManager cpImageStorePersonSynManager;
|
||||
@Value("${imageQualityScore}")
|
||||
private Double imgQualityScore;
|
||||
@Resource
|
||||
private PersonFileService personFileService;
|
||||
@Resource
|
||||
private ImgStorePersonPropertiesMapper propertiesMapper;
|
||||
public <T> void handlerBatchPersonImport(List<List<String>> batchRecordList, T context, String filePath) {
|
||||
BatchImportContext importContext = (BatchImportContext)context;
|
||||
List<BatchDetailInsertBatchParam> batchDetailInsertBatchParams = new ArrayList<>(batchRecordList.size());
|
||||
List<AddImgPersonParam> personParamList = generatePersonParams(batchRecordList, filePath, importContext, batchDetailInsertBatchParams);
|
||||
List<ImgStorePerson> needInsertList = new ArrayList<>(personParamList.size());
|
||||
List<ImgStorePersonOrganization> personOrganizationList = new ArrayList<>(personParamList.size());
|
||||
List<ImgStorePersonLabel> personLabelList = new ArrayList<>(personParamList.size());
|
||||
List<ImgStorePerson> needCreateAccountList = new ArrayList<>(personParamList.size());
|
||||
personParamsToEntity(importContext, batchDetailInsertBatchParams, personParamList, needInsertList, personOrganizationList, personLabelList, needCreateAccountList);
|
||||
try {
|
||||
if (!CollectionUtils.isEmpty(needCreateAccountList)) {
|
||||
List<PortalUserAccountBatchAddResult.ErrorInfo> errorInfoList = addUserAccountUsePortal(importContext, needCreateAccountList);
|
||||
if (!CollectionUtils.isEmpty(errorInfoList)) {
|
||||
List<String> errorPersonIdList = Collections3.extractToList(errorInfoList, "personId");
|
||||
removeErrorEntity(needInsertList, personOrganizationList, personLabelList, errorPersonIdList);
|
||||
for (PortalUserAccountBatchAddResult.ErrorInfo errorInfo : errorInfoList) {
|
||||
batchDetailInsertBatchParams.add(generateBatchDetail(importContext, errorInfo
|
||||
.getPersonName(), errorInfo.getErrorMsg(), 2));
|
||||
}
|
||||
}
|
||||
}
|
||||
this.imgPersonManager.batchInsertWithTx(needInsertList, personOrganizationList, personLabelList);
|
||||
List<String> batchInsertPersonIds = (List<String>)needInsertList.parallelStream().map(ImgStorePerson::getId).collect(
|
||||
Collectors.toList());
|
||||
Set<String> imageIdResultSet = Sets.newHashSet();
|
||||
batchInsertPersonIds.parallelStream().forEach(personId -> imageIdResultSet.addAll(this.cpImageStorePersonSynManager.addGroupPersonSynTask(personId)));
|
||||
if (Collections3.isNotEmpty(imageIdResultSet)) {
|
||||
imageIdResultSet.parallelStream()
|
||||
.forEach(imageId -> this.cpImageStorePersonSynManager.handleGroupPersonSynTask(imageId));
|
||||
}
|
||||
for (ImgStorePerson storePerson : needInsertList) {
|
||||
batchDetailInsertBatchParams.add(generateBatchDetail(importContext, storePerson.getName(), "", 1));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
this.logger.error("person import data insert exception", e);
|
||||
for (ImgStorePerson storePerson : needInsertList) {
|
||||
batchDetailInsertBatchParams
|
||||
.add(generateBatchDetail(importContext, storePerson.getName(), "数据插入异常", 2));
|
||||
}
|
||||
needInsertList.clear();
|
||||
}
|
||||
try {
|
||||
this.imgPersonBatchDetailService.insertBatch(batchDetailInsertBatchParams);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("---person import batch detail insert exception", e);
|
||||
}
|
||||
importContext.getSuccessCount().getAndAdd(needInsertList.size());
|
||||
importContext.getFailCount().getAndAdd((batchDetailInsertBatchParams.size() - needInsertList.size()));
|
||||
}
|
||||
private List<PortalUserAccountBatchAddResult.ErrorInfo> addUserAccountUsePortal(BatchImportContext importContext, List<ImgStorePerson> needCreateAccountList) throws ServiceException {
|
||||
PortalUserAccountBatchAddParam userAccountBatchAddParam = new PortalUserAccountBatchAddParam();
|
||||
userAccountBatchAddParam.setBusinessId(importContext.getBatchImport().getBusinessId());
|
||||
userAccountBatchAddParam.setUserInfos(generateUserInfo(needCreateAccountList));
|
||||
CloudwalkResult<PortalUserAccountBatchAddResult> batchAddResult = this.portalUserService.batchAdd(userAccountBatchAddParam);
|
||||
if (!batchAddResult.isSuccess()) {
|
||||
this.logger.error("call cwos add user account failed, result:[{}]", JSON.toJSONString(batchAddResult));
|
||||
throw new ServiceException(batchAddResult.getCode(), batchAddResult.getMessage());
|
||||
}
|
||||
return ((PortalUserAccountBatchAddResult)batchAddResult.getData()).getErrorInfoList();
|
||||
}
|
||||
private List<PortalUserAccountBatchAddParam.UserInfo> generateUserInfo(List<ImgStorePerson> needInsertList) {
|
||||
List<PortalUserAccountBatchAddParam.UserInfo> userInfoList = new ArrayList<>(needInsertList.size());
|
||||
for (ImgStorePerson imgStorePerson : needInsertList) {
|
||||
PortalUserAccountBatchAddParam.UserInfo userInfo = new PortalUserAccountBatchAddParam.UserInfo();
|
||||
userInfo.setPersonId(imgStorePerson.getId());
|
||||
userInfo.setSystemId(imgStorePerson.getSysAccountId());
|
||||
userInfo.setName(imgStorePerson.getName());
|
||||
userInfo.setUserName(imgStorePerson.getUserName());
|
||||
userInfo.setEmail(imgStorePerson.getEmail());
|
||||
userInfo.setPhone(imgStorePerson.getPhone());
|
||||
userInfo.setPersonCode(imgStorePerson.getPersonCode());
|
||||
userInfo.setCorpAdmin(Short.valueOf((short)2));
|
||||
userInfo.setUserLevel(Short.valueOf((short)3));
|
||||
userInfoList.add(userInfo);
|
||||
}
|
||||
return userInfoList;
|
||||
}
|
||||
private void removeErrorEntity(List<ImgStorePerson> needInsertList, List<ImgStorePersonOrganization> personOrganizationList, List<ImgStorePersonLabel> personLabelList, List<String> errorPersonIdList) {
|
||||
needInsertList.removeIf(next -> errorPersonIdList.contains(next.getId()));
|
||||
personLabelList.removeIf(next -> errorPersonIdList.contains(next.getPersonId()));
|
||||
personOrganizationList.removeIf(next -> errorPersonIdList.contains(next.getPersonId()));
|
||||
}
|
||||
private void personParamsToEntity(BatchImportContext importContext, List<BatchDetailInsertBatchParam> batchDetailInsertBatchParams, List<AddImgPersonParam> personParamList, List<ImgStorePerson> needInsertList, List<ImgStorePersonOrganization> personOrganizationList, List<ImgStorePersonLabel> personLabelList, List<ImgStorePerson> needCreateAccoutList) {
|
||||
for (AddImgPersonParam personParam : personParamList) {
|
||||
try {
|
||||
ImgStorePerson imgStorePerson = generatePersonDTO(importContext, personParam);
|
||||
needInsertList.add(imgStorePerson);
|
||||
if (personParam.getCreateSysAccount() != null && personParam.getCreateSysAccount().intValue() == 1)
|
||||
{
|
||||
needCreateAccoutList.add(imgStorePerson);
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(personParam.getOrganizationIds())) {
|
||||
personOrganizationList.addAll(generatePersonOrganizations(imgStorePerson.getId(), personParam
|
||||
.getOrganizationIds(), importContext));
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(personParam.getLabelIds())) {
|
||||
personLabelList.addAll(generatePersonLabels(imgStorePerson.getId(), personParam.getLabelIds(), importContext));
|
||||
}
|
||||
}
|
||||
catch (ServiceException e) {
|
||||
this.logger.warn("package person data exception:{}", e.getMessage());
|
||||
batchDetailInsertBatchParams
|
||||
.add(generateBatchDetail(importContext, personParam.getName(), e.getMessage(), 2));
|
||||
} catch (Exception e) {
|
||||
this.logger.error("package person data exception:{}", e.getMessage());
|
||||
batchDetailInsertBatchParams
|
||||
.add(generateBatchDetail(importContext, personParam.getName(), "人员数据封装异常", 2));
|
||||
}
|
||||
}
|
||||
}
|
||||
private List<AddImgPersonParam> generatePersonParams(List<List<String>> batchRecordList, String filePath, BatchImportContext importContext, List<BatchDetailInsertBatchParam> batchDetailInsertBatchParams) {
|
||||
List<AddImgPersonParam> personParamList = new ArrayList<>(batchRecordList.size());
|
||||
AddImgPersonParam addPersonParam = null;
|
||||
for (List<String> record : batchRecordList) {
|
||||
addPersonParam = new AddImgPersonParam();
|
||||
try {
|
||||
checkRecordAndFillParam(record, importContext, filePath, addPersonParam);
|
||||
this.logger.info("addPersonParam after properties handle :[{}]", JSON.toJSONString(addPersonParam));
|
||||
personParamList.add(addPersonParam);
|
||||
} catch (ImageStoreException|ServiceException e) {
|
||||
batchDetailInsertBatchParams.add(generateBatchDetail(importContext, record.get(0), e.getMessage(), 2));
|
||||
} catch (Exception e) {
|
||||
this.logger.error("Batch import person,checkRecordAndFillParam exception:{}", e.getMessage());
|
||||
batchDetailInsertBatchParams.add(generateBatchDetail(importContext, record.get(0), "未知错误", 2));
|
||||
}
|
||||
}
|
||||
return personParamList;
|
||||
}
|
||||
private Collection<? extends ImgStorePersonLabel> generatePersonLabels(String personId, List<String> labelIds, BatchImportContext importContext) {
|
||||
List<ImgStorePersonLabel> personLabels = new ArrayList<>(labelIds.size());
|
||||
for (String labelId : labelIds) {
|
||||
ImgStorePersonLabel imgStorePersonLabel = new ImgStorePersonLabel();
|
||||
imgStorePersonLabel.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
imgStorePersonLabel.setCreateUserId(importContext.getBatchImport().getCreateUserId());
|
||||
imgStorePersonLabel.setLabelId(labelId);
|
||||
imgStorePersonLabel.setPersonId(personId);
|
||||
imgStorePersonLabel.setId(CloudwalkDateUtils.getUUID());
|
||||
personLabels.add(imgStorePersonLabel);
|
||||
}
|
||||
return personLabels;
|
||||
}
|
||||
private Collection<? extends ImgStorePersonOrganization> generatePersonOrganizations(String personId, List<String> organizationIds, BatchImportContext importContext) {
|
||||
List<ImgStorePersonOrganization> personOrganizations = new ArrayList<>(organizationIds.size());
|
||||
for (String orgId : organizationIds) {
|
||||
ImgStorePersonOrganization imgStorePersonOrganization = new ImgStorePersonOrganization();
|
||||
imgStorePersonOrganization.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
imgStorePersonOrganization.setCreateUserId(importContext.getBatchImport().getCreateUserId());
|
||||
imgStorePersonOrganization.setPersonId(personId);
|
||||
imgStorePersonOrganization.setOrgId(orgId);
|
||||
imgStorePersonOrganization.setId(CloudwalkDateUtils.getUUID());
|
||||
personOrganizations.add(imgStorePersonOrganization);
|
||||
}
|
||||
return personOrganizations;
|
||||
}
|
||||
private ImgStorePerson generatePersonDTO(BatchImportContext importContext, AddImgPersonParam personParam) throws ServiceException {
|
||||
ImgStorePerson personDto = new ImgStorePerson();
|
||||
BeanCopyUtils.copyProperties(personParam, personDto);
|
||||
personDto.setId(this.uuidSerial.uuid());
|
||||
if (!StringUtils.isEmpty(personParam.getComparePicture())) {
|
||||
personDto.setImageId(this.imgPersonManager.addAgImage(personParam.getComparePicture(), getCloudwalkContext()));
|
||||
}
|
||||
personDto.setComparePicture(personParam.getComparePicture());
|
||||
personDto.setBusinessId(importContext.getBatchImport().getBusinessId());
|
||||
personDto.setCreateUserId(importContext.getBatchImport().getCreateUserId());
|
||||
personDto.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
personDto.setStatus(Short.valueOf((short)0));
|
||||
personDto.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
personDto.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
personDto.setLastUpdateUserId(importContext.getBatchImport().getCreateUserId());
|
||||
personDto
|
||||
.setCreateSysAccount(Short.valueOf((personParam.getCreateSysAccount() == null) ? 0 : personParam.getCreateSysAccount().shortValue()));
|
||||
personDto.setSysAccountId(personParam.getSysAccountId());
|
||||
personDto.setSource(CpPersonSourceEnum.PAGE.getCode());
|
||||
personDto.setIcCardNo(personParam.getIcCardNo());
|
||||
personDto.setIcCardType(personParam.getIcCardType());
|
||||
personDto.setWelcome(personParam.getWelcome());
|
||||
personDto.setReserveInfo(personParam.getReserveInfo());
|
||||
return personDto;
|
||||
}
|
||||
private void checkRecordAndFillParam(List<String> record, BatchImportContext importContext, String filePath, AddImgPersonParam addPersonParam) throws ImageStoreException, ServiceException {
|
||||
Map<String, ImgStorePersonProperties> namePropertiesMap = importContext.getNameCodeMap();
|
||||
Map<Integer, String> indexNameMap = importContext.getNameIndexMap();
|
||||
Map<String, Organization> orgNameMap = importContext.getOrgNameMap();
|
||||
Map<String, Label> labelNameMap = importContext.getLabelNameMap();
|
||||
Map<String, ZoneResult> zoneMap = importContext.getZoneMap();
|
||||
if (namePropertiesMap.size() < 12) {
|
||||
throw new ImageStoreException("53014029", "人员属性未设置");
|
||||
}
|
||||
for (int i = 0; i < record.size(); i++) {
|
||||
String value = record.get(i);
|
||||
String name = indexNameMap.get(Integer.valueOf(i));
|
||||
ImgStorePersonProperties properties = namePropertiesMap.get(name);
|
||||
if (properties != null) {
|
||||
try {
|
||||
checkField(properties, value);
|
||||
} catch (ImageStoreException e) {
|
||||
this.logger.warn("当前属性值缺失{}", JSONObject.toJSONString(record));
|
||||
throw new ImageStoreException("53014017", properties.getName() + "没有有效值");
|
||||
}
|
||||
if (!StringUtils.isEmpty(value)) {
|
||||
if ("personCode".equals(properties.getCode())) {
|
||||
Pattern pattern = Pattern.compile("^[^\\u4e00-\\u9fa5]+$");
|
||||
Matcher matcher = pattern.matcher(value);
|
||||
if (!matcher.matches()) {
|
||||
this.logger.warn("文件内工号格式不正确,name:[{}], value:[{}]", properties.getName(), value);
|
||||
throw new ImageStoreException("53014001",
|
||||
String.format("%s[%s]文件内工号格式不正确", new Object[] { properties.getName(), value }));
|
||||
}
|
||||
}
|
||||
if ("userName".equals(properties.getCode())) {
|
||||
Pattern pattern = Pattern.compile("^[^\\u4e00-\\u9fa5]+$");
|
||||
Matcher matcher = pattern.matcher(value);
|
||||
if (!matcher.matches()) {
|
||||
this.logger.warn("文件内用户名格式不正确,name:[{}], value:[{}]", properties.getName(), value);
|
||||
throw new ImageStoreException("53014003",
|
||||
String.format("%s[%s]文件内用户名格式不正确", new Object[] { properties.getName(), value }));
|
||||
}
|
||||
}
|
||||
if ("phone".equals(properties.getCode())) {
|
||||
Pattern pattern = Pattern.compile("^[1][3,4,5,6,7,8,9][0-9]{9}$");
|
||||
Matcher matcher = pattern.matcher(value);
|
||||
if (!matcher.matches()) {
|
||||
this.logger.warn("文件内手机号格式不正确,name:[{}], value:[{}]", properties.getName(), value);
|
||||
throw new ImageStoreException("53014017",
|
||||
String.format("%s[%s]文件内手机号格式不正确", new Object[] { properties.getName(), value }));
|
||||
}
|
||||
}
|
||||
if ("email".equals(properties.getCode())) {
|
||||
Pattern pattern = Pattern.compile("^[A-Za-z0-9]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$");
|
||||
Matcher matcher = pattern.matcher(value);
|
||||
if (!matcher.matches()) {
|
||||
this.logger.warn("文件内邮箱格式不正确,name:[{}], value:[{}]", properties.getName(), value);
|
||||
throw new ImageStoreException("53014017",
|
||||
String.format("%s[%s]文件内邮箱格式不正确", new Object[] { properties.getName(), value }));
|
||||
}
|
||||
}
|
||||
if ("floorName".equals(properties.getCode())) {
|
||||
addPersonParam.setDefaultFloor(handlerZoneName(value, zoneMap));
|
||||
} else if ("floorNames".equals(properties.getCode())) {
|
||||
addPersonParam.setChooseFloor(handlerZoneName(value, zoneMap));
|
||||
} else if ("organizationIds".equals(properties.getCode())) {
|
||||
addPersonParam.setOrganizationIds(handlerOrgName(value, orgNameMap));
|
||||
} else if ("labelIds".equals(properties.getCode())) {
|
||||
addPersonParam.setLabelIds(handlerLabelName(value, labelNameMap));
|
||||
} else if ("sysAccountId".equals(properties.getCode())) {
|
||||
if (StringUtils.isBlank(value)) {
|
||||
addPersonParam.setCreateSysAccount(Short.valueOf((short)0));
|
||||
addPersonParam.setSysAccountId(null);
|
||||
} else {
|
||||
addPersonParam.setCreateSysAccount(Short.valueOf((short)1));
|
||||
addPersonParam.setSysAccountId(value);
|
||||
}
|
||||
} else {
|
||||
handlerPropertyTypeAndFillParam(properties, value, filePath, addPersonParam, importContext);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (CollectionUtils.isEmpty(addPersonParam.getLabelIds()) &&
|
||||
CollectionUtils.isEmpty(addPersonParam.getOrganizationIds())) {
|
||||
this.logger.warn("组织/标签至少二选一");
|
||||
throw new ImageStoreException("53014020", "组织/标签至少二选一");
|
||||
}
|
||||
}
|
||||
private String handlerZoneName(String value, Map<String, ZoneResult> zoneMap) {
|
||||
String floorId = "";
|
||||
if (!StringUtils.isEmpty(value)) {
|
||||
value = value.replaceAll("\\s+", "");
|
||||
String[] floorArrs = value.split(",");
|
||||
for (String floor : floorArrs) {
|
||||
if (zoneMap.containsKey(floor)) {
|
||||
if (StringUtils.isNotEmpty(floorId)) {
|
||||
floorId = floorId + ",";
|
||||
}
|
||||
floorId = floorId + ((ZoneResult)zoneMap.get(floor)).getId();
|
||||
}
|
||||
}
|
||||
}
|
||||
return floorId;
|
||||
}
|
||||
private List<String> handlerOrgName(String value, Map<String, Organization> orgNameMap) {
|
||||
List<String> orgIds = new ArrayList<>();
|
||||
if (!StringUtils.isEmpty(value)) {
|
||||
value = value.replaceAll("\\s+", "");
|
||||
String[] orgNameArr = value.split(";");
|
||||
for (String orgName : orgNameArr) {
|
||||
if (orgNameMap.containsKey(orgName)) {
|
||||
orgIds.add(((Organization)orgNameMap.get(orgName)).getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
return orgIds;
|
||||
}
|
||||
private List<String> handlerLabelName(String value, Map<String, Label> labelNameMap) {
|
||||
List<String> labelIds = new ArrayList<>();
|
||||
if (!StringUtils.isEmpty(value)) {
|
||||
value = value.replaceAll("\\s+", "");
|
||||
String[] labelNameArr = value.split(";");
|
||||
for (String labelName : labelNameArr) {
|
||||
if (labelNameMap.containsKey(labelName)) {
|
||||
labelIds.add(((Label)labelNameMap.get(labelName)).getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
return labelIds;
|
||||
}
|
||||
private void handlerPropertyTypeAndFillParam(ImgStorePersonProperties properties, String value, String filePath, AddImgPersonParam addPersonParam, BatchImportContext context) throws ImageStoreException, ServiceException {
|
||||
long copyImageTimeStart;
|
||||
String fullPath;
|
||||
SimpleDateFormat simpleDateFormat;
|
||||
Date date;
|
||||
switch (properties.getType().shortValue()) {
|
||||
case 4:
|
||||
copyImageTimeStart = System.currentTimeMillis();
|
||||
fullPath = filePath + File.separator + value;
|
||||
try {
|
||||
MultipartFile multipartFile = this.personFileService.buildMultipartFile(value, Files.readAllBytes(Paths.get(fullPath, new String[0])));
|
||||
CloudwalkResult<String> result = null;
|
||||
if ("comparePicture".equalsIgnoreCase(properties.getCode())) {
|
||||
result = this.personFileService.uploadCompressImage2(multipartFile);
|
||||
} else {
|
||||
result = this.personFileService.uploadImage(multipartFile);
|
||||
}
|
||||
if (!result.isSuccess()) {
|
||||
throw new ImageStoreException(result.getCode(), result.getMessage());
|
||||
}
|
||||
context.getImageCopyTime().getAndAdd(System.currentTimeMillis() - copyImageTimeStart);
|
||||
String relativePath = (null != result.getData()) ? (String)result.getData() : "";
|
||||
populateBeanValue(properties, relativePath, addPersonParam);
|
||||
} catch (IOException e) {
|
||||
throw new ImageStoreException("53014017", properties.getName() + "不存在/无效");
|
||||
}
|
||||
return;
|
||||
case 3:
|
||||
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
date = null;
|
||||
try {
|
||||
date = simpleDateFormat.parse(value);
|
||||
} catch (ParseException e) {
|
||||
this.logger.warn("当前时间格式不合法", e);
|
||||
throw new ImageStoreException("53014017", properties.getName() + "格式不合法");
|
||||
}
|
||||
populateBeanValue(properties, Long.valueOf(date.getTime()), addPersonParam);
|
||||
return;
|
||||
case 1:
|
||||
case 2:
|
||||
populateBeanValue(properties, value, addPersonParam);
|
||||
return;
|
||||
}
|
||||
this.logger.warn("当前属性类型不合法");
|
||||
throw new ImageStoreException("53014017", "当前属性类型不合法");
|
||||
}
|
||||
private BatchDetailInsertBatchParam generateBatchDetail(BatchImportContext importContext, String personName, String remark, int status) {
|
||||
BatchDetailInsertBatchParam batchDetail = new BatchDetailInsertBatchParam();
|
||||
batchDetail.setId(CloudwalkDateUtils.getUUID());
|
||||
batchDetail.setBatchId(importContext.getBatchImport().getId());
|
||||
batchDetail.setFileName(importContext.getBatchImport().getFileName());
|
||||
batchDetail.setCreateTime(importContext.getBatchImport().getCreateTime());
|
||||
batchDetail.setCreateUserId(importContext.getBatchImport().getCreateUserId());
|
||||
batchDetail.setPersonName(personName);
|
||||
batchDetail.setRemark(remark);
|
||||
batchDetail.setStatus(Integer.valueOf(status));
|
||||
return batchDetail;
|
||||
}
|
||||
private <T> void checkField(ImgStorePersonProperties properties, String cellValue) throws ImageStoreException {
|
||||
short required = (properties.getHasRequired() == null) ? 0 : properties.getHasRequired().shortValue();
|
||||
if (required == 1 && StringUtils.isEmpty(cellValue)) {
|
||||
throw new ImageStoreException("53014017", properties.getReminder());
|
||||
}
|
||||
}
|
||||
private <S, T> void populateBeanValue(ImgStorePersonProperties properties, S source, T target) throws ImageStoreException {
|
||||
String fieldName = properties.getCode();
|
||||
Field targetField = ReflectionUtils.findField(target.getClass(), fieldName);
|
||||
if (targetField == null) {
|
||||
throw new ImageStoreException("53014016", this.messageSource
|
||||
.getMessage("53014016", null, LocaleContextHolder.getLocale()));
|
||||
}
|
||||
targetField.setAccessible(true);
|
||||
if ("createSysAccount".equals(fieldName)) {
|
||||
ReflectionUtils.setField(targetField, target, Short.valueOf(String.valueOf(source)));
|
||||
} else {
|
||||
if (StringUtils.isEmpty(String.valueOf(source))) {
|
||||
source = null;
|
||||
}
|
||||
if (ImageStoreConstants.getCustProperties().contains(properties.getCode())) {
|
||||
ReflectionUtils.setField(targetField, target, String.valueOf(source));
|
||||
} else {
|
||||
ReflectionUtils.setField(targetField, target, source);
|
||||
}
|
||||
}
|
||||
}
|
||||
public CloudwalkResult<Boolean> insert(BatchImportParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
BatchImport batchImport = new BatchImport();
|
||||
batchImport.setBatchNo((new SimpleDateFormat("yyyyMMddHHmmssSSS")).format(new Date()));
|
||||
batchImport.setBusinessId(
|
||||
StringUtils.isEmpty(param.getBusinessId()) ? context.getCompany()
|
||||
.getCompanyId() : param.getBusinessId());
|
||||
batchImport.setId(CloudwalkDateUtils.getUUID());
|
||||
batchImport.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
batchImport.setCreateUserId(context.getUser().getCaller());
|
||||
batchImport.setStatus(Integer.valueOf(1));
|
||||
batchImport.setType(Integer.valueOf(2));
|
||||
batchImport.setOperation("1");
|
||||
batchImport.setFilePath(param.getFilePath());
|
||||
batchImport.setFileName(param.getFilePath().substring(param.getFilePath().lastIndexOf(File.separator) + 1));
|
||||
batchImport.setLoginName(context.getUser().getCallerName());
|
||||
int count = this.personBatchImportMapper.insert(batchImport);
|
||||
if (count < 1) {
|
||||
return CloudwalkResult.fail("53014035", this.messageSource
|
||||
.getMessage("53014035", null, LocaleContextHolder.getLocale()));
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.valueOf(true));
|
||||
}
|
||||
public CloudwalkResult<CloudwalkPageAble<BatchImportQueryResult>> page(BatchImportQueryParam param, CloudwalkPageInfo page, CloudwalkCallContext context) throws ServiceException {
|
||||
BatchImport batchImportQuery = (BatchImport)BeanCopyUtils.copyProperties(param, new BatchImport());
|
||||
batchImportQuery.setBusinessId(StringUtils.isEmpty(param.getBusinessId()) ? context.getCompany().getCompanyId() : param
|
||||
.getBusinessId());
|
||||
CloudwalkPageAble<BatchImport> pageAble = null;
|
||||
try {
|
||||
PageHelper.startPage(page.getCurrentPage(), page.getPageSize());
|
||||
Page<BatchImport> page1 = (Page<BatchImport>)this.personBatchImportMapper.page(batchImportQuery);
|
||||
pageAble = new CloudwalkPageAble(page1.getResult(), page, page1.getTotal());
|
||||
} catch (Exception e) {
|
||||
this.logger.error("分页查询批量导入记录列表信息失败,原因:", e);
|
||||
throw new ServiceException(e);
|
||||
}
|
||||
List<BatchImportQueryResult> result = BeanCopyUtils.copy(pageAble.getDatas(), BatchImportQueryResult.class);
|
||||
return CloudwalkResult.success(new CloudwalkPageAble(result, page, pageAble.getTotalRows()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/ImgPersonBatchServiceImpl.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+629
-645
File diff suppressed because it is too large
Load Diff
+325
-315
@@ -20,9 +20,11 @@ import cn.cloudwalk.cloud.utils.BeanCopyUtils;
|
||||
import cn.cloudwalk.cloud.utils.CloudwalkDateUtils;
|
||||
import cn.cloudwalk.data.organization.dto.ImgStorePersonQueryDto;
|
||||
import cn.cloudwalk.data.organization.dto.PersonRegistryDTO;
|
||||
import cn.cloudwalk.data.organization.entity.ImgStorePerson;
|
||||
import cn.cloudwalk.data.organization.entity.ImgStorePersonProperties;
|
||||
import cn.cloudwalk.data.organization.entity.PersonPropertiesSwitch;
|
||||
import cn.cloudwalk.data.organization.entity.PersonRegistry;
|
||||
import cn.cloudwalk.data.organization.entity.PersonRegistryProperties;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonPropertiesMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.PersonPropertiesSwitchMapper;
|
||||
@@ -33,9 +35,7 @@ import cn.cloudwalk.service.organization.service.feign.PineappleEngineClient;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.google.common.collect.Lists;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import javax.annotation.Resource;
|
||||
@@ -45,321 +45,331 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.util.ObjectUtils;
|
||||
import org.springside.modules.utils.Collections3;
|
||||
|
||||
@Service
|
||||
public class ImgPersonPropertiesServiceImpl
|
||||
extends AbstractImagStoreService
|
||||
implements ImgStorePersonPropertiesService {
|
||||
@Resource
|
||||
private ImgStorePersonPropertiesMapper personPropertiesMapper;
|
||||
@Resource
|
||||
private ImgStorePersonMapper imgStorePersonMapper;
|
||||
@Resource
|
||||
private PersonRegistryMapper personRegistryMapper;
|
||||
@Resource
|
||||
private PersonPropertiesSwitchMapper personPropertiesSwitchMapper;
|
||||
@Resource
|
||||
private PersonRegistryPropertiesMapper personRegistryPropertiesMapper;
|
||||
@Resource
|
||||
private PineappleEngineClient pineappleEngineClient;
|
||||
@Resource
|
||||
private UUIDSerial uuidSerial;
|
||||
@Value(value="${revision.engine.port}")
|
||||
private String revisionEnginePort;
|
||||
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> addOrUpdate(AddImgPersonProParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
HashSet<String> nameMap = new HashSet<String>();
|
||||
String businessId = context.getCompany().getCompanyId();
|
||||
if (StringUtils.isNotBlank((CharSequence)param.getBusinessId())) {
|
||||
businessId = param.getBusinessId();
|
||||
}
|
||||
String caller = context.getUser().getCaller();
|
||||
List properties = param.getProperties();
|
||||
ArrayList<ImgStorePersonProperties> newList = new ArrayList<ImgStorePersonProperties>();
|
||||
if (properties != null && properties.size() > 0) {
|
||||
for (ImgPersonProParam property : properties) {
|
||||
nameMap.add(property.getName());
|
||||
ImgStorePersonProperties personProperty = (ImgStorePersonProperties)BeanCopyUtils.copyProperties((Object)property, ImgStorePersonProperties.class);
|
||||
personProperty.setBusinessId(businessId);
|
||||
if (personProperty.getCreateTime() == null) {
|
||||
personProperty.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
personProperty.setCreateUserId(caller);
|
||||
}
|
||||
personProperty.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
personProperty.setLastUpdateUserId(caller);
|
||||
newList.add(personProperty);
|
||||
}
|
||||
if (nameMap.size() < properties.size()) {
|
||||
throw new ServiceException("53004117", this.getMessage("53004117"));
|
||||
}
|
||||
ImgStorePersonProperties record = new ImgStorePersonProperties();
|
||||
record.setBusinessId(businessId);
|
||||
record.setStatus(Integer.valueOf(0));
|
||||
List listFromDB = this.personPropertiesMapper.select(record);
|
||||
if (listFromDB == null || listFromDB.size() == 0) {
|
||||
String code = "ext";
|
||||
int i = 1;
|
||||
for (ImgStorePersonProperties personProperties : newList) {
|
||||
personProperties.setId(CloudwalkDateUtils.getUUID());
|
||||
personProperties.setStatus(Integer.valueOf(0));
|
||||
if (StringUtils.isBlank((CharSequence)personProperties.getCode())) {
|
||||
personProperties.setCode(code + i++);
|
||||
}
|
||||
this.personPropertiesMapper.insertSelective(personProperties);
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
return this.addAndUpdate(newList, listFromDB, context, businessId);
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
public CloudwalkResult<PersonProListResult> getList(String businessId) throws ServiceException {
|
||||
PersonProListResult result = new PersonProListResult();
|
||||
ImgStorePersonProperties record = new ImgStorePersonProperties();
|
||||
record.setBusinessId(businessId);
|
||||
record.setStatus(Integer.valueOf(0));
|
||||
List listFromDB = this.personPropertiesMapper.select(record);
|
||||
boolean hasAccount = true;
|
||||
if (listFromDB == null || listFromDB.size() == 0) {
|
||||
hasAccount = false;
|
||||
record.setBusinessId("cloudwalk");
|
||||
record.setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS);
|
||||
listFromDB = this.personPropertiesMapper.select(record);
|
||||
for (ImgStorePersonProperties personProperties : listFromDB) {
|
||||
personProperties.setId(null);
|
||||
personProperties.setStatus(null);
|
||||
personProperties.setHasSysAccount(null);
|
||||
personProperties.setBusinessId(null);
|
||||
}
|
||||
}
|
||||
List returnList = BeanCopyUtils.copy((Collection)listFromDB, ImgPersonProGetResult.class);
|
||||
result.setProperties(returnList);
|
||||
result.setHasAccount(Boolean.valueOf(hasAccount));
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
public CloudwalkResult<Boolean> init(AddImgPersonProParam param, CloudwalkCallContext cloudwalkContext) throws ServiceException {
|
||||
Object personProperties2;
|
||||
ImgStorePersonProperties record = new ImgStorePersonProperties();
|
||||
record.setBusinessId("cloudwalk");
|
||||
record.setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS);
|
||||
List select = this.personPropertiesMapper.select(record);
|
||||
if (select != null && select.size() > 0) {
|
||||
for (Object personProperties2 : select) {
|
||||
personProperties2.setStatus(Integer.valueOf(1));
|
||||
personProperties2.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
personProperties2.setLastUpdateUserId(cloudwalkContext.getUser().getCaller());
|
||||
this.personPropertiesMapper.updateByPrimaryKeySelective((ImgStorePersonProperties)personProperties2);
|
||||
}
|
||||
}
|
||||
List properties = param.getProperties();
|
||||
personProperties2 = new ArrayList();
|
||||
if (properties != null && properties.size() > 0) {
|
||||
personProperties2 = BeanCopyUtils.copy((Collection)properties, ImgStorePersonProperties.class);
|
||||
Iterator iterator = personProperties2.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
ImgStorePersonProperties personProperty = (ImgStorePersonProperties)iterator.next();
|
||||
personProperty.setId(CloudwalkDateUtils.getUUID());
|
||||
personProperty.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
personProperty.setCreateUserId(cloudwalkContext.getUser().getCaller());
|
||||
personProperty.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
personProperty.setLastUpdateUserId(cloudwalkContext.getUser().getCaller());
|
||||
personProperty.setBusinessId("cloudwalk");
|
||||
personProperty.setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS);
|
||||
personProperty.setHasDefault(Integer.valueOf(1));
|
||||
personProperty.setHasRequired(Integer.valueOf(0));
|
||||
personProperty.setHasSysAccount(Integer.valueOf(0));
|
||||
this.personPropertiesMapper.insertSelective(personProperty);
|
||||
}
|
||||
} else {
|
||||
ImgStorePersonProperties personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("name").setName("人员姓名").setType(Short.valueOf((short)1)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(0)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(1)).setReminder("请输入人员姓名").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("userName").setName("用户名").setType(Short.valueOf((short)1)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(1)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(2)).setReminder("请输入用户名").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("phone").setName("手机号码").setType(Short.valueOf((short)1)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(1)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(3)).setReminder("请输入手机号码").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("email").setName("邮箱").setType(Short.valueOf((short)1)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(1)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(4)).setReminder("请输入邮箱").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("personCode").setName("工号").setType(Short.valueOf((short)1)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(1)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(5)).setReminder("请输入工号").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("organizationIds").setName("所属机构").setType(Short.valueOf((short)2)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(0)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(6)).setReminder("请选择所属机构").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("labelIds").setName("人员标签").setType(Short.valueOf((short)2)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(0)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(7)).setReminder("请选择人员标签").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("icCardNo").setName("IC卡号").setType(Short.valueOf((short)1)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(0)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(8)).setReminder("请输入IC卡号").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("icCardType").setName("IC卡类型").setType(Short.valueOf((short)1)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(0)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(9)).setReminder("请输入IC卡类型").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("comparePicture").setName("注册照").setType(Short.valueOf((short)4)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(0)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(10)).setReminder("请上传人员高清正面照用作AI比对").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("welcome").setName("欢迎语").setType(Short.valueOf((short)1)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(0)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(11)).setReminder("请输入欢迎语").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("showPicture").setName("展示照").setType(Short.valueOf((short)4)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(0)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(12)).setReminder("请上传展示照").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
private CloudwalkResult<Boolean> addAndUpdate(List<ImgStorePersonProperties> newList, List<ImgStorePersonProperties> listFromDB, CloudwalkCallContext context, String businessId) throws ServiceException {
|
||||
ImgStorePersonQueryDto record = new ImgStorePersonQueryDto();
|
||||
record.setBusinessId(businessId);
|
||||
record.setStatus(Short.valueOf((short)0));
|
||||
record.setIsDel(Short.valueOf((short)0));
|
||||
List gets = this.imgStorePersonMapper.gets(record);
|
||||
HashSet<String> codeSet = new HashSet<String>();
|
||||
HashSet<String> defaultSet = new HashSet<String>();
|
||||
ArrayList<ImgStorePersonProperties> dbRequiredList = new ArrayList<ImgStorePersonProperties>();
|
||||
ArrayList<ImgStorePersonProperties> newRequiredList = new ArrayList<ImgStorePersonProperties>();
|
||||
for (ImgStorePersonProperties imgStorePersonProperties : listFromDB) {
|
||||
if (imgStorePersonProperties.getCode() != null && imgStorePersonProperties.getCode().startsWith("ext")) {
|
||||
codeSet.add(imgStorePersonProperties.getCode());
|
||||
}
|
||||
if (imgStorePersonProperties.getHasDefault() != null && imgStorePersonProperties.getHasDefault() == 1) {
|
||||
defaultSet.add(imgStorePersonProperties.getName());
|
||||
}
|
||||
if (imgStorePersonProperties.getHasRequired() == null || imgStorePersonProperties.getHasRequired() != 1) continue;
|
||||
dbRequiredList.add(imgStorePersonProperties);
|
||||
}
|
||||
String newAccountCode = "";
|
||||
for (ImgStorePersonProperties imgStorePersonProperties : newList) {
|
||||
if (StringUtils.isBlank((CharSequence)imgStorePersonProperties.getId()) && !defaultSet.add(imgStorePersonProperties.getName())) {
|
||||
throw new ServiceException("53014811", this.getMessage("53014811"));
|
||||
}
|
||||
if (imgStorePersonProperties.getHasRequired() == null || imgStorePersonProperties.getHasRequired() != 1) continue;
|
||||
newRequiredList.add(imgStorePersonProperties);
|
||||
}
|
||||
newRequiredList.removeAll(dbRequiredList);
|
||||
if (newRequiredList.size() > 0 && gets.size() > 0) {
|
||||
throw new ServiceException("53014812", this.getMessage("53014812"));
|
||||
}
|
||||
ArrayList<ImgStorePersonProperties> arrayList = new ArrayList<ImgStorePersonProperties>(newList);
|
||||
arrayList.retainAll(listFromDB);
|
||||
if (arrayList != null && arrayList.size() > 0) {
|
||||
for (ImgStorePersonProperties imgStorePersonProperties : arrayList) {
|
||||
imgStorePersonProperties.setStatus(Integer.valueOf(0));
|
||||
imgStorePersonProperties.setLastUpdateUserId(context.getUser().getCaller());
|
||||
imgStorePersonProperties.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.personPropertiesMapper.updateByPrimaryKeySelective(imgStorePersonProperties);
|
||||
}
|
||||
}
|
||||
listFromDB.removeAll(arrayList);
|
||||
ArrayList arrayList2 = Lists.newArrayListWithCapacity((int)listFromDB.size());
|
||||
if (listFromDB != null && listFromDB.size() > 0) {
|
||||
for (ImgStorePersonProperties personProperties : listFromDB) {
|
||||
if (personProperties.getHasDefault() == null || personProperties.getHasDefault() == 1) continue;
|
||||
this.personPropertiesMapper.delete(personProperties);
|
||||
codeSet.remove(personProperties.getCode());
|
||||
arrayList2.add(personProperties.getId());
|
||||
businessId = personProperties.getBusinessId();
|
||||
String codeProperty = personProperties.getCode();
|
||||
this.imgStorePersonMapper.removePropertyByBusinessIdAndCode(businessId, codeProperty);
|
||||
}
|
||||
}
|
||||
if (!CollectionUtils.isEmpty((Collection)arrayList2)) {
|
||||
List dbRegistryProperyList;
|
||||
this.logger.info("人员注册配置待删除的关联属性,属性主键列表:[{}]", (Object)StringUtils.join((Iterable)arrayList2, (String)","));
|
||||
PersonRegistryDTO personRegistryDTO = new PersonRegistryDTO();
|
||||
personRegistryDTO.setBusinessId(businessId);
|
||||
List dbPersonRegistryList = this.personRegistryMapper.selectByCondition(personRegistryDTO);
|
||||
if (!CollectionUtils.isEmpty((Collection)dbPersonRegistryList) && !CollectionUtils.isEmpty((Collection)(dbRegistryProperyList = this.personRegistryPropertiesMapper.select(((PersonRegistry)dbPersonRegistryList.get(0)).getId(), (List)arrayList2)))) {
|
||||
this.logger.info("删除人员注册配置关联属性,注册配置表主键:[{}],属性主键列表:[{}]", (Object)((PersonRegistry)dbPersonRegistryList.get(0)).getId(), (Object)Collections3.extractToString((Collection)dbRegistryProperyList, (String)"personPropertyId", (String)","));
|
||||
this.personRegistryPropertiesMapper.delete(((PersonRegistry)dbPersonRegistryList.get(0)).getId(), Collections3.extractToList((Collection)dbRegistryProperyList, (String)"personPropertyId"));
|
||||
}
|
||||
}
|
||||
newList.removeAll(arrayList);
|
||||
if (newList != null && newList.size() > 0) {
|
||||
for (ImgStorePersonProperties personProperties : newList) {
|
||||
if (StringUtils.isNotBlank((CharSequence)personProperties.getId())) {
|
||||
throw new ServiceException("53004121", "新增条目id必须为空或传入id错误,请检查数据后重试");
|
||||
}
|
||||
personProperties.setId(CloudwalkDateUtils.getUUID());
|
||||
personProperties.setStatus(Integer.valueOf(0));
|
||||
String code = this.getCode(codeSet);
|
||||
if (code == null) {
|
||||
throw new ServiceException("53004116", "扩展字段已满");
|
||||
}
|
||||
personProperties.setCode(code);
|
||||
this.personPropertiesMapper.insertSelective(personProperties);
|
||||
}
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
private String getCode(Set<String> codeSet) {
|
||||
String[] codeBaseArray = ImageStoreConstants.getCustProperties().toArray(new String[0]);
|
||||
for (int i = 0; i < codeBaseArray.length; ++i) {
|
||||
if (!codeSet.add(codeBaseArray[i])) continue;
|
||||
return codeBaseArray[i];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public CloudwalkResult<EngineResult> engineStatus() throws ServiceException {
|
||||
this.logger.info("通过分析引擎列表端口来判断通用修图引擎是否在线");
|
||||
EngineListParam engineListParam = EngineListParam.builder().build();
|
||||
EngineListResult result = this.pineappleEngineClient.engineList(engineListParam);
|
||||
this.logger.info("引擎状态查询返回结果:{}, 待查询引擎端口为{}", (Object)JSON.toJSONString((Object)result), (Object)this.revisionEnginePort);
|
||||
if (ObjectUtils.isEmpty((Object)result) || result.getResult() != 0 || ObjectUtils.isEmpty((Object)result.getRows())) {
|
||||
this.logger.error("查询引擎状态异常,错误原因:{}", (Object)result.getInfo());
|
||||
throw new ServiceException("53004123", this.getMessage("53004123"));
|
||||
}
|
||||
List engines = result.getRows();
|
||||
Boolean online = false;
|
||||
if (StringUtils.isNotBlank((CharSequence)this.revisionEnginePort)) {
|
||||
for (EngineListResult.EngineStatus status : engines) {
|
||||
if (!this.revisionEnginePort.equals(status.getHost().split(":")[1]) || !status.getOnline().booleanValue()) continue;
|
||||
online = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
EngineResult engineResult = new EngineResult();
|
||||
engineResult.setOnline(online);
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> saveParam(SwitchParam param, CloudwalkCallContext cloudwalkContext) throws ServiceException {
|
||||
String businessId = cloudwalkContext.getCompany().getCompanyId();
|
||||
String caller = cloudwalkContext.getUser().getCaller();
|
||||
try {
|
||||
this.personPropertiesSwitchMapper.deleteByBusinessId(businessId);
|
||||
PersonPropertiesSwitch entry = (PersonPropertiesSwitch)BeanCopyUtils.copyProperties((Object)param, PersonPropertiesSwitch.class);
|
||||
if (entry.getBackgroundParam().equals(Boolean.TRUE)) {
|
||||
if (entry.getBackgroundObject() == null) {
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
} else {
|
||||
entry.setBackgroundObject(null);
|
||||
}
|
||||
entry.setId(this.uuidSerial.uuid());
|
||||
entry.setBusinessId(businessId);
|
||||
entry.setStatus(Short.valueOf((short)0));
|
||||
entry.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
entry.setCreateUserId(caller);
|
||||
entry.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
entry.setLastUpdateUserId(caller);
|
||||
this.personPropertiesSwitchMapper.insert(entry);
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("保存注册图优化参数失败,原因:", e);
|
||||
throw new ServiceException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public CloudwalkResult<PersonPropertiesSwitchResult> getParam(CloudwalkCallContext cloudwalkContext) throws ServiceException {
|
||||
String businessId = cloudwalkContext.getCompany().getCompanyId();
|
||||
try {
|
||||
PersonPropertiesSwitch entry = this.personPropertiesSwitchMapper.selectByBusinessId(businessId);
|
||||
PersonPropertiesSwitchResult result = ObjectUtils.isEmpty((Object)entry) ? null : (PersonPropertiesSwitchResult)BeanCopyUtils.copyProperties((Object)entry, PersonPropertiesSwitchResult.class);
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("查询注册图优化参数失败,原因:", e);
|
||||
throw new ServiceException(e);
|
||||
}
|
||||
}
|
||||
implements ImgStorePersonPropertiesService
|
||||
{
|
||||
@Resource
|
||||
private ImgStorePersonPropertiesMapper personPropertiesMapper;
|
||||
@Resource
|
||||
private ImgStorePersonMapper imgStorePersonMapper;
|
||||
@Resource
|
||||
private PersonRegistryMapper personRegistryMapper;
|
||||
@Resource
|
||||
private PersonPropertiesSwitchMapper personPropertiesSwitchMapper;
|
||||
@Resource
|
||||
private PersonRegistryPropertiesMapper personRegistryPropertiesMapper;
|
||||
@Resource
|
||||
private PineappleEngineClient pineappleEngineClient;
|
||||
@Resource
|
||||
private UUIDSerial uuidSerial;
|
||||
@Value("${revision.engine.port}")
|
||||
private String revisionEnginePort;
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> addOrUpdate(AddImgPersonProParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
Set<String> nameMap = new HashSet<>();
|
||||
String businessId = context.getCompany().getCompanyId();
|
||||
if (StringUtils.isNotBlank(param.getBusinessId())) {
|
||||
businessId = param.getBusinessId();
|
||||
}
|
||||
String caller = context.getUser().getCaller();
|
||||
List<ImgPersonProParam> properties = param.getProperties();
|
||||
List<ImgStorePersonProperties> newList = new ArrayList<>();
|
||||
if (properties != null && properties.size() > 0) {
|
||||
for (ImgPersonProParam property : properties) {
|
||||
nameMap.add(property.getName());
|
||||
ImgStorePersonProperties personProperty = (ImgStorePersonProperties)BeanCopyUtils.copyProperties(property, ImgStorePersonProperties.class);
|
||||
personProperty.setBusinessId(businessId);
|
||||
if (personProperty.getCreateTime() == null) {
|
||||
personProperty.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
personProperty.setCreateUserId(caller);
|
||||
}
|
||||
personProperty.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
personProperty.setLastUpdateUserId(caller);
|
||||
newList.add(personProperty);
|
||||
}
|
||||
if (nameMap.size() < properties.size()) {
|
||||
throw new ServiceException("53004117",
|
||||
getMessage("53004117"));
|
||||
}
|
||||
ImgStorePersonProperties record = new ImgStorePersonProperties();
|
||||
record.setBusinessId(businessId);
|
||||
record.setStatus(Integer.valueOf(0));
|
||||
List<ImgStorePersonProperties> listFromDB = this.personPropertiesMapper.select(record);
|
||||
if (listFromDB == null || listFromDB.size() == 0) {
|
||||
String code = "ext";
|
||||
int i = 1;
|
||||
for (ImgStorePersonProperties personProperties : newList) {
|
||||
personProperties.setId(CloudwalkDateUtils.getUUID());
|
||||
personProperties.setStatus(Integer.valueOf(0));
|
||||
if (StringUtils.isBlank(personProperties.getCode())) {
|
||||
personProperties.setCode(code + i++);
|
||||
}
|
||||
this.personPropertiesMapper.insertSelective(personProperties);
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
return addAndUpdate(newList, listFromDB, context, businessId);
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
public CloudwalkResult<PersonProListResult> getList(String businessId) throws ServiceException {
|
||||
PersonProListResult result = new PersonProListResult();
|
||||
ImgStorePersonProperties record = new ImgStorePersonProperties();
|
||||
record.setBusinessId(businessId);
|
||||
record.setStatus(Integer.valueOf(0));
|
||||
List<ImgStorePersonProperties> listFromDB = this.personPropertiesMapper.select(record);
|
||||
boolean hasAccount = true;
|
||||
if (listFromDB == null || listFromDB.size() == 0) {
|
||||
hasAccount = false;
|
||||
record.setBusinessId("cloudwalk");
|
||||
record.setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS);
|
||||
listFromDB = this.personPropertiesMapper.select(record);
|
||||
for (ImgStorePersonProperties personProperties : listFromDB) {
|
||||
personProperties.setId(null);
|
||||
personProperties.setStatus(null);
|
||||
personProperties.setHasSysAccount(null);
|
||||
personProperties.setBusinessId(null);
|
||||
}
|
||||
}
|
||||
List<ImgPersonProGetResult> returnList = BeanCopyUtils.copy(listFromDB, ImgPersonProGetResult.class);
|
||||
result.setProperties(returnList);
|
||||
result.setHasAccount(Boolean.valueOf(hasAccount));
|
||||
return CloudwalkResult.success(result);
|
||||
}
|
||||
public CloudwalkResult<Boolean> init(AddImgPersonProParam param, CloudwalkCallContext cloudwalkContext) throws ServiceException {
|
||||
ImgStorePersonProperties record = new ImgStorePersonProperties();
|
||||
record.setBusinessId("cloudwalk");
|
||||
record.setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS);
|
||||
List<ImgStorePersonProperties> select = this.personPropertiesMapper.select(record);
|
||||
if (select != null && select.size() > 0) {
|
||||
for (ImgStorePersonProperties imgStorePersonProperties : select) {
|
||||
imgStorePersonProperties.setStatus(Integer.valueOf(1));
|
||||
imgStorePersonProperties.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
imgStorePersonProperties.setLastUpdateUserId(cloudwalkContext.getUser().getCaller());
|
||||
this.personPropertiesMapper.updateByPrimaryKeySelective(imgStorePersonProperties);
|
||||
}
|
||||
}
|
||||
List<ImgPersonProParam> properties = param.getProperties();
|
||||
List<ImgStorePersonProperties> personProperties = new ArrayList<>();
|
||||
if (properties != null && properties.size() > 0) {
|
||||
personProperties = BeanCopyUtils.copy(properties, ImgStorePersonProperties.class);
|
||||
for (ImgStorePersonProperties personProperty : personProperties) {
|
||||
personProperty.setId(CloudwalkDateUtils.getUUID());
|
||||
personProperty.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
personProperty.setCreateUserId(cloudwalkContext.getUser().getCaller());
|
||||
personProperty.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
personProperty.setLastUpdateUserId(cloudwalkContext.getUser().getCaller());
|
||||
personProperty.setBusinessId("cloudwalk");
|
||||
personProperty.setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS);
|
||||
personProperty.setHasDefault(Integer.valueOf(1));
|
||||
personProperty.setHasRequired(Integer.valueOf(0));
|
||||
personProperty.setHasSysAccount(Integer.valueOf(0));
|
||||
this.personPropertiesMapper.insertSelective(personProperty);
|
||||
}
|
||||
}
|
||||
else {
|
||||
ImgStorePersonProperties personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("name").setName("人员姓名").setType(Short.valueOf((short)1)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(0)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(1)).setReminder("请输入人员姓名").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("userName").setName("用户名").setType(Short.valueOf((short)1)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(1)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(2)).setReminder("请输入用户名").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("phone").setName("手机号码").setType(Short.valueOf((short)1)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(1)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(3)).setReminder("请输入手机号码").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("email").setName("邮箱").setType(Short.valueOf((short)1)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(1)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(4)).setReminder("请输入邮箱").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("personCode").setName("工号").setType(Short.valueOf((short)1)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(1)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(5)).setReminder("请输入工号").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("organizationIds").setName("所属机构").setType(Short.valueOf((short)2)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(0)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(6)).setReminder("请选择所属机构").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("labelIds").setName("人员标签").setType(Short.valueOf((short)2)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(0)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(7)).setReminder("请选择人员标签").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("icCardNo").setName("IC卡号").setType(Short.valueOf((short)1)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(0)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(8)).setReminder("请输入IC卡号").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("icCardType").setName("IC卡类型").setType(Short.valueOf((short)1)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(0)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(9)).setReminder("请输入IC卡类型").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("comparePicture").setName("注册照").setType(Short.valueOf((short)4)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(0)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(10)).setReminder("请上传人员高清正面照用作AI比对").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("welcome").setName("欢迎语").setType(Short.valueOf((short)1)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(0)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(11)).setReminder("请输入欢迎语").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
personPropertyinit = ImgStorePersonProperties.getBuilder().setId(CloudwalkDateUtils.getUUID()).setBusinessId("cloudwalk").setCode("showPicture").setName("展示照").setType(Short.valueOf((short)4)).setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS).setHasDefault(Integer.valueOf(1)).setHasSysAccount(Integer.valueOf(0)).setHasSysAccountAvailable(Integer.valueOf(0)).setHasRequired(Integer.valueOf(0)).setCreateTime(Long.valueOf(System.currentTimeMillis())).setCreateUserId(cloudwalkContext.getUser().getCaller()).setLastUpdateTime(Long.valueOf(System.currentTimeMillis())).setLastUpdateUserId(cloudwalkContext.getUser().getCaller()).setOrderNum(Integer.valueOf(12)).setReminder("请上传展示照").bulid();
|
||||
this.personPropertiesMapper.insertSelective(personPropertyinit);
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
private CloudwalkResult<Boolean> addAndUpdate(List<ImgStorePersonProperties> newList, List<ImgStorePersonProperties> listFromDB, CloudwalkCallContext context, String businessId) throws ServiceException {
|
||||
ImgStorePersonQueryDto record = new ImgStorePersonQueryDto();
|
||||
record.setBusinessId(businessId);
|
||||
record.setStatus(Short.valueOf((short)0));
|
||||
record.setIsDel(Short.valueOf((short)0));
|
||||
List<ImgStorePerson> gets = this.imgStorePersonMapper.gets(record);
|
||||
Set<String> codeSet = new HashSet<>();
|
||||
Set<String> defaultSet = new HashSet<>();
|
||||
List<ImgStorePersonProperties> dbRequiredList = new ArrayList<>();
|
||||
List<ImgStorePersonProperties> newRequiredList = new ArrayList<>();
|
||||
for (ImgStorePersonProperties personProperties : listFromDB) {
|
||||
if (personProperties.getCode() != null && personProperties.getCode().startsWith("ext")) {
|
||||
codeSet.add(personProperties.getCode());
|
||||
}
|
||||
if (personProperties.getHasDefault() != null && personProperties.getHasDefault().intValue() == 1) {
|
||||
defaultSet.add(personProperties.getName());
|
||||
}
|
||||
if (personProperties.getHasRequired() != null && personProperties.getHasRequired().intValue() == 1) {
|
||||
dbRequiredList.add(personProperties);
|
||||
}
|
||||
}
|
||||
String newAccountCode = "";
|
||||
for (ImgStorePersonProperties personProperties : newList) {
|
||||
if (StringUtils.isBlank(personProperties.getId()) &&
|
||||
!defaultSet.add(personProperties.getName())) {
|
||||
throw new ServiceException("53014811",
|
||||
getMessage("53014811"));
|
||||
}
|
||||
if (personProperties.getHasRequired() != null && personProperties.getHasRequired().intValue() == 1) {
|
||||
newRequiredList.add(personProperties);
|
||||
}
|
||||
}
|
||||
newRequiredList.removeAll(dbRequiredList);
|
||||
if (newRequiredList.size() > 0 && gets.size() > 0) {
|
||||
throw new ServiceException("53014812",
|
||||
getMessage("53014812"));
|
||||
}
|
||||
List<ImgStorePersonProperties> tempNew = new ArrayList<>(newList);
|
||||
tempNew.retainAll(listFromDB);
|
||||
if (tempNew != null && tempNew.size() > 0)
|
||||
{
|
||||
for (ImgStorePersonProperties personProperties : tempNew) {
|
||||
personProperties.setStatus(Integer.valueOf(0));
|
||||
personProperties.setLastUpdateUserId(context.getUser().getCaller());
|
||||
personProperties.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.personPropertiesMapper.updateByPrimaryKeySelective(personProperties);
|
||||
}
|
||||
}
|
||||
listFromDB.removeAll(tempNew);
|
||||
List<String> deletePropertyList = Lists.newArrayListWithCapacity(listFromDB.size());
|
||||
if (listFromDB != null && listFromDB.size() > 0) {
|
||||
for (ImgStorePersonProperties personProperties : listFromDB) {
|
||||
if (personProperties.getHasDefault() != null && personProperties.getHasDefault().intValue() != 1) {
|
||||
this.personPropertiesMapper.delete(personProperties);
|
||||
codeSet.remove(personProperties.getCode());
|
||||
deletePropertyList.add(personProperties.getId());
|
||||
businessId = personProperties.getBusinessId();
|
||||
String codeProperty = personProperties.getCode();
|
||||
this.imgStorePersonMapper.removePropertyByBusinessIdAndCode(businessId, codeProperty);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(deletePropertyList)) {
|
||||
this.logger.info("人员注册配置待删除的关联属性,属性主键列表:[{}]", StringUtils.join(deletePropertyList, ","));
|
||||
PersonRegistryDTO queryPersonRegistry = new PersonRegistryDTO();
|
||||
queryPersonRegistry.setBusinessId(businessId);
|
||||
List<PersonRegistry> dbPersonRegistryList = this.personRegistryMapper.selectByCondition(queryPersonRegistry);
|
||||
if (!CollectionUtils.isEmpty(dbPersonRegistryList)) {
|
||||
List<PersonRegistryProperties> dbRegistryProperyList = this.personRegistryPropertiesMapper.select(((PersonRegistry)dbPersonRegistryList.get(0)).getId(), deletePropertyList);
|
||||
if (!CollectionUtils.isEmpty(dbRegistryProperyList)) {
|
||||
this.logger.info("删除人员注册配置关联属性,注册配置表主键:[{}],属性主键列表:[{}]", ((PersonRegistry)dbPersonRegistryList.get(0)).getId(),
|
||||
Collections3.extractToString(dbRegistryProperyList, "personPropertyId", ","));
|
||||
this.personRegistryPropertiesMapper.delete(((PersonRegistry)dbPersonRegistryList.get(0)).getId(),
|
||||
Collections3.extractToList(dbRegistryProperyList, "personPropertyId"));
|
||||
}
|
||||
}
|
||||
}
|
||||
newList.removeAll(tempNew);
|
||||
if (newList != null && newList.size() > 0)
|
||||
{
|
||||
for (ImgStorePersonProperties personProperties : newList) {
|
||||
if (StringUtils.isNotBlank(personProperties.getId())) {
|
||||
throw new ServiceException("53004121", "新增条目id必须为空或传入id错误,请检查数据后重试");
|
||||
}
|
||||
personProperties.setId(CloudwalkDateUtils.getUUID());
|
||||
personProperties.setStatus(Integer.valueOf(0));
|
||||
String code = getCode(codeSet);
|
||||
if (code == null) {
|
||||
throw new ServiceException("53004116", "扩展字段已满");
|
||||
}
|
||||
personProperties.setCode(code);
|
||||
this.personPropertiesMapper.insertSelective(personProperties);
|
||||
}
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
private String getCode(Set<String> codeSet) {
|
||||
String[] codeBaseArray = (String[])ImageStoreConstants.getCustProperties().toArray((Object[])new String[0]);
|
||||
for (int i = 0; i < codeBaseArray.length; i++) {
|
||||
if (codeSet.add(codeBaseArray[i])) {
|
||||
return codeBaseArray[i];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public CloudwalkResult<EngineResult> engineStatus() throws ServiceException {
|
||||
this.logger.info("通过分析引擎列表端口来判断通用修图引擎是否在线");
|
||||
EngineListParam engineListParam = EngineListParam.builder().build();
|
||||
EngineListResult result = this.pineappleEngineClient.engineList(engineListParam);
|
||||
this.logger.info("引擎状态查询返回结果:{}, 待查询引擎端口为{}", JSON.toJSONString(result), this.revisionEnginePort);
|
||||
if (ObjectUtils.isEmpty(result) || result.getResult().intValue() != 0 || ObjectUtils.isEmpty(result.getRows())) {
|
||||
this.logger.error("查询引擎状态异常,错误原因:{}", result.getInfo());
|
||||
throw new ServiceException("53004123",
|
||||
getMessage("53004123"));
|
||||
}
|
||||
List<EngineListResult.EngineStatus> engines = result.getRows();
|
||||
Boolean online = Boolean.valueOf(false);
|
||||
if (StringUtils.isNotBlank(this.revisionEnginePort)) {
|
||||
for (EngineListResult.EngineStatus status : engines) {
|
||||
if (this.revisionEnginePort.equals(status.getHost().split(":")[1]) && status.getOnline().booleanValue() == true) {
|
||||
online = Boolean.valueOf(true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
EngineResult engineResult = new EngineResult();
|
||||
engineResult.setOnline(online);
|
||||
return CloudwalkResult.success(engineResult);
|
||||
}
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> saveParam(SwitchParam param, CloudwalkCallContext cloudwalkContext) throws ServiceException {
|
||||
String businessId = cloudwalkContext.getCompany().getCompanyId();
|
||||
String caller = cloudwalkContext.getUser().getCaller();
|
||||
try {
|
||||
this.personPropertiesSwitchMapper.deleteByBusinessId(businessId);
|
||||
PersonPropertiesSwitch entry = (PersonPropertiesSwitch)BeanCopyUtils.copyProperties(param, PersonPropertiesSwitch.class);
|
||||
if (entry.getBackgroundParam().equals(Boolean.TRUE)) {
|
||||
if (entry.getBackgroundObject() == null) {
|
||||
return CloudwalkResult.fail("53004130",
|
||||
getMessage("53004130"));
|
||||
}
|
||||
} else {
|
||||
entry.setBackgroundObject(null);
|
||||
}
|
||||
entry.setId(this.uuidSerial.uuid());
|
||||
entry.setBusinessId(businessId);
|
||||
entry.setStatus(Short.valueOf((short)0));
|
||||
entry.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
entry.setCreateUserId(caller);
|
||||
entry.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
entry.setLastUpdateUserId(caller);
|
||||
this.personPropertiesSwitchMapper.insert(entry);
|
||||
return CloudwalkResult.success(Boolean.valueOf(true));
|
||||
} catch (Exception e) {
|
||||
this.logger.error("保存注册图优化参数失败,原因:", e);
|
||||
throw new ServiceException(e);
|
||||
}
|
||||
}
|
||||
public CloudwalkResult<PersonPropertiesSwitchResult> getParam(CloudwalkCallContext cloudwalkContext) throws ServiceException {
|
||||
String businessId = cloudwalkContext.getCompany().getCompanyId();
|
||||
try {
|
||||
PersonPropertiesSwitch entry = this.personPropertiesSwitchMapper.selectByBusinessId(businessId);
|
||||
PersonPropertiesSwitchResult result = ObjectUtils.isEmpty(entry) ? null : (PersonPropertiesSwitchResult)BeanCopyUtils.copyProperties(entry, PersonPropertiesSwitchResult.class);
|
||||
return CloudwalkResult.success(result);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("查询注册图优化参数失败,原因:", e);
|
||||
throw new ServiceException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/ImgPersonPropertiesServiceImpl.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+963
-1023
File diff suppressed because one or more lines are too long
+387
-386
@@ -37,11 +37,9 @@ import cn.cloudwalk.data.organization.mapper.ImgStoreLabelMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonLabelMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.SysLogMapper;
|
||||
import cn.cloudwalk.data.organization.vo.PageLabelVO;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import cn.cloudwalk.service.organization.common.ToolUtil;
|
||||
import cn.cloudwalk.service.organization.service.CpImageStorePersonManager;
|
||||
import cn.cloudwalk.service.organization.service.CpImageStorePersonSynManager;
|
||||
import cn.cloudwalk.service.organization.service.PortalUserServiceImpl;
|
||||
import cn.cloudwalk.service.organization.service.feign.CrkAccessFeignClient;
|
||||
import cn.cloudwalk.service.organization.service.feign.ElevatorFeignClient;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
@@ -69,391 +67,394 @@ import org.springframework.util.ObjectUtils;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
import org.springside.modules.utils.Collections3;
|
||||
|
||||
@Service
|
||||
public class LabelServiceImpl
|
||||
extends AbstractImagStoreService
|
||||
implements LabelService {
|
||||
@Resource
|
||||
private ElevatorFeignClient elevatorFeignClient;
|
||||
@Resource
|
||||
private CrkAccessFeignClient crkAccessFeignClient;
|
||||
@Autowired
|
||||
private ImgStoreLabelMapper imgStoreLabelMapper;
|
||||
@Autowired
|
||||
private ImgStorePersonMapper personMapper;
|
||||
@Autowired
|
||||
private ImgStorePersonLabelMapper imgStorePersonLabelMapper;
|
||||
@Autowired
|
||||
private CpImageStorePersonSynManager cpImageStorePersonSynManager;
|
||||
@Resource
|
||||
private CpImageStorePersonManager cpImageStorePersonManager;
|
||||
@Autowired
|
||||
private SysLogMapper sysLogMapper;
|
||||
@Resource
|
||||
private PortalUserServiceImpl portalUserService;
|
||||
private static final short IS_DEL = 1;
|
||||
private static final short IS_NOT_DEL = 0;
|
||||
@Value(value="${download.rows.of.page:5000}")
|
||||
private int rowsOfPage;
|
||||
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<String> add(AddLabelParam addLabelParam, CloudwalkCallContext context) {
|
||||
String businessId = StringUtils.isEmpty((CharSequence)addLabelParam.getBusinessId()) ? context.getCompany().getCompanyId() : addLabelParam.getBusinessId();
|
||||
Short addType = ObjectUtils.isEmpty((Object)addLabelParam.getAddType()) ? (short)0 : addLabelParam.getAddType();
|
||||
Integer count = this.imgStoreLabelMapper.countByName(addLabelParam.getName(), businessId);
|
||||
if (count != null && count != 0) {
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
String code = addLabelParam.getCode();
|
||||
if (StringUtils.isNotBlank((CharSequence)code) && (count = this.imgStoreLabelMapper.countByCode(code, businessId)) != null && count != 0) {
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
Label label = new Label();
|
||||
long time = System.currentTimeMillis();
|
||||
label.setName(addLabelParam.getName());
|
||||
if (StringUtils.isBlank((CharSequence)code)) {
|
||||
code = this.createGeneralCode();
|
||||
}
|
||||
label.setCode(code);
|
||||
label.setId(this.getPrimaryId());
|
||||
label.setCreateTime(Long.valueOf(time));
|
||||
label.setCreateUserId(context.getUser().getCaller());
|
||||
label.setBusinessId(businessId);
|
||||
label.setIsDel(Short.valueOf((short)0));
|
||||
label.setAddType(addType);
|
||||
label.setLastUpdateTime(Long.valueOf(time));
|
||||
label.setLastUpdateUserId(context.getUser().getCaller());
|
||||
SysLog logParam = new SysLog();
|
||||
logParam.setLogType(Integer.valueOf(5));
|
||||
logParam.setRemark(OperationLogEnum.LABEL_ADD.getName() + "-" + label.getName());
|
||||
this.saveSysLog(logParam, context);
|
||||
this.imgStoreLabelMapper.insertSelective(label);
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> edit(EditLabelParam param, CloudwalkCallContext context) {
|
||||
String businessId = StringUtils.isEmpty((CharSequence)param.getBusinessId()) ? context.getCompany().getCompanyId() : param.getBusinessId();
|
||||
GetsLabelDTO getsLabelDTO = new GetsLabelDTO();
|
||||
getsLabelDTO.setId(param.getId());
|
||||
getsLabelDTO.setIsDel(Short.valueOf((short)0));
|
||||
getsLabelDTO.setBusinessId(businessId);
|
||||
List labelList = this.imgStoreLabelMapper.gets(getsLabelDTO);
|
||||
if (labelList.size() == 0) {
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
Label old = (Label)labelList.get(0);
|
||||
Label newLabel = new Label();
|
||||
if (StringUtils.isEmpty((CharSequence)param.getName())) {
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
List labels = this.imgStoreLabelMapper.getLabelByName(param.getName(), businessId);
|
||||
for (Label label : labels) {
|
||||
if (label.getId().equals(param.getId())) continue;
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
newLabel.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
newLabel.setLastUpdateUserId(context.getUser().getCaller());
|
||||
newLabel.setId(old.getId());
|
||||
newLabel.setName(param.getName());
|
||||
newLabel.setAddType(old.getAddType());
|
||||
SysLog logParam = new SysLog();
|
||||
logParam.setLogType(Integer.valueOf(3));
|
||||
logParam.setRemark(OperationLogEnum.LABEL_EDIT.getName() + "-" + param.getName());
|
||||
this.saveSysLog(logParam, context);
|
||||
this.imgStoreLabelMapper.updateByPrimaryKeySelective(newLabel);
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> delete(DelLabelParam delLabelParam, CloudwalkCallContext context) {
|
||||
String businessId = StringUtils.isEmpty((CharSequence)delLabelParam.getBusinessId()) ? context.getCompany().getCompanyId() : delLabelParam.getBusinessId();
|
||||
Set personIdsByLabelIds = this.imgStorePersonLabelMapper.getPersonIdsByLabelIds(Collections.singletonList(delLabelParam.getId()));
|
||||
if (!CollectionUtils.isEmpty((Collection)personIdsByLabelIds)) {
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
GetsLabelDTO getsLabelDTO = new GetsLabelDTO();
|
||||
getsLabelDTO.setId(delLabelParam.getId());
|
||||
getsLabelDTO.setIsDel(Short.valueOf((short)0));
|
||||
getsLabelDTO.setBusinessId(businessId);
|
||||
List labelList = this.imgStoreLabelMapper.gets(getsLabelDTO);
|
||||
if (labelList.size() == 0) {
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
Label label = (Label)labelList.get(0);
|
||||
label.setIsDel(Short.valueOf((short)1));
|
||||
label.setLastUpdateUserId(context.getUser().getCaller());
|
||||
label.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.imgStoreLabelMapper.updateByPrimaryKeySelective(label);
|
||||
ImgStorePersonLabel del = new ImgStorePersonLabel();
|
||||
del.setLabelId(label.getId());
|
||||
SysLog logParam = new SysLog();
|
||||
logParam.setLogType(Integer.valueOf(6));
|
||||
logParam.setRemark(OperationLogEnum.LABEL_DELETE.getName() + "-" + ((Label)labelList.get(0)).getName());
|
||||
this.saveSysLog(logParam, context);
|
||||
this.imgStorePersonLabelMapper.delete(del);
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
public CloudwalkResult<CloudwalkPageAble<PageLabelResult>> page(PageLabelParam pageLabelParam, CloudwalkCallContext context) {
|
||||
String businessId = StringUtils.isEmpty((CharSequence)pageLabelParam.getBusinessId()) ? context.getCompany().getCompanyId() : pageLabelParam.getBusinessId();
|
||||
CloudwalkPageAble pageAble = null;
|
||||
CloudwalkPageInfo page = new CloudwalkPageInfo(pageLabelParam.getCurrentPage(), pageLabelParam.getRowsOfPage());
|
||||
Page ret = null;
|
||||
try {
|
||||
PageHelper.startPage((int)pageLabelParam.getCurrentPage(), (int)pageLabelParam.getRowsOfPage());
|
||||
PageHelper.orderBy((String)"CREATE_TIME DESC");
|
||||
PageLabelDTO pageLabelDTO = (PageLabelDTO)BeanCopyUtils.copyProperties((Object)pageLabelParam, PageLabelDTO.class);
|
||||
pageLabelDTO.setBusinessId(businessId);
|
||||
ret = (Page)this.imgStoreLabelMapper.page(pageLabelDTO);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("分页查询异常,e:{}", (Object)e.getMessage());
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
List res = BeanCopyUtils.copy((Collection)ret.getResult(), PageLabelResult.class);
|
||||
ArrayList<String> labelIds = new ArrayList<String>();
|
||||
List<String> userIdList = res.stream().flatMap(item -> Stream.of(item.getCreateUserId(), item.getLastUpdateUserId())).filter(Objects::nonNull).distinct().collect(Collectors.toList());
|
||||
Map<String, String> userNameMap = this.portalUserService.query(userIdList).stream().collect(Collectors.toMap(UserQueryResult::getId, UserQueryResult::getName));
|
||||
for (PageLabelResult result : res) {
|
||||
labelIds.add(result.getId());
|
||||
result.setCreateUserName(userNameMap.get(result.getCreateUserId()));
|
||||
result.setLastUpdateUserName(userNameMap.get(result.getLastUpdateUserId()));
|
||||
}
|
||||
if (labelIds.size() > 0) {
|
||||
List counts = this.imgStoreLabelMapper.getCountByLabels(labelIds);
|
||||
HashMap<String, Integer> map = new HashMap<String, Integer>();
|
||||
for (LabelCountDTO labelCountDTO : counts) {
|
||||
map.put(labelCountDTO.getId(), labelCountDTO.getCount());
|
||||
}
|
||||
for (PageLabelResult pageLabelResult : res) {
|
||||
Integer count = (Integer)map.get(pageLabelResult.getId());
|
||||
if (count != null) {
|
||||
pageLabelResult.setPersonCount(count);
|
||||
continue;
|
||||
}
|
||||
pageLabelResult.setPersonCount(Integer.valueOf(0));
|
||||
}
|
||||
}
|
||||
pageAble = new CloudwalkPageAble((Collection)res, page, ret.getTotal());
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
public CloudwalkResult<List<PageLabelResult>> listByPage(PageLabelParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId = StringUtils.isEmpty((CharSequence)param.getBusinessId()) ? context.getCompany().getCompanyId() : param.getBusinessId();
|
||||
try {
|
||||
GetsLabelDTO dto = (GetsLabelDTO)BeanCopyUtils.copyProperties((Object)param, (Object)new GetsLabelDTO());
|
||||
dto.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
dto.setBusinessId(businessId);
|
||||
long s1 = System.currentTimeMillis();
|
||||
int totalCount = this.imgStoreLabelMapper.count(dto);
|
||||
long e1 = System.currentTimeMillis();
|
||||
this.logger.info("标签导出查询总数{},耗时{}毫秒", (Object)totalCount, (Object)(e1 - s1));
|
||||
int totalPage = 1;
|
||||
if (totalCount != 0) {
|
||||
totalPage = totalCount % this.rowsOfPage == 0 ? totalCount / this.rowsOfPage : totalCount / this.rowsOfPage + 1;
|
||||
}
|
||||
ArrayList personList = Lists.newArrayListWithCapacity((int)totalCount);
|
||||
for (int i = 1; i <= totalPage; ++i) {
|
||||
PageHelper.startPage((int)i, (int)this.rowsOfPage);
|
||||
PageHelper.orderBy((String)"LAST_UPDATE_TIME DESC, ID DESC");
|
||||
this.logger.info("分页查询标签信息列表,查询参数:[{}]", (Object)JSON.toJSONString((Object)dto));
|
||||
long s2 = System.currentTimeMillis();
|
||||
Page gets = (Page)this.imgStoreLabelMapper.gets(dto);
|
||||
long e2 = System.currentTimeMillis();
|
||||
this.logger.info("标签导出第{}次分页查询,耗时{}毫秒", (Object)i, (Object)(e2 - s2));
|
||||
personList.addAll(gets.getResult());
|
||||
}
|
||||
List res = BeanCopyUtils.copy((Collection)personList, PageLabelResult.class);
|
||||
ArrayList<String> labelIds = new ArrayList<String>();
|
||||
for (PageLabelResult labelResult : res) {
|
||||
labelIds.add(labelResult.getId());
|
||||
}
|
||||
if (labelIds.size() > 0) {
|
||||
List counts = this.imgStoreLabelMapper.getCountByLabels(labelIds);
|
||||
HashMap<String, Integer> map = new HashMap<String, Integer>();
|
||||
for (LabelCountDTO labelCountDTO : counts) {
|
||||
map.put(labelCountDTO.getId(), labelCountDTO.getCount());
|
||||
}
|
||||
for (PageLabelResult pageLabelResult : res) {
|
||||
Integer count = (Integer)map.get(pageLabelResult.getId());
|
||||
if (count != null) {
|
||||
pageLabelResult.setPersonCount(count);
|
||||
} else {
|
||||
pageLabelResult.setPersonCount(Integer.valueOf(0));
|
||||
}
|
||||
AcsDeviceRestructureConditionForm conditionForm = new AcsDeviceRestructureConditionForm();
|
||||
conditionForm.setLabelId(pageLabelResult.getId());
|
||||
conditionForm.setBusinessId(context.getCompany().getCompanyId());
|
||||
CloudwalkResult<List<AcsDeviceNewResult>> deviceList = this.crkAccessFeignClient.listCondition(conditionForm);
|
||||
if (!CollectionUtils.isEmpty((Collection)((Collection)deviceList.getData()))) {
|
||||
String online = "";
|
||||
String offline = "";
|
||||
for (int i = 0; i < ((List)deviceList.getData()).size(); ++i) {
|
||||
if ("2".equals(((AcsDeviceNewResult)((List)deviceList.getData()).get(i)).getDeviceOnlineStatus())) {
|
||||
if ("".equals(online)) {
|
||||
online = online + ((AcsDeviceNewResult)((List)deviceList.getData()).get(i)).getDeviceName();
|
||||
continue;
|
||||
}
|
||||
online = online + "," + ((AcsDeviceNewResult)((List)deviceList.getData()).get(i)).getDeviceName();
|
||||
continue;
|
||||
}
|
||||
offline = "".equals(offline) ? offline + ((AcsDeviceNewResult)((List)deviceList.getData()).get(i)).getDeviceName() : offline + ',' + ((AcsDeviceNewResult)((List)deviceList.getData()).get(i)).getDeviceName();
|
||||
}
|
||||
pageLabelResult.setOnlineDevices(online);
|
||||
pageLabelResult.setOfflineDevices(offline);
|
||||
}
|
||||
AcsRestructureQueryForm acsPassRuleImageForm = new AcsRestructureQueryForm();
|
||||
acsPassRuleImageForm.setLabelId(pageLabelResult.getId());
|
||||
acsPassRuleImageForm.setBusinessId(businessId);
|
||||
CloudwalkResult<List<AcsDeviceRestructureResult>> images = this.elevatorFeignClient.listCondition(acsPassRuleImageForm);
|
||||
if (!"00000000".equals(images.getCode())) continue;
|
||||
ArrayList<String> floorList = new ArrayList<String>();
|
||||
String zoneNames = "";
|
||||
List acsPassRuleImageResultDtoList = (List)images.getData();
|
||||
for (int i = 0; i < acsPassRuleImageResultDtoList.size(); ++i) {
|
||||
if (i > 0) {
|
||||
zoneNames = zoneNames + ",";
|
||||
}
|
||||
zoneNames = zoneNames + ((AcsDeviceRestructureResult)acsPassRuleImageResultDtoList.get(i)).getZoneName();
|
||||
floorList.add(((AcsDeviceRestructureResult)acsPassRuleImageResultDtoList.get(i)).getZoneId());
|
||||
}
|
||||
pageLabelResult.setFloorNames(zoneNames);
|
||||
}
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("执行报错 {}: {}", (Object)e.getClass().getName(), (Object)e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public CloudwalkResult<List<LabelResult>> getAllLabels(PageLabelParam param, CloudwalkCallContext context) {
|
||||
GetsLabelDTO pageLabelDTO = (GetsLabelDTO)BeanCopyUtils.copyProperties((Object)param, GetsLabelDTO.class);
|
||||
pageLabelDTO.setBusinessId(StringUtils.isEmpty((CharSequence)param.getBusinessId()) ? context.getCompany().getCompanyId() : param.getBusinessId());
|
||||
List allLabels = this.imgStoreLabelMapper.getAllLabels(pageLabelDTO);
|
||||
List labelResults = BeanCopyUtils.copy((Collection)allLabels, LabelResult.class);
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> addPerson(LabelAddPersonParam personParam, CloudwalkCallContext context) {
|
||||
String businessId = StringUtils.isEmpty((CharSequence)personParam.getBusinessId()) ? context.getCompany().getCompanyId() : personParam.getBusinessId();
|
||||
Label lab = this.imgStoreLabelMapper.selectByPrimaryKey(personParam.getLabelId());
|
||||
if (lab == null || lab.getIsDel() == 1 || !businessId.equals(lab.getBusinessId())) {
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
if (personParam.getPersonIds() == null || personParam.getPersonIds().size() == 0) {
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
SysLog logParam = new SysLog();
|
||||
logParam.setLogType(Integer.valueOf(5));
|
||||
logParam.setRemark(OperationLogEnum.LABEL_PERSON_ADD.getName());
|
||||
this.saveSysLog(logParam, context);
|
||||
List personIds = this.imgStoreLabelMapper.getPersonIdInRef((AddPersonLabelDTO)BeanCopyUtils.copyProperties((Object)personParam, AddPersonLabelDTO.class));
|
||||
if (personIds.size() > 0) {
|
||||
personParam.getPersonIds().removeAll(personIds);
|
||||
}
|
||||
if (personParam.getPersonIds().size() == 0) {
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
ImgStorePersonQueryDto dto = new ImgStorePersonQueryDto();
|
||||
dto.setIds((Collection)personParam.getPersonIds());
|
||||
dto.setBusinessId(businessId);
|
||||
dto.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
if (this.personMapper.gets(dto).size() != personParam.getPersonIds().size()) {
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
ArrayList<ImgStorePersonLabel> labels = new ArrayList<ImgStorePersonLabel>();
|
||||
long time = System.currentTimeMillis();
|
||||
for (String id : personParam.getPersonIds()) {
|
||||
ImgStorePersonLabel label = new ImgStorePersonLabel();
|
||||
label.setId(this.getPrimaryId());
|
||||
label.setCreateUserId(context.getUser().getCaller());
|
||||
label.setLabelId(personParam.getLabelId());
|
||||
label.setLastUpdateUserId(context.getUser().getCaller());
|
||||
label.setPersonId(id);
|
||||
label.setCreateTime(Long.valueOf(time));
|
||||
label.setLastUpdateTime(Long.valueOf(time));
|
||||
labels.add(label);
|
||||
}
|
||||
this.imgStoreLabelMapper.batchInsert(labels);
|
||||
ImgStorePersonBatchUpdateDto record = new ImgStorePersonBatchUpdateDto();
|
||||
record.setIds(personParam.getPersonIds());
|
||||
record.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.personMapper.updateBatchByIds(record);
|
||||
List<String> imageIdResultList = this.cpImageStorePersonSynManager.addGroupPersonSynTask(personParam.getLabelId(), (List<String>)personParam.getPersonIds(), true);
|
||||
if (Collections3.isNotEmpty(imageIdResultList)) {
|
||||
imageIdResultList.parallelStream().forEach(imageId -> this.cpImageStorePersonSynManager.handleGroupPersonSynTask((String)imageId));
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> delPerson(DelPersonLabelParam param, CloudwalkCallContext context) {
|
||||
GetsLabelDTO getsLabelDTO = new GetsLabelDTO();
|
||||
getsLabelDTO.setId(param.getLabelId());
|
||||
getsLabelDTO.setBusinessId(StringUtils.isEmpty((CharSequence)param.getBusinessId()) ? context.getCompany().getCompanyId() : param.getBusinessId());
|
||||
List labelList = this.imgStoreLabelMapper.gets(getsLabelDTO);
|
||||
if (labelList.size() == 0) {
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
if (param.getPersonIds() != null && param.getPersonIds().size() > 0) {
|
||||
SysLog logParam = new SysLog();
|
||||
logParam.setLogType(Integer.valueOf(6));
|
||||
logParam.setRemark(OperationLogEnum.LABEL_PERSON_DELETE.getName());
|
||||
this.saveSysLog(logParam, context);
|
||||
this.imgStoreLabelMapper.deletePerson((DelPersonLabelDTO)BeanCopyUtils.copyProperties((Object)param, DelPersonLabelDTO.class));
|
||||
ImgStorePersonBatchUpdateDto record = new ImgStorePersonBatchUpdateDto();
|
||||
record.setIds(param.getPersonIds());
|
||||
record.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.personMapper.updateBatchByIds(record);
|
||||
List<String> imageIdResultList = this.cpImageStorePersonSynManager.addGroupPersonSynTask(param.getLabelId(), (List<String>)param.getPersonIds(), false);
|
||||
if (Collections3.isNotEmpty(imageIdResultList)) {
|
||||
imageIdResultList.parallelStream().forEach(imageId -> this.cpImageStorePersonSynManager.handleGroupPersonSynTask((String)imageId));
|
||||
}
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
public CloudwalkResult<LabelResult> detail(PageLabelParam param, CloudwalkCallContext context) {
|
||||
LabelResult labelResult = null;
|
||||
GetsLabelDTO getsLabelDTO = new GetsLabelDTO();
|
||||
getsLabelDTO.setId(param.getId());
|
||||
getsLabelDTO.setName(param.getName());
|
||||
getsLabelDTO.setCode(param.getCode());
|
||||
getsLabelDTO.setBusinessId(StringUtils.isEmpty((CharSequence)param.getBusinessId()) ? context.getCompany().getCompanyId() : param.getBusinessId());
|
||||
List labelList = this.imgStoreLabelMapper.gets(getsLabelDTO);
|
||||
if (labelList != null && labelList.size() > 0) {
|
||||
Label label = (Label)labelList.get(0);
|
||||
labelResult = (LabelResult)BeanCopyUtils.copyProperties((Object)label, LabelResult.class);
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
private void saveSysLog(SysLog param, CloudwalkCallContext context) {
|
||||
param.setId(this.getPrimaryId());
|
||||
param.setLoginName(context.getUser().getCallerName());
|
||||
param.setContactPerson(param.getLoginName());
|
||||
param.setCreateUserId(context.getUser().getCaller());
|
||||
param.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
param.setLastUpdateTime(param.getCreateTime());
|
||||
param.setLastUpdateUserId(param.getCreateUserId());
|
||||
param.setBusinessId(context.getCompany().getCompanyId());
|
||||
param.setServiceCode("imgstoreApp");
|
||||
param.setModule("label");
|
||||
param.setStatus(Integer.valueOf(1));
|
||||
ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
|
||||
HttpServletRequest request = requestAttributes.getRequest();
|
||||
param.setIp(ToolUtil.getClientIp(request));
|
||||
try {
|
||||
this.sysLogMapper.addLog(param);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("新增系统操作日志失败,失败原因是:{}", e);
|
||||
}
|
||||
}
|
||||
implements LabelService
|
||||
{
|
||||
@Resource
|
||||
private ElevatorFeignClient elevatorFeignClient;
|
||||
@Resource
|
||||
private CrkAccessFeignClient crkAccessFeignClient;
|
||||
@Autowired
|
||||
private ImgStoreLabelMapper imgStoreLabelMapper;
|
||||
@Autowired
|
||||
private ImgStorePersonMapper personMapper;
|
||||
@Autowired
|
||||
private ImgStorePersonLabelMapper imgStorePersonLabelMapper;
|
||||
@Autowired
|
||||
private CpImageStorePersonSynManager cpImageStorePersonSynManager;
|
||||
@Resource
|
||||
private CpImageStorePersonManager cpImageStorePersonManager;
|
||||
@Autowired
|
||||
private SysLogMapper sysLogMapper;
|
||||
@Resource
|
||||
private PortalUserServiceImpl portalUserService;
|
||||
private static final short IS_DEL = 1;
|
||||
private static final short IS_NOT_DEL = 0;
|
||||
@Value("${download.rows.of.page:5000}")
|
||||
private int rowsOfPage;
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<String> add(AddLabelParam addLabelParam, CloudwalkCallContext context) {
|
||||
String businessId = StringUtils.isEmpty(addLabelParam.getBusinessId()) ? context.getCompany().getCompanyId() : addLabelParam.getBusinessId();
|
||||
Short addType = Short.valueOf(ObjectUtils.isEmpty(addLabelParam.getAddType()) ? 0 : addLabelParam.getAddType().shortValue());
|
||||
Integer count = this.imgStoreLabelMapper.countByName(addLabelParam.getName(), businessId);
|
||||
if (count != null && count.intValue() != 0) {
|
||||
return CloudwalkResult.fail("53003700", getMessage("53003700"));
|
||||
}
|
||||
String code = addLabelParam.getCode();
|
||||
if (StringUtils.isNotBlank(code)) {
|
||||
count = this.imgStoreLabelMapper.countByCode(code, businessId);
|
||||
if (count != null && count.intValue() != 0) {
|
||||
return CloudwalkResult.fail("53003705", getMessage("53003705"));
|
||||
}
|
||||
}
|
||||
Label label = new Label();
|
||||
long time = System.currentTimeMillis();
|
||||
label.setName(addLabelParam.getName());
|
||||
if (StringUtils.isBlank(code)) {
|
||||
code = createGeneralCode();
|
||||
}
|
||||
label.setCode(code);
|
||||
label.setId(getPrimaryId());
|
||||
label.setCreateTime(Long.valueOf(time));
|
||||
label.setCreateUserId(context.getUser().getCaller());
|
||||
label.setBusinessId(businessId);
|
||||
label.setIsDel(Short.valueOf((short)0));
|
||||
label.setAddType(addType);
|
||||
label.setLastUpdateTime(Long.valueOf(time));
|
||||
label.setLastUpdateUserId(context.getUser().getCaller());
|
||||
SysLog logParam = new SysLog();
|
||||
logParam.setLogType(Integer.valueOf(5));
|
||||
logParam.setRemark(OperationLogEnum.LABEL_ADD.getName() + "-" + label.getName());
|
||||
saveSysLog(logParam, context);
|
||||
this.imgStoreLabelMapper.insertSelective(label);
|
||||
return CloudwalkResult.success(label.getId());
|
||||
}
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> edit(EditLabelParam param, CloudwalkCallContext context) {
|
||||
String businessId = StringUtils.isEmpty(param.getBusinessId()) ? context.getCompany().getCompanyId() : param.getBusinessId();
|
||||
GetsLabelDTO getsLabelDTO = new GetsLabelDTO();
|
||||
getsLabelDTO.setId(param.getId());
|
||||
getsLabelDTO.setIsDel(Short.valueOf((short)0));
|
||||
getsLabelDTO.setBusinessId(businessId);
|
||||
List<Label> labelList = this.imgStoreLabelMapper.gets(getsLabelDTO);
|
||||
if (labelList.size() == 0) {
|
||||
return CloudwalkResult.fail("53003701", getMessage("53003701"));
|
||||
}
|
||||
Label old = labelList.get(0);
|
||||
Label newLabel = new Label();
|
||||
if (StringUtils.isEmpty(param.getName())) {
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
List<Label> labels = this.imgStoreLabelMapper.getLabelByName(param.getName(), businessId);
|
||||
for (Label label : labels) {
|
||||
if (!label.getId().equals(param.getId())) {
|
||||
return CloudwalkResult.fail("53003700", getMessage("53003700"));
|
||||
}
|
||||
}
|
||||
newLabel.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
newLabel.setLastUpdateUserId(context.getUser().getCaller());
|
||||
newLabel.setId(old.getId());
|
||||
newLabel.setName(param.getName());
|
||||
newLabel.setAddType(old.getAddType());
|
||||
SysLog logParam = new SysLog();
|
||||
logParam.setLogType(Integer.valueOf(3));
|
||||
logParam.setRemark(OperationLogEnum.LABEL_EDIT.getName() + "-" + param.getName());
|
||||
saveSysLog(logParam, context);
|
||||
this.imgStoreLabelMapper.updateByPrimaryKeySelective(newLabel);
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> delete(DelLabelParam delLabelParam, CloudwalkCallContext context) {
|
||||
String businessId = StringUtils.isEmpty(delLabelParam.getBusinessId()) ? context.getCompany().getCompanyId() : delLabelParam.getBusinessId();
|
||||
Set<String> personIdsByLabelIds = this.imgStorePersonLabelMapper.getPersonIdsByLabelIds(Collections.singletonList(delLabelParam.getId()));
|
||||
if (!CollectionUtils.isEmpty(personIdsByLabelIds)) {
|
||||
return CloudwalkResult.fail("53003707", getMessage("53003707"));
|
||||
}
|
||||
GetsLabelDTO getsLabelDTO = new GetsLabelDTO();
|
||||
getsLabelDTO.setId(delLabelParam.getId());
|
||||
getsLabelDTO.setIsDel(Short.valueOf((short)0));
|
||||
getsLabelDTO.setBusinessId(businessId);
|
||||
List<Label> labelList = this.imgStoreLabelMapper.gets(getsLabelDTO);
|
||||
if (labelList.size() == 0) {
|
||||
return CloudwalkResult.fail("53003701", getMessage("53003701"));
|
||||
}
|
||||
Label label = labelList.get(0);
|
||||
label.setIsDel(Short.valueOf((short)1));
|
||||
label.setLastUpdateUserId(context.getUser().getCaller());
|
||||
label.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.imgStoreLabelMapper.updateByPrimaryKeySelective(label);
|
||||
ImgStorePersonLabel del = new ImgStorePersonLabel();
|
||||
del.setLabelId(label.getId());
|
||||
SysLog logParam = new SysLog();
|
||||
logParam.setLogType(Integer.valueOf(6));
|
||||
logParam.setRemark(OperationLogEnum.LABEL_DELETE.getName() + "-" + ((Label)labelList.get(0)).getName());
|
||||
saveSysLog(logParam, context);
|
||||
this.imgStorePersonLabelMapper.delete(del);
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
public CloudwalkResult<CloudwalkPageAble<PageLabelResult>> page(PageLabelParam pageLabelParam, CloudwalkCallContext context) {
|
||||
String businessId = StringUtils.isEmpty(pageLabelParam.getBusinessId()) ? context.getCompany().getCompanyId() : pageLabelParam.getBusinessId();
|
||||
CloudwalkPageAble<PageLabelResult> pageAble = null;
|
||||
CloudwalkPageInfo page = new CloudwalkPageInfo(pageLabelParam.getCurrentPage(), pageLabelParam.getRowsOfPage());
|
||||
Page<PageLabelVO> ret = null;
|
||||
try {
|
||||
PageHelper.startPage(pageLabelParam.getCurrentPage(), pageLabelParam.getRowsOfPage());
|
||||
PageHelper.orderBy("CREATE_TIME DESC");
|
||||
PageLabelDTO pageLabelDTO = (PageLabelDTO)BeanCopyUtils.copyProperties(pageLabelParam, PageLabelDTO.class);
|
||||
pageLabelDTO.setBusinessId(businessId);
|
||||
ret = (Page<PageLabelVO>)this.imgStoreLabelMapper.page(pageLabelDTO);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("分页查询异常,e:{}", e.getMessage());
|
||||
return CloudwalkResult.fail("53003702", getMessage("53003702"));
|
||||
}
|
||||
List<PageLabelResult> res = BeanCopyUtils.copy(ret.getResult(), PageLabelResult.class);
|
||||
List<String> labelIds = new ArrayList<>();
|
||||
List<String> userIdList = (List<String>)res.stream().flatMap(item -> Stream.of(new String[] { item.getCreateUserId(), item.getLastUpdateUserId() })).filter(Objects::nonNull).distinct().collect(Collectors.toList());
|
||||
Map<String, String> userNameMap = (Map<String, String>)this.portalUserService.query(userIdList).stream().collect(Collectors.toMap(UserQueryResult::getId, UserQueryResult::getName));
|
||||
for (PageLabelResult result : res) {
|
||||
labelIds.add(result.getId());
|
||||
result.setCreateUserName(userNameMap.get(result.getCreateUserId()));
|
||||
result.setLastUpdateUserName(userNameMap.get(result.getLastUpdateUserId()));
|
||||
}
|
||||
if (labelIds.size() > 0) {
|
||||
List<LabelCountDTO> counts = this.imgStoreLabelMapper.getCountByLabels(labelIds);
|
||||
Map<String, Integer> map = new HashMap<>();
|
||||
for (LabelCountDTO labelCountDTO : counts) {
|
||||
map.put(labelCountDTO.getId(), labelCountDTO.getCount());
|
||||
}
|
||||
for (PageLabelResult pageLabelResult : res) {
|
||||
Integer count = map.get(pageLabelResult.getId());
|
||||
if (count != null) {
|
||||
pageLabelResult.setPersonCount(count); continue;
|
||||
}
|
||||
pageLabelResult.setPersonCount(Integer.valueOf(0));
|
||||
}
|
||||
}
|
||||
pageAble = new CloudwalkPageAble(res, page, ret.getTotal());
|
||||
return CloudwalkResult.success(pageAble);
|
||||
}
|
||||
public CloudwalkResult<List<PageLabelResult>> listByPage(PageLabelParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId = StringUtils.isEmpty(param.getBusinessId()) ? context.getCompany().getCompanyId() : param.getBusinessId();
|
||||
try {
|
||||
GetsLabelDTO dto = (GetsLabelDTO)BeanCopyUtils.copyProperties(param, new GetsLabelDTO());
|
||||
dto.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
dto.setBusinessId(businessId);
|
||||
long s1 = System.currentTimeMillis();
|
||||
int totalCount = this.imgStoreLabelMapper.count(dto);
|
||||
long e1 = System.currentTimeMillis();
|
||||
this.logger.info("标签导出查询总数{},耗时{}毫秒", Integer.valueOf(totalCount), Long.valueOf(e1 - s1));
|
||||
int totalPage = 1;
|
||||
if (totalCount != 0) {
|
||||
totalPage = (totalCount % this.rowsOfPage == 0) ? (totalCount / this.rowsOfPage) : (totalCount / this.rowsOfPage + 1);
|
||||
}
|
||||
List<Label> personList = Lists.newArrayListWithCapacity(totalCount);
|
||||
for (int i = 1; i <= totalPage; i++) {
|
||||
PageHelper.startPage(i, this.rowsOfPage);
|
||||
PageHelper.orderBy("LAST_UPDATE_TIME DESC, ID DESC");
|
||||
this.logger.info("分页查询标签信息列表,查询参数:[{}]", JSON.toJSONString(dto));
|
||||
long s2 = System.currentTimeMillis();
|
||||
Page<Label> gets = (Page<Label>)this.imgStoreLabelMapper.gets(dto);
|
||||
long e2 = System.currentTimeMillis();
|
||||
this.logger.info("标签导出第{}次分页查询,耗时{}毫秒", Integer.valueOf(i), Long.valueOf(e2 - s2));
|
||||
personList.addAll(gets.getResult());
|
||||
}
|
||||
List<PageLabelResult> res = BeanCopyUtils.copy(personList, PageLabelResult.class);
|
||||
List<String> labelIds = new ArrayList<>();
|
||||
for (PageLabelResult labelResult : res) {
|
||||
labelIds.add(labelResult.getId());
|
||||
}
|
||||
if (labelIds.size() > 0) {
|
||||
List<LabelCountDTO> counts = this.imgStoreLabelMapper.getCountByLabels(labelIds);
|
||||
Map<String, Integer> map = new HashMap<>();
|
||||
for (LabelCountDTO labelCountDTO : counts) {
|
||||
map.put(labelCountDTO.getId(), labelCountDTO.getCount());
|
||||
}
|
||||
for (PageLabelResult pageLabelResult : res) {
|
||||
Integer count = map.get(pageLabelResult.getId());
|
||||
if (count != null) {
|
||||
pageLabelResult.setPersonCount(count);
|
||||
} else {
|
||||
pageLabelResult.setPersonCount(Integer.valueOf(0));
|
||||
}
|
||||
AcsDeviceRestructureConditionForm conditionForm = new AcsDeviceRestructureConditionForm();
|
||||
conditionForm.setLabelId(pageLabelResult.getId());
|
||||
conditionForm.setBusinessId(context.getCompany().getCompanyId());
|
||||
CloudwalkResult<List<AcsDeviceNewResult>> deviceList = this.crkAccessFeignClient.listCondition(conditionForm);
|
||||
if (!CollectionUtils.isEmpty((Collection)deviceList.getData())) {
|
||||
String online = "";
|
||||
String offline = "";
|
||||
for (int j = 0; j < ((List)deviceList.getData()).size(); j++) {
|
||||
if ("2".equals(((AcsDeviceNewResult)((List<AcsDeviceNewResult>)deviceList.getData()).get(j)).getDeviceOnlineStatus())) {
|
||||
if ("".equals(online)) {
|
||||
online = online + ((AcsDeviceNewResult)((List<AcsDeviceNewResult>)deviceList.getData()).get(j)).getDeviceName();
|
||||
} else {
|
||||
online = online + "," + ((AcsDeviceNewResult)((List<AcsDeviceNewResult>)deviceList.getData()).get(j)).getDeviceName();
|
||||
}
|
||||
} else if ("".equals(offline)) {
|
||||
offline = offline + ((AcsDeviceNewResult)((List<AcsDeviceNewResult>)deviceList.getData()).get(j)).getDeviceName();
|
||||
} else {
|
||||
offline = offline + ',' + ((AcsDeviceNewResult)((List<AcsDeviceNewResult>)deviceList.getData()).get(j)).getDeviceName();
|
||||
}
|
||||
}
|
||||
pageLabelResult.setOnlineDevices(online);
|
||||
pageLabelResult.setOfflineDevices(offline);
|
||||
}
|
||||
AcsRestructureQueryForm acsPassRuleImageForm = new AcsRestructureQueryForm();
|
||||
acsPassRuleImageForm.setLabelId(pageLabelResult.getId());
|
||||
acsPassRuleImageForm.setBusinessId(businessId);
|
||||
CloudwalkResult<List<AcsDeviceRestructureResult>> images = this.elevatorFeignClient.listCondition(acsPassRuleImageForm);
|
||||
if (Objects.equals(images.getCode(), "00000000")) {
|
||||
List<String> floorList = new ArrayList<>();
|
||||
String zoneNames = "";
|
||||
List<AcsDeviceRestructureResult> acsPassRuleImageResultDtoList = (List<AcsDeviceRestructureResult>)images.getData();
|
||||
for (int j = 0; j < acsPassRuleImageResultDtoList.size(); j++) {
|
||||
if (j > 0) {
|
||||
zoneNames = zoneNames + ",";
|
||||
}
|
||||
zoneNames = zoneNames + ((AcsDeviceRestructureResult)acsPassRuleImageResultDtoList.get(j)).getZoneName();
|
||||
floorList.add(((AcsDeviceRestructureResult)acsPassRuleImageResultDtoList.get(j)).getZoneId());
|
||||
}
|
||||
pageLabelResult.setFloorNames(zoneNames);
|
||||
}
|
||||
}
|
||||
}
|
||||
return CloudwalkResult.success(res);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("执行报错 {}: {}", e.getClass().getName(), e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
public CloudwalkResult<List<LabelResult>> getAllLabels(PageLabelParam param, CloudwalkCallContext context) {
|
||||
GetsLabelDTO pageLabelDTO = (GetsLabelDTO)BeanCopyUtils.copyProperties(param, GetsLabelDTO.class);
|
||||
pageLabelDTO.setBusinessId(StringUtils.isEmpty(param.getBusinessId()) ? context.getCompany().getCompanyId() : param.getBusinessId());
|
||||
List<Label> allLabels = this.imgStoreLabelMapper.getAllLabels(pageLabelDTO);
|
||||
List<LabelResult> labelResults = BeanCopyUtils.copy(allLabels, LabelResult.class);
|
||||
return CloudwalkResult.success(labelResults);
|
||||
}
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> addPerson(LabelAddPersonParam personParam, CloudwalkCallContext context) {
|
||||
String businessId = StringUtils.isEmpty(personParam.getBusinessId()) ? context.getCompany().getCompanyId() : personParam.getBusinessId();
|
||||
Label lab = this.imgStoreLabelMapper.selectByPrimaryKey(personParam.getLabelId());
|
||||
if (lab == null || lab.getIsDel().shortValue() == 1 || !businessId.equals(lab.getBusinessId())) {
|
||||
return CloudwalkResult.fail("53003701", getMessage("53003701"));
|
||||
}
|
||||
if (personParam.getPersonIds() == null || personParam.getPersonIds().size() == 0) {
|
||||
return CloudwalkResult.fail("53060411", getMessage("53060411"));
|
||||
}
|
||||
SysLog logParam = new SysLog();
|
||||
logParam.setLogType(Integer.valueOf(5));
|
||||
logParam.setRemark(OperationLogEnum.LABEL_PERSON_ADD.getName());
|
||||
saveSysLog(logParam, context);
|
||||
List<String> personIds = this.imgStoreLabelMapper.getPersonIdInRef((AddPersonLabelDTO)BeanCopyUtils.copyProperties(personParam, AddPersonLabelDTO.class));
|
||||
if (personIds.size() > 0)
|
||||
{
|
||||
personParam.getPersonIds().removeAll(personIds);
|
||||
}
|
||||
if (personParam.getPersonIds().size() == 0)
|
||||
{
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
ImgStorePersonQueryDto dto = new ImgStorePersonQueryDto();
|
||||
dto.setIds(personParam.getPersonIds());
|
||||
dto.setBusinessId(businessId);
|
||||
dto.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
if (this.personMapper.gets(dto).size() != personParam.getPersonIds().size())
|
||||
{
|
||||
return CloudwalkResult.fail("53003311", getMessage("53003311"));
|
||||
}
|
||||
List<ImgStorePersonLabel> labels = new ArrayList<>();
|
||||
long time = System.currentTimeMillis();
|
||||
for (String id : personParam.getPersonIds()) {
|
||||
ImgStorePersonLabel label = new ImgStorePersonLabel();
|
||||
label.setId(getPrimaryId());
|
||||
label.setCreateUserId(context.getUser().getCaller());
|
||||
label.setLabelId(personParam.getLabelId());
|
||||
label.setLastUpdateUserId(context.getUser().getCaller());
|
||||
label.setPersonId(id);
|
||||
label.setCreateTime(Long.valueOf(time));
|
||||
label.setLastUpdateTime(Long.valueOf(time));
|
||||
labels.add(label);
|
||||
}
|
||||
this.imgStoreLabelMapper.batchInsert(labels);
|
||||
ImgStorePersonBatchUpdateDto record = new ImgStorePersonBatchUpdateDto();
|
||||
record.setIds(personParam.getPersonIds());
|
||||
record.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.personMapper.updateBatchByIds(record);
|
||||
List<String> imageIdResultList = this.cpImageStorePersonSynManager.addGroupPersonSynTask(personParam.getLabelId(), personParam.getPersonIds(), true);
|
||||
if (Collections3.isNotEmpty(imageIdResultList)) {
|
||||
imageIdResultList.parallelStream()
|
||||
.forEach(imageId -> this.cpImageStorePersonSynManager.handleGroupPersonSynTask(imageId));
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> delPerson(DelPersonLabelParam param, CloudwalkCallContext context) {
|
||||
GetsLabelDTO getsLabelDTO = new GetsLabelDTO();
|
||||
getsLabelDTO.setId(param.getLabelId());
|
||||
getsLabelDTO.setBusinessId(StringUtils.isEmpty(param.getBusinessId()) ? context.getCompany().getCompanyId() : param.getBusinessId());
|
||||
List<Label> labelList = this.imgStoreLabelMapper.gets(getsLabelDTO);
|
||||
if (labelList.size() == 0) {
|
||||
return CloudwalkResult.fail("53003701", getMessage("53003701"));
|
||||
}
|
||||
if (param.getPersonIds() != null && param.getPersonIds().size() > 0) {
|
||||
SysLog logParam = new SysLog();
|
||||
logParam.setLogType(Integer.valueOf(6));
|
||||
logParam.setRemark(OperationLogEnum.LABEL_PERSON_DELETE.getName());
|
||||
saveSysLog(logParam, context);
|
||||
this.imgStoreLabelMapper.deletePerson((DelPersonLabelDTO)BeanCopyUtils.copyProperties(param, DelPersonLabelDTO.class));
|
||||
ImgStorePersonBatchUpdateDto record = new ImgStorePersonBatchUpdateDto();
|
||||
record.setIds(param.getPersonIds());
|
||||
record.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.personMapper.updateBatchByIds(record);
|
||||
List<String> imageIdResultList = this.cpImageStorePersonSynManager.addGroupPersonSynTask(param.getLabelId(), param.getPersonIds(), false);
|
||||
if (Collections3.isNotEmpty(imageIdResultList)) {
|
||||
imageIdResultList.parallelStream()
|
||||
.forEach(imageId -> this.cpImageStorePersonSynManager.handleGroupPersonSynTask(imageId));
|
||||
}
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
public CloudwalkResult<LabelResult> detail(PageLabelParam param, CloudwalkCallContext context) {
|
||||
LabelResult labelResult = null;
|
||||
GetsLabelDTO getsLabelDTO = new GetsLabelDTO();
|
||||
getsLabelDTO.setId(param.getId());
|
||||
getsLabelDTO.setName(param.getName());
|
||||
getsLabelDTO.setCode(param.getCode());
|
||||
getsLabelDTO.setBusinessId(StringUtils.isEmpty(param.getBusinessId()) ? context.getCompany().getCompanyId() : param.getBusinessId());
|
||||
List<Label> labelList = this.imgStoreLabelMapper.gets(getsLabelDTO);
|
||||
if (labelList != null && labelList.size() > 0) {
|
||||
Label label = labelList.get(0);
|
||||
labelResult = (LabelResult)BeanCopyUtils.copyProperties(label, LabelResult.class);
|
||||
}
|
||||
return CloudwalkResult.success(labelResult);
|
||||
}
|
||||
private void saveSysLog(SysLog param, CloudwalkCallContext context) {
|
||||
param.setId(getPrimaryId());
|
||||
param.setLoginName(context.getUser().getCallerName());
|
||||
param.setContactPerson(param.getLoginName());
|
||||
param.setCreateUserId(context.getUser().getCaller());
|
||||
param.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
param.setLastUpdateTime(param.getCreateTime());
|
||||
param.setLastUpdateUserId(param.getCreateUserId());
|
||||
param.setBusinessId(context.getCompany().getCompanyId());
|
||||
param.setServiceCode("imgstoreApp");
|
||||
param.setModule("label");
|
||||
param.setStatus(Integer.valueOf(1));
|
||||
ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
|
||||
HttpServletRequest request = requestAttributes.getRequest();
|
||||
param.setIp(ToolUtil.getClientIp(request));
|
||||
try {
|
||||
this.sysLogMapper.addLog(param);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("新增系统操作日志失败,失败原因是:{}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/LabelServiceImpl.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+28
-27
@@ -12,35 +12,36 @@ import cn.cloudwalk.data.organization.mapper.OperationLogMapper;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import javax.annotation.Resource;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class OperationLogServiceImpl
|
||||
extends AbstractImagStoreService
|
||||
implements IOperationLogService {
|
||||
@Resource
|
||||
private OperationLogMapper operationLogMapper;
|
||||
|
||||
public CloudwalkResult<Boolean> addLog(OperationLogAddParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
try {
|
||||
OperationLog log = (OperationLog)BeanCopyUtils.copyProperties((Object)param, OperationLog.class);
|
||||
this.operationLogMapper.addLog(log);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("操作日志新增失败,原因:", e);
|
||||
throw new ServiceException(e);
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
public CloudwalkResult<Boolean> delete(OperationLogDelParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
try {
|
||||
this.operationLogMapper.deleteByDelTime(param.getDeleteTime());
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("操作日志删除失败,原因:", e);
|
||||
throw new ServiceException(e);
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
implements IOperationLogService
|
||||
{
|
||||
@Resource
|
||||
private OperationLogMapper operationLogMapper;
|
||||
public CloudwalkResult<Boolean> addLog(OperationLogAddParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
try {
|
||||
OperationLog log = (OperationLog)BeanCopyUtils.copyProperties(param, OperationLog.class);
|
||||
this.operationLogMapper.addLog(log);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("操作日志新增失败,原因:", e);
|
||||
throw new ServiceException(e);
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.valueOf(true));
|
||||
}
|
||||
public CloudwalkResult<Boolean> delete(OperationLogDelParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
try {
|
||||
this.operationLogMapper.deleteByDelTime(param.getDeleteTime());
|
||||
} catch (Exception e) {
|
||||
this.logger.error("操作日志删除失败,原因:", e);
|
||||
throw new ServiceException(e);
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.valueOf(true));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/OperationLogServiceImpl.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+1033
-1037
File diff suppressed because it is too large
Load Diff
+476
@@ -0,0 +1,476 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.common.constant.ImageStoreConstants;
|
||||
import cn.cloudwalk.client.organization.common.enums.OrganizationTypeCodeEnum;
|
||||
import cn.cloudwalk.client.organization.param.QueryOrgTypeParam;
|
||||
import cn.cloudwalk.client.organization.param.organization.AddOrganizationTypeParam;
|
||||
import cn.cloudwalk.client.organization.param.organization.DelOrganizationTypeParam;
|
||||
import cn.cloudwalk.client.organization.param.organization.EditOrganizationTypeParam;
|
||||
import cn.cloudwalk.client.organization.param.organization.OrganizationTypePropertyParam;
|
||||
import cn.cloudwalk.client.organization.result.OrganizationTypeListResult;
|
||||
import cn.cloudwalk.client.organization.result.OrganizationTypePropertyCommonResult;
|
||||
import cn.cloudwalk.client.organization.result.OrganizationTypeResult;
|
||||
import cn.cloudwalk.client.organization.service.OrganizationTypeService;
|
||||
import cn.cloudwalk.cloud.annotation.CloudwalkParamsValidate;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkCallContext;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
import cn.cloudwalk.cloud.page.CloudwalkPageAble;
|
||||
import cn.cloudwalk.cloud.page.CloudwalkPageInfo;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.cloud.utils.BeanCopyUtils;
|
||||
import cn.cloudwalk.cloud.utils.CloudwalkDateUtils;
|
||||
import cn.cloudwalk.data.organization.dto.GetsOrganizationDTO;
|
||||
import cn.cloudwalk.data.organization.dto.OrganizationTypeQueryDto;
|
||||
import cn.cloudwalk.data.organization.entity.Organization;
|
||||
import cn.cloudwalk.data.organization.entity.OrganizationType;
|
||||
import cn.cloudwalk.data.organization.entity.OrganizationTypeProperties;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStoreOrganizationMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStoreOrganizationTypeMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStoreOrganizationTypePropertiesMapper;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import com.github.pagehelper.Page;
|
||||
import com.github.pagehelper.PageHelper;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import javax.annotation.Resource;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
@Primary
|
||||
@Service
|
||||
public class OrganizationTypeServiceImpl
|
||||
extends AbstractImagStoreService
|
||||
implements OrganizationTypeService
|
||||
{
|
||||
@Resource
|
||||
private ImgStoreOrganizationTypeMapper orgTypeMapper;
|
||||
@Resource
|
||||
private ImgStoreOrganizationTypePropertiesMapper orgTypePropertiesMapper;
|
||||
@Resource
|
||||
private ImgStoreOrganizationMapper imgStoreOrganizationMapper;
|
||||
private static final String EXT = "ext";
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<String> add(AddOrganizationTypeParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId;
|
||||
if (StringUtils.isEmpty(param.getBusinessId())) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
} else {
|
||||
businessId = param.getBusinessId();
|
||||
}
|
||||
if (businessId.equals("cloudwalk")) {
|
||||
throw new ServiceException("53003818", getMessage("53003818"));
|
||||
}
|
||||
Set<String> nameMap = new HashSet<>();
|
||||
List<OrganizationTypePropertyParam> properties = param.getProperties();
|
||||
for (OrganizationTypePropertyParam propertyParam : properties) {
|
||||
nameMap.add(propertyParam.getName());
|
||||
}
|
||||
if (nameMap.size() < properties.size()) {
|
||||
throw new ServiceException("53003805", getMessage("53003805"));
|
||||
}
|
||||
OrganizationTypeQueryDto organizationTypeQueryDto = (OrganizationTypeQueryDto)BeanCopyUtils.copyProperties(param, OrganizationTypeQueryDto.class);
|
||||
organizationTypeQueryDto.setStatus(Integer.valueOf(0));
|
||||
organizationTypeQueryDto.setBusinessId(businessId);
|
||||
List<OrganizationType> select = this.orgTypeMapper.selectByCondition(organizationTypeQueryDto);
|
||||
if (!CollectionUtils.isEmpty(select)) {
|
||||
throw new ServiceException("53003803", getMessage("53003803"));
|
||||
}
|
||||
OrganizationType organizationType = (OrganizationType)BeanCopyUtils.copyProperties(param, OrganizationType.class);
|
||||
String uuid = CloudwalkDateUtils.getUUID();
|
||||
organizationType.setId(uuid);
|
||||
organizationType.setBusinessId(businessId);
|
||||
organizationType.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
organizationType.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
organizationType.setCreateUserId(context.getUser().getCaller());
|
||||
organizationType.setLastUpdateUserId(context.getUser().getCaller());
|
||||
this.orgTypeMapper.insertSelective(organizationType);
|
||||
int index = 1;
|
||||
if (!CollectionUtils.isEmpty(properties))
|
||||
{
|
||||
for (OrganizationTypePropertyParam propertyParam : properties) {
|
||||
OrganizationTypeProperties property = (OrganizationTypeProperties)BeanCopyUtils.copyProperties(propertyParam, OrganizationTypeProperties.class);
|
||||
property.setId(CloudwalkDateUtils.getUUID());
|
||||
property.setBusinessId(businessId);
|
||||
property.setOrganizationTypeId(uuid);
|
||||
property.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
property.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
property.setCreateUserId(context.getUser().getCaller());
|
||||
property.setLastUpdateUserId(context.getUser().getCaller());
|
||||
property.setCode("ext" + index++);
|
||||
this.orgTypePropertiesMapper.insertSelective(property);
|
||||
}
|
||||
}
|
||||
return CloudwalkResult.success(uuid);
|
||||
}
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> edit(EditOrganizationTypeParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId;
|
||||
if (StringUtils.isEmpty(param.getBusinessId())) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
} else {
|
||||
businessId = param.getBusinessId();
|
||||
}
|
||||
if (businessId.equals("cloudwalk")) {
|
||||
throw new ServiceException("53003818", getMessage("53003818"));
|
||||
}
|
||||
Set<String> nameMap = new HashSet<>();
|
||||
List<OrganizationTypePropertyParam> properties = param.getProperties();
|
||||
for (OrganizationTypePropertyParam propertyParam : properties) {
|
||||
nameMap.add(propertyParam.getName());
|
||||
}
|
||||
if (nameMap.size() < properties.size()) {
|
||||
throw new ServiceException("53003805", getMessage("53003805"));
|
||||
}
|
||||
OrganizationTypeQueryDto organizationTypeQuery = new OrganizationTypeQueryDto();
|
||||
organizationTypeQuery.setName(param.getName());
|
||||
organizationTypeQuery.setStatus(Integer.valueOf(0));
|
||||
organizationTypeQuery.setBusinessId(businessId);
|
||||
List<OrganizationType> select = this.orgTypeMapper.selectByCondition(organizationTypeQuery);
|
||||
if (!CollectionUtils.isEmpty(select)) {
|
||||
for (OrganizationType type : select) {
|
||||
if (!type.getId().equals(param.getId())) {
|
||||
throw new ServiceException("53003803", getMessage("53003803"));
|
||||
}
|
||||
}
|
||||
}
|
||||
boolean hasOrganization = false;
|
||||
boolean hasChildren = false;
|
||||
GetsOrganizationDTO organizationDTO = new GetsOrganizationDTO();
|
||||
organizationDTO.setTypeId(param.getId());
|
||||
organizationDTO.setIsDel(Short.valueOf((short)0));
|
||||
List<Organization> organizations = this.imgStoreOrganizationMapper.gets(organizationDTO);
|
||||
if (!CollectionUtils.isEmpty(organizations)) {
|
||||
hasOrganization = true;
|
||||
List<String> parentIds = new ArrayList<>();
|
||||
for (Organization organization : organizations) {
|
||||
parentIds.add(organization.getId());
|
||||
}
|
||||
organizationDTO = new GetsOrganizationDTO();
|
||||
organizationDTO.setIsDel(Short.valueOf((short)0));
|
||||
organizationDTO.setParentIds(parentIds);
|
||||
List<Organization> childrens = this.imgStoreOrganizationMapper.gets(organizationDTO);
|
||||
if (childrens != null && childrens.size() > 0) {
|
||||
hasChildren = true;
|
||||
}
|
||||
}
|
||||
if (param.getHasLowerLevel().intValue() == 0 && hasChildren) {
|
||||
throw new ServiceException("53003813", getMessage("53003813"));
|
||||
}
|
||||
OrganizationType organizationType = (OrganizationType)BeanCopyUtils.copyProperties(organizationTypeQuery, OrganizationType.class);
|
||||
organizationType.setId(param.getId());
|
||||
organizationType.setHasLowerLevel(param.getHasLowerLevel());
|
||||
organizationType.setLastUpdateUserId(context.getUser().getCaller());
|
||||
organizationType.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.orgTypeMapper.updateByPrimaryKeySelective(organizationType);
|
||||
OrganizationTypeProperties proQuery = new OrganizationTypeProperties();
|
||||
proQuery.setOrganizationTypeId(param.getId());
|
||||
List<OrganizationTypeProperties> typePropertiesDB = this.orgTypePropertiesMapper.select(proQuery);
|
||||
if (properties != null)
|
||||
{
|
||||
if (CollectionUtils.isEmpty(typePropertiesDB)) {
|
||||
int index = 1;
|
||||
for (OrganizationTypePropertyParam propertyParam : properties) {
|
||||
OrganizationTypeProperties property = (OrganizationTypeProperties)BeanCopyUtils.copyProperties(propertyParam, OrganizationTypeProperties.class);
|
||||
property.setId(CloudwalkDateUtils.getUUID());
|
||||
property.setBusinessId(businessId);
|
||||
property.setOrganizationTypeId(param.getId());
|
||||
property.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
property.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
property.setCreateUserId(context.getUser().getCaller());
|
||||
property.setLastUpdateUserId(context.getUser().getCaller());
|
||||
property.setCode("ext" + index++);
|
||||
property.setStatus(Integer.valueOf(0));
|
||||
this.orgTypePropertiesMapper.insertSelective(property);
|
||||
}
|
||||
} else {
|
||||
Map<String, OrganizationTypeProperties> DBMap = new HashMap<>();
|
||||
Set<String> codeSet = new HashSet<>();
|
||||
for (OrganizationTypeProperties organizationTypeProperties : typePropertiesDB) {
|
||||
String code = organizationTypeProperties.getCode();
|
||||
codeSet.add(code);
|
||||
DBMap.put(organizationTypeProperties.getId(), organizationTypeProperties);
|
||||
}
|
||||
List<OrganizationTypeProperties> newList = BeanCopyUtils.copy(properties, OrganizationTypeProperties.class);
|
||||
List<OrganizationTypeProperties> newListCopy = new ArrayList<>(newList);
|
||||
newListCopy.retainAll(typePropertiesDB);
|
||||
if (!CollectionUtils.isEmpty(newListCopy)) {
|
||||
for (OrganizationTypeProperties organizationTypeProperties : newListCopy) {
|
||||
if (hasOrganization && organizationTypeProperties.getHasRequired().intValue() == 1) {
|
||||
Integer hasRequired = ((OrganizationTypeProperties)DBMap.get(organizationTypeProperties.getId())).getHasRequired();
|
||||
if (hasRequired != null && hasRequired.intValue() == 0) {
|
||||
throw new ServiceException("53003815", getMessage("53003815"));
|
||||
}
|
||||
}
|
||||
organizationTypeProperties.setStatus(Integer.valueOf(0));
|
||||
organizationTypeProperties.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
organizationTypeProperties.setLastUpdateUserId(context.getUser().getCaller());
|
||||
this.orgTypePropertiesMapper.updateByPrimaryKeySelective(organizationTypeProperties);
|
||||
}
|
||||
}
|
||||
typePropertiesDB.removeAll(newListCopy);
|
||||
if (!CollectionUtils.isEmpty(typePropertiesDB)) {
|
||||
for (OrganizationTypeProperties organizationTypeProperties : typePropertiesDB) {
|
||||
organizationTypeProperties.setStatus(Integer.valueOf(1));
|
||||
organizationTypeProperties.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
organizationTypeProperties.setLastUpdateUserId(context.getUser().getCaller());
|
||||
this.orgTypePropertiesMapper.updateByPrimaryKeySelective(organizationTypeProperties);
|
||||
codeSet.remove(organizationTypeProperties.getCode());
|
||||
String typeId = param.getId();
|
||||
String codeProperty = organizationTypeProperties.getCode();
|
||||
this.imgStoreOrganizationMapper.removePropertyByTypeIdAndCode(typeId, codeProperty);
|
||||
}
|
||||
}
|
||||
newList.removeAll(newListCopy);
|
||||
if (!CollectionUtils.isEmpty(newList)) {
|
||||
for (OrganizationTypeProperties organizationTypeProperties : newList) {
|
||||
if (organizationTypeProperties.getHasRequired().intValue() == 1 && hasOrganization) {
|
||||
throw new ServiceException("53003814", getMessage("53003814"));
|
||||
}
|
||||
organizationTypeProperties.setId(CloudwalkDateUtils.getUUID());
|
||||
organizationTypeProperties.setBusinessId(businessId);
|
||||
organizationTypeProperties.setOrganizationTypeId(param.getId());
|
||||
organizationTypeProperties.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
organizationTypeProperties.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
organizationTypeProperties.setCreateUserId(context.getUser().getCaller());
|
||||
organizationTypeProperties.setLastUpdateUserId(context.getUser().getCaller());
|
||||
organizationTypeProperties.setCode(getCode(codeSet));
|
||||
organizationTypeProperties.setStatus(Integer.valueOf(0));
|
||||
this.orgTypePropertiesMapper.insertSelective(organizationTypeProperties);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
private String getCode(Set<String> codeSet) {
|
||||
for (int i = 1; i <= 30; i++) {
|
||||
if (codeSet.add("ext" + i)) {
|
||||
return "ext" + i;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
public CloudwalkResult<Boolean> delete(DelOrganizationTypeParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
List<String> ids = param.getIds();
|
||||
if (!CollectionUtils.isEmpty(ids)) {
|
||||
for (String typeId : ids) {
|
||||
GetsOrganizationDTO getsOrganizationDTO = new GetsOrganizationDTO();
|
||||
getsOrganizationDTO.setTypeId(typeId);
|
||||
getsOrganizationDTO.setIsDel(Short.valueOf((short)0));
|
||||
List<Organization> gets = this.imgStoreOrganizationMapper.gets(getsOrganizationDTO);
|
||||
if (!CollectionUtils.isEmpty(gets)) {
|
||||
throw new ServiceException("53003304", getMessage("53003304"));
|
||||
}
|
||||
}
|
||||
for (String id : ids) {
|
||||
OrganizationType organizationType = this.orgTypeMapper.selectByPrimaryKey(id);
|
||||
if (organizationType == null) {
|
||||
throw new ServiceException("53003310", getMessage("53003310"));
|
||||
}
|
||||
organizationType.setId(id);
|
||||
OrganizationType organizationTypeDB = this.orgTypeMapper.selectByPrimaryKey(id);
|
||||
if ("cloudwalk".equals(organizationTypeDB.getBusinessId())) {
|
||||
throw new ServiceException("53003818", getMessage("53003818"));
|
||||
}
|
||||
organizationType.setStatus(Integer.valueOf(1));
|
||||
organizationType.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
organizationType.setLastUpdateUserId(context.getUser().getCaller());
|
||||
this.orgTypeMapper.updateByPrimaryKeySelective(organizationType);
|
||||
OrganizationTypeProperties record = new OrganizationTypeProperties();
|
||||
record.setOrganizationTypeId(id);
|
||||
record.setStatus(Integer.valueOf(1));
|
||||
record.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
record.setLastUpdateUserId(context.getUser().getCaller());
|
||||
this.orgTypePropertiesMapper.updateByTypeKey(record);
|
||||
}
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
public CloudwalkResult<CloudwalkPageAble<OrganizationTypeListResult>> page(QueryOrgTypeParam param, CloudwalkPageInfo page, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId = context.getCompany().getCompanyId();
|
||||
List<OrganizationTypeListResult> results = new ArrayList<>();
|
||||
OrganizationTypeQueryDto record = (OrganizationTypeQueryDto)BeanCopyUtils.copyProperties(param, OrganizationTypeQueryDto.class);
|
||||
record.setBusinessId(businessId);
|
||||
record.setStatus(Integer.valueOf(0));
|
||||
try {
|
||||
PageHelper.startPage(page.getCurrentPage(), page.getPageSize());
|
||||
Page<OrganizationType> gets = (Page<OrganizationType>)this.orgTypeMapper.select(record);
|
||||
List<OrganizationType> result = gets.getResult();
|
||||
Map<String, Integer> deletableMap = OrganizationTypeCodeEnum.deletable();
|
||||
for (OrganizationType organizationType : result) {
|
||||
OrganizationTypeListResult typeResult = (OrganizationTypeListResult)BeanCopyUtils.copyProperties(organizationType, OrganizationTypeListResult.class);
|
||||
typeResult.setDeletable(deletableMap.getOrDefault(organizationType.getCode(), Integer.valueOf(1)));
|
||||
OrganizationTypeProperties recordQuery = new OrganizationTypeProperties();
|
||||
recordQuery.setStatus(Integer.valueOf(0));
|
||||
recordQuery.setOrganizationTypeId(organizationType.getId());
|
||||
List<OrganizationTypeProperties> propertiesList = this.orgTypePropertiesMapper.select(recordQuery);
|
||||
if (!CollectionUtils.isEmpty(propertiesList)) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (OrganizationTypeProperties organizationTypeProperties : propertiesList) {
|
||||
builder.append("," + organizationTypeProperties.getName());
|
||||
}
|
||||
typeResult.setProperties(builder.substring(1));
|
||||
} else {
|
||||
typeResult.setProperties("");
|
||||
}
|
||||
results.add(typeResult);
|
||||
}
|
||||
CloudwalkPageAble<OrganizationTypeListResult> pageAble = new CloudwalkPageAble(results, page, gets.getTotal());
|
||||
return CloudwalkResult.success(pageAble);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("分页查询机构类型信息失败,原因:", e);
|
||||
throw new ServiceException("53003804", getMessage("53003804"));
|
||||
}
|
||||
}
|
||||
public CloudwalkResult<List<OrganizationTypeListResult>> getList(QueryOrgTypeParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId;
|
||||
if (StringUtils.isEmpty(param.getBusinessId())) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
} else {
|
||||
businessId = param.getBusinessId();
|
||||
}
|
||||
Map<String, Integer> deletableMap = OrganizationTypeCodeEnum.deletable(OrganizationTypeCodeEnum.UNIT.getGroup());
|
||||
List<OrganizationTypeListResult> results = new ArrayList<>();
|
||||
OrganizationTypeQueryDto record = (OrganizationTypeQueryDto)BeanCopyUtils.copyProperties(param, OrganizationTypeQueryDto.class);
|
||||
record.setBusinessId(businessId);
|
||||
record.setStatus(Integer.valueOf(0));
|
||||
List<OrganizationType> result = this.orgTypeMapper.select(record);
|
||||
for (OrganizationType organizationType : result) {
|
||||
OrganizationTypeListResult typeResult = (OrganizationTypeListResult)BeanCopyUtils.copyProperties(organizationType, OrganizationTypeListResult.class);
|
||||
typeResult.setDeletable(deletableMap.getOrDefault(organizationType.getCode(), Integer.valueOf(1)));
|
||||
OrganizationTypeProperties recordQuery = new OrganizationTypeProperties();
|
||||
recordQuery.setStatus(Integer.valueOf(0));
|
||||
recordQuery.setOrganizationTypeId(organizationType.getId());
|
||||
List<OrganizationTypeProperties> propertiesList = this.orgTypePropertiesMapper.select(recordQuery);
|
||||
if (!CollectionUtils.isEmpty(propertiesList)) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (OrganizationTypeProperties organizationTypeProperties : propertiesList) {
|
||||
builder.append("," + organizationTypeProperties.getName());
|
||||
}
|
||||
typeResult.setProperties(builder.substring(1));
|
||||
} else {
|
||||
typeResult.setProperties("");
|
||||
}
|
||||
results.add(typeResult);
|
||||
}
|
||||
return CloudwalkResult.success(results);
|
||||
}
|
||||
public CloudwalkResult<OrganizationTypeResult> detail(QueryOrgTypeParam param, CloudwalkCallContext cloudwalkContext) throws ServiceException {
|
||||
if (StringUtils.isEmpty(param.getId())) {
|
||||
throw new ServiceException("53060410", getMessage("53060410"));
|
||||
}
|
||||
OrganizationType organizationType = this.orgTypeMapper.selectByPrimaryKey(param.getId());
|
||||
OrganizationTypeResult result = (OrganizationTypeResult)BeanCopyUtils.copyProperties(organizationType, OrganizationTypeResult.class);
|
||||
OrganizationTypeProperties proQuery = new OrganizationTypeProperties();
|
||||
proQuery.setOrganizationTypeId(param.getId());
|
||||
List<OrganizationTypeProperties> typeProperties = this.orgTypePropertiesMapper.select(proQuery);
|
||||
result.setProperties(BeanCopyUtils.copy(typeProperties, OrganizationTypePropertyParam.class));
|
||||
return CloudwalkResult.success(result);
|
||||
}
|
||||
public CloudwalkResult<List<OrganizationTypePropertyCommonResult>> commonList(CloudwalkCallContext cloudwalkContext) throws ServiceException {
|
||||
List<OrganizationTypePropertyCommonResult> result = new ArrayList<>();
|
||||
OrganizationTypeProperties recordQuery = new OrganizationTypeProperties();
|
||||
recordQuery.setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS);
|
||||
recordQuery.setBusinessId("cloudwalk");
|
||||
List<OrganizationTypeProperties> select = this.orgTypePropertiesMapper.select(recordQuery);
|
||||
if (select != null && select.size() > 0) {
|
||||
result = BeanCopyUtils.copy(select, OrganizationTypePropertyCommonResult.class);
|
||||
}
|
||||
return CloudwalkResult.success(result);
|
||||
}
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
public CloudwalkResult<Boolean> init(EditOrganizationTypeParam param, CloudwalkCallContext cloudwalkContext) {
|
||||
List<OrganizationTypePropertyParam> properties = param.getProperties();
|
||||
OrganizationTypeProperties recordQuery = new OrganizationTypeProperties();
|
||||
recordQuery.setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS);
|
||||
recordQuery.setBusinessId("cloudwalk");
|
||||
List<OrganizationTypeProperties> select = this.orgTypePropertiesMapper.select(recordQuery);
|
||||
if (select != null && select.size() > 0)
|
||||
{
|
||||
for (OrganizationTypeProperties organizationTypeProperties : select) {
|
||||
organizationTypeProperties.setStatus(Integer.valueOf(1));
|
||||
organizationTypeProperties.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
organizationTypeProperties.setLastUpdateUserId(cloudwalkContext.getUser().getCaller());
|
||||
this.orgTypePropertiesMapper.updateByPrimaryKeySelective(organizationTypeProperties);
|
||||
}
|
||||
}
|
||||
if (properties != null && properties.size() > 0) {
|
||||
List<OrganizationTypeProperties> initList = BeanCopyUtils.copy(properties, OrganizationTypeProperties.class);
|
||||
for (OrganizationTypeProperties property : initList) {
|
||||
if (StringUtils.isEmpty(property.getName())) {
|
||||
continue;
|
||||
}
|
||||
property.setId(CloudwalkDateUtils.getUUID());
|
||||
property.setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS);
|
||||
property.setBusinessId("cloudwalk");
|
||||
property.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
property.setLastUpdateUserId(cloudwalkContext.getUser().getCaller());
|
||||
property.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
property.setCreateUserId(cloudwalkContext.getUser().getCaller());
|
||||
this.orgTypePropertiesMapper.insertSelective(property);
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
String[] initNameArray = { "地址", "邮编", "电话", "传真", "面积", "财务是否独立核算" };
|
||||
int index = 1;
|
||||
for (String name : initNameArray) {
|
||||
OrganizationTypeProperties property = new OrganizationTypeProperties();
|
||||
property.setId(CloudwalkDateUtils.getUUID());
|
||||
property.setName(name);
|
||||
property.setOrderNum(Integer.valueOf(index++));
|
||||
property.setStatus(ImageStoreConstants.COMMON_PROPERTIES_STATUS);
|
||||
property.setBusinessId("cloudwalk");
|
||||
property.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
property.setLastUpdateUserId(cloudwalkContext.getUser().getCaller());
|
||||
property.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
property.setCreateUserId(cloudwalkContext.getUser().getCaller());
|
||||
this.orgTypePropertiesMapper.insertSelective(property);
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
public CloudwalkResult<Boolean> defaultInit(CloudwalkCallContext cloudwalkContext) throws ServiceException {
|
||||
this.logger.info("初始化机构类型");
|
||||
OrganizationType organizationType = new OrganizationType();
|
||||
String uuid = CloudwalkDateUtils.getUUID();
|
||||
organizationType.setId(uuid);
|
||||
organizationType.setName("公司");
|
||||
organizationType.setBusinessId("cloudwalk");
|
||||
organizationType.setStatus(Integer.valueOf(0));
|
||||
organizationType.setHasDefault(Integer.valueOf(1));
|
||||
organizationType.setHasLowerLevel(Integer.valueOf(1));
|
||||
organizationType.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
organizationType.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.orgTypeMapper.insertSelective(organizationType);
|
||||
String[] initNameArray = { "地址", "邮编", "电话", "负责人", "说明" };
|
||||
int index = 1;
|
||||
for (String name : initNameArray) {
|
||||
OrganizationTypeProperties property = new OrganizationTypeProperties();
|
||||
property.setId(CloudwalkDateUtils.getUUID());
|
||||
property.setOrganizationTypeId(uuid);
|
||||
property.setName(name);
|
||||
property.setOrderNum(Integer.valueOf(index++));
|
||||
property.setStatus(Integer.valueOf(0));
|
||||
property.setBusinessId("cloudwalk");
|
||||
property.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
property.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.orgTypePropertiesMapper.insertSelective(property);
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/OrganizationTypeServiceImpl.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+145
-140
@@ -19,166 +19,171 @@ import cn.cloudwalk.data.organization.dto.GetsOrganizationDTO;
|
||||
import cn.cloudwalk.data.organization.dto.OrgCountDTO;
|
||||
import cn.cloudwalk.data.organization.dto.OrganizationExtendDTO;
|
||||
import cn.cloudwalk.data.organization.dto.OrganizationTypeQueryDto;
|
||||
import cn.cloudwalk.data.organization.entity.Organization;
|
||||
import cn.cloudwalk.data.organization.entity.OrganizationDetail;
|
||||
import cn.cloudwalk.data.organization.entity.OrganizationType;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStoreOrganizationMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStoreOrganizationTypeMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonOrganizationMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.OrganizationExtendMapper;
|
||||
import cn.cloudwalk.service.organization.service.OrganizationServiceImpl;
|
||||
import cn.cloudwalk.service.organization.service.feign.VehicleFeignClient;
|
||||
import cn.cloudwalk.service.organization.service.feign.ZoneFeignClient;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Resource;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
@Service(value="organizationUnitServiceImpl")
|
||||
@Service("organizationUnitServiceImpl")
|
||||
public class OrganizationUnitServiceImpl
|
||||
extends OrganizationServiceImpl
|
||||
implements OrganizationService {
|
||||
@Resource
|
||||
private ImgStoreOrganizationTypeMapper organizationTypeMapper;
|
||||
@Resource
|
||||
private ImgStoreOrganizationMapper organizationMapper;
|
||||
@Resource
|
||||
private OrganizationExtendMapper organizationExtendMapper;
|
||||
@Resource
|
||||
private ImgStorePersonOrganizationMapper personOrganizationMapper;
|
||||
@Resource
|
||||
private ZoneFeignClient zoneFeignClient;
|
||||
@Resource
|
||||
private VehicleFeignClient vehicleFeignClient;
|
||||
|
||||
@Override
|
||||
public CloudwalkResult<List<OrganizationResult>> getList(QueryOrganizationParam param, CloudwalkCallContext context) {
|
||||
String businessId = StringUtils.isNotBlank((CharSequence)param.getBusinessId()) ? param.getBusinessId() : context.getCompany().getCompanyId();
|
||||
List codes = OrganizationTypeCodeEnum.groupBy((String)OrganizationTypeCodeEnum.UNIT.getGroup());
|
||||
codes.add("ROOT");
|
||||
OrganizationTypeQueryDto queryDto = new OrganizationTypeQueryDto();
|
||||
queryDto.setBusinessId(businessId);
|
||||
queryDto.setCodes(codes);
|
||||
List organizationTypeList = this.organizationTypeMapper.select(queryDto);
|
||||
List typeIdsQuery = organizationTypeList.stream().map(OrganizationType::getId).collect(Collectors.toList());
|
||||
GetsOrganizationDTO getsOrganizationDTO = (GetsOrganizationDTO)BeanCopyUtils.copyProperties((Object)param, GetsOrganizationDTO.class);
|
||||
getsOrganizationDTO.setBusinessId(businessId);
|
||||
getsOrganizationDTO.setIds(param.getIds());
|
||||
getsOrganizationDTO.setTypeIds(typeIdsQuery);
|
||||
if (StringUtils.isNotEmpty((CharSequence)param.getName()) && !param.getName().endsWith("%")) {
|
||||
getsOrganizationDTO.setName(param.getName().concat("%"));
|
||||
}
|
||||
List resultData = this.organizationMapper.listDetail(getsOrganizationDTO);
|
||||
ArrayList<String> ids = new ArrayList<String>();
|
||||
HashSet<String> typeIds = new HashSet<String>();
|
||||
for (Object organization : resultData) {
|
||||
ids.add(organization.getId());
|
||||
typeIds.add(organization.getTypeId());
|
||||
}
|
||||
ArrayList<OrganizationResult> resultList = new ArrayList<OrganizationResult>(resultData.size());
|
||||
for (OrganizationDetail resultDatum : resultData) {
|
||||
OrganizationExtendDTO extend = resultDatum.getExtend();
|
||||
OrganizationExtendResult extendResult = (OrganizationExtendResult)BeanCopyUtils.copyProperties((Object)extend, OrganizationExtendResult.class);
|
||||
OrganizationResult result = (OrganizationResult)BeanCopyUtils.copyProperties((Object)resultDatum, OrganizationResult.class);
|
||||
result.setExtend(extendResult);
|
||||
resultList.add(result);
|
||||
}
|
||||
QueryZoneUnitParam queryZoneUnitParam = new QueryZoneUnitParam();
|
||||
queryZoneUnitParam.setUnitIds(ids);
|
||||
CloudwalkResult<List<ZoneUnitResultDTO>> zoneDetail = this.zoneFeignClient.findZoneDetailByUnitIds(queryZoneUnitParam);
|
||||
HashMap<String, String> unitZoneMap = new HashMap<String, String>();
|
||||
if ("00000000".equals(zoneDetail.getCode())) {
|
||||
List data = (List)zoneDetail.getData();
|
||||
for (ZoneUnitResultDTO datum : data) {
|
||||
String unitId = datum.getUnitId();
|
||||
String zoneId = datum.getZoneId();
|
||||
String zoneName = datum.getZoneName();
|
||||
if (StringUtils.isEmpty((CharSequence)((CharSequence)unitZoneMap.get(unitId)))) {
|
||||
unitZoneMap.put(unitId, zoneName);
|
||||
continue;
|
||||
}
|
||||
unitZoneMap.put(unitId, (String)unitZoneMap.get(unitId) + "," + zoneName);
|
||||
}
|
||||
}
|
||||
AddVehiclePersonForm addVehiclePersonForm = new AddVehiclePersonForm();
|
||||
CloudwalkResult<List<VehicleCountCompany>> companyCountDate = this.vehicleFeignClient.getVehicleIdsCountByCompany(addVehiclePersonForm);
|
||||
HashMap<String, Integer> companyCountMap = new HashMap<String, Integer>();
|
||||
if ("00000000".equals(companyCountDate.getCode())) {
|
||||
List data = (List)companyCountDate.getData();
|
||||
for (VehicleCountCompany datum : data) {
|
||||
String companyId = datum.getCompanyId();
|
||||
Integer count = datum.getCount();
|
||||
companyCountMap.put(companyId, count);
|
||||
}
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(ids)) {
|
||||
HashMap<String, Integer> map = new HashMap<String, Integer>();
|
||||
HashMap<String, OrganizationType> typeMap = new HashMap<String, OrganizationType>();
|
||||
List orgCountDTOS = this.organizationMapper.getPersonCount(ids);
|
||||
OrganizationTypeQueryDto typeQueryDto = new OrganizationTypeQueryDto();
|
||||
typeQueryDto.setIds(new ArrayList(typeIds));
|
||||
if (!CollectionUtils.isEmpty((Collection)orgCountDTOS)) {
|
||||
for (OrgCountDTO dto : orgCountDTOS) {
|
||||
map.put(dto.getId(), dto.getCount());
|
||||
}
|
||||
}
|
||||
for (OrganizationType organizationType : organizationTypeList) {
|
||||
typeMap.put(organizationType.getId(), organizationType);
|
||||
}
|
||||
for (OrganizationResult result : resultList) {
|
||||
Integer count = (Integer)map.get(result.getId());
|
||||
String zoneName = (String)unitZoneMap.get(result.getId());
|
||||
result.setZoneName(zoneName);
|
||||
result.setCarNum((Integer)companyCountMap.get(result.getId()));
|
||||
if (count != null) {
|
||||
result.setPersonCount(count);
|
||||
} else {
|
||||
result.setPersonCount(Integer.valueOf(0));
|
||||
}
|
||||
OrganizationType organizationType = (OrganizationType)typeMap.get(result.getTypeId());
|
||||
if (organizationType != null) {
|
||||
String typeName = organizationType.getName();
|
||||
result.setType(typeName == null ? "" : typeName);
|
||||
result.setHasLowerLevel(organizationType.getHasLowerLevel());
|
||||
continue;
|
||||
}
|
||||
result.setType("");
|
||||
result.setHasLowerLevel(null);
|
||||
}
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> delete(DelOrganizationParam param, CloudwalkCallContext context) {
|
||||
String businessId = context.getCompany().getCompanyId();
|
||||
List ids = param.getIds();
|
||||
List orgByIds = this.organizationMapper.getOrgByIds(ids, businessId);
|
||||
if (orgByIds.size() != param.getIds().size()) {
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
List personCount = this.organizationMapper.getPersonCount(ids);
|
||||
for (OrgCountDTO orgCountDTO : personCount) {
|
||||
if (orgCountDTO.getCount() <= 0) continue;
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
this.organizationMapper.batchDel(param.getIds(), System.currentTimeMillis(), context.getUser().getCaller(), businessId);
|
||||
this.personOrganizationMapper.deleteByOrgIds(param.getIds());
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CloudwalkResult<String> add(AddOrganizationParam param, CloudwalkCallContext context) {
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
implements OrganizationService
|
||||
{
|
||||
@Resource
|
||||
private ImgStoreOrganizationTypeMapper organizationTypeMapper;
|
||||
@Resource
|
||||
private ImgStoreOrganizationMapper organizationMapper;
|
||||
@Resource
|
||||
private OrganizationExtendMapper organizationExtendMapper;
|
||||
@Resource
|
||||
private ImgStorePersonOrganizationMapper personOrganizationMapper;
|
||||
@Resource
|
||||
private ZoneFeignClient zoneFeignClient;
|
||||
@Resource
|
||||
private VehicleFeignClient vehicleFeignClient;
|
||||
public CloudwalkResult<List<OrganizationResult>> getList(QueryOrganizationParam param, CloudwalkCallContext context) {
|
||||
String businessId;
|
||||
if (StringUtils.isNotBlank(param.getBusinessId())) {
|
||||
businessId = param.getBusinessId();
|
||||
} else {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
List<String> codes = OrganizationTypeCodeEnum.groupBy(OrganizationTypeCodeEnum.UNIT.getGroup());
|
||||
codes.add("ROOT");
|
||||
OrganizationTypeQueryDto queryDto = new OrganizationTypeQueryDto();
|
||||
queryDto.setBusinessId(businessId);
|
||||
queryDto.setCodes(codes);
|
||||
List<OrganizationType> organizationTypeList = this.organizationTypeMapper.select(queryDto);
|
||||
List<String> typeIdsQuery = (List<String>)organizationTypeList.stream().map(OrganizationType::getId).collect(Collectors.toList());
|
||||
GetsOrganizationDTO getsOrganizationDTO = (GetsOrganizationDTO)BeanCopyUtils.copyProperties(param, GetsOrganizationDTO.class);
|
||||
getsOrganizationDTO.setBusinessId(businessId);
|
||||
getsOrganizationDTO.setIds(param.getIds());
|
||||
getsOrganizationDTO.setTypeIds(typeIdsQuery);
|
||||
if (StringUtils.isNotEmpty(param.getName()) && !param.getName().endsWith("%")) {
|
||||
getsOrganizationDTO.setName(param.getName().concat("%"));
|
||||
}
|
||||
List<OrganizationDetail> resultData = this.organizationMapper.listDetail(getsOrganizationDTO);
|
||||
List<String> ids = new ArrayList<>();
|
||||
Set<String> typeIds = new HashSet<>();
|
||||
for (OrganizationDetail organization : resultData) {
|
||||
ids.add(organization.getId());
|
||||
typeIds.add(organization.getTypeId());
|
||||
}
|
||||
List<OrganizationResult> resultList = new ArrayList<>(resultData.size());
|
||||
for (OrganizationDetail resultDatum : resultData) {
|
||||
OrganizationExtendDTO extend = resultDatum.getExtend();
|
||||
OrganizationExtendResult extendResult = (OrganizationExtendResult)BeanCopyUtils.copyProperties(extend, OrganizationExtendResult.class);
|
||||
OrganizationResult result = (OrganizationResult)BeanCopyUtils.copyProperties(resultDatum, OrganizationResult.class);
|
||||
result.setExtend(extendResult);
|
||||
resultList.add(result);
|
||||
}
|
||||
QueryZoneUnitParam queryZoneUnitParam = new QueryZoneUnitParam();
|
||||
queryZoneUnitParam.setUnitIds(ids);
|
||||
CloudwalkResult<List<ZoneUnitResultDTO>> zoneDetail = this.zoneFeignClient.findZoneDetailByUnitIds(queryZoneUnitParam);
|
||||
Map<String, String> unitZoneMap = new HashMap<>();
|
||||
if (Objects.equals(zoneDetail.getCode(), "00000000")) {
|
||||
List<ZoneUnitResultDTO> data = (List<ZoneUnitResultDTO>)zoneDetail.getData();
|
||||
for (ZoneUnitResultDTO datum : data) {
|
||||
String unitId = datum.getUnitId();
|
||||
String zoneId = datum.getZoneId();
|
||||
String zoneName = datum.getZoneName();
|
||||
if (StringUtils.isEmpty(unitZoneMap.get(unitId))) {
|
||||
unitZoneMap.put(unitId, zoneName); continue;
|
||||
}
|
||||
unitZoneMap.put(unitId, (String)unitZoneMap.get(unitId) + "," + zoneName);
|
||||
}
|
||||
}
|
||||
AddVehiclePersonForm addVehiclePersonForm = new AddVehiclePersonForm();
|
||||
CloudwalkResult<List<VehicleCountCompany>> companyCountDate = this.vehicleFeignClient.getVehicleIdsCountByCompany(addVehiclePersonForm);
|
||||
Map<String, Integer> companyCountMap = new HashMap<>();
|
||||
if (Objects.equals(companyCountDate.getCode(), "00000000")) {
|
||||
List<VehicleCountCompany> data = (List<VehicleCountCompany>)companyCountDate.getData();
|
||||
for (VehicleCountCompany datum : data) {
|
||||
String companyId = datum.getCompanyId();
|
||||
Integer count = datum.getCount();
|
||||
companyCountMap.put(companyId, count);
|
||||
}
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(ids)) {
|
||||
Map<String, Integer> map = new HashMap<>();
|
||||
Map<String, OrganizationType> typeMap = new HashMap<>();
|
||||
List<OrgCountDTO> orgCountDTOS = this.organizationMapper.getPersonCount(ids);
|
||||
OrganizationTypeQueryDto typeQueryDto = new OrganizationTypeQueryDto();
|
||||
typeQueryDto.setIds(new ArrayList<>(typeIds));
|
||||
if (!CollectionUtils.isEmpty(orgCountDTOS)) {
|
||||
for (OrgCountDTO dto : orgCountDTOS) {
|
||||
map.put(dto.getId(), dto.getCount());
|
||||
}
|
||||
}
|
||||
for (OrganizationType organizationType : organizationTypeList) {
|
||||
typeMap.put(organizationType.getId(), organizationType);
|
||||
}
|
||||
for (OrganizationResult result : resultList) {
|
||||
Integer count = map.get(result.getId());
|
||||
String zoneName = unitZoneMap.get(result.getId());
|
||||
result.setZoneName(zoneName);
|
||||
result.setCarNum(companyCountMap.get(result.getId()));
|
||||
if (count != null) {
|
||||
result.setPersonCount(count);
|
||||
} else {
|
||||
result.setPersonCount(Integer.valueOf(0));
|
||||
}
|
||||
OrganizationType organizationType = typeMap.get(result.getTypeId());
|
||||
if (organizationType != null) {
|
||||
String typeName = organizationType.getName();
|
||||
result.setType((typeName == null) ? "" : typeName);
|
||||
result.setHasLowerLevel(organizationType.getHasLowerLevel()); continue;
|
||||
}
|
||||
result.setType("");
|
||||
result.setHasLowerLevel(null);
|
||||
}
|
||||
}
|
||||
return CloudwalkResult.success(resultList);
|
||||
}
|
||||
@Transactional
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> delete(DelOrganizationParam param, CloudwalkCallContext context) {
|
||||
String businessId = context.getCompany().getCompanyId();
|
||||
List<String> ids = param.getIds();
|
||||
List<Organization> orgByIds = this.organizationMapper.getOrgByIds(ids, businessId);
|
||||
if (orgByIds.size() != param.getIds().size())
|
||||
{
|
||||
return CloudwalkResult.fail("53060411", getMessage("53060411"));
|
||||
}
|
||||
List<OrgCountDTO> personCount = this.organizationMapper.getPersonCount(ids);
|
||||
for (OrgCountDTO orgCountDTO : personCount) {
|
||||
if (orgCountDTO.getCount().intValue() > 0) {
|
||||
return CloudwalkResult.fail("53003315", "单位人员数量大于0,请将人员从单位中移除后再删除");
|
||||
}
|
||||
}
|
||||
this.organizationMapper.batchDel(param.getIds(), System.currentTimeMillis(), context.getUser().getCaller(), businessId);
|
||||
this.personOrganizationMapper.deleteByOrgIds(param.getIds());
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
public CloudwalkResult<String> add(AddOrganizationParam param, CloudwalkCallContext context) {
|
||||
return CloudwalkResult.success("暂不支持新增单位");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/OrganizationUnitServiceImpl.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+199
-194
@@ -23,7 +23,6 @@ import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import com.github.pagehelper.Page;
|
||||
import com.github.pagehelper.PageHelper;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import javax.annotation.Resource;
|
||||
@@ -31,200 +30,206 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
@Service
|
||||
public class OrganizationUnitTypeServiceImpl
|
||||
extends AbstractImagStoreService {
|
||||
@Resource
|
||||
private ImgStoreOrganizationMapper organizationMapper;
|
||||
@Resource
|
||||
private ImgStoreOrganizationTypeMapper orgTypeMapper;
|
||||
@Resource
|
||||
private ImgStoreOrganizationTypePropertiesMapper orgTypePropertiesMapper;
|
||||
protected static final short IS_NOT_DEL = 0;
|
||||
|
||||
public CloudwalkResult<CloudwalkPageAble<OrganizationTypeListResult>> page(QueryOrgTypeParam param, CloudwalkPageInfo page, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId = context.getCompany().getCompanyId();
|
||||
ArrayList<OrganizationTypeListResult> results = new ArrayList<OrganizationTypeListResult>();
|
||||
OrganizationTypeQueryDto record = (OrganizationTypeQueryDto)BeanCopyUtils.copyProperties((Object)param, OrganizationTypeQueryDto.class);
|
||||
record.setBusinessId(businessId);
|
||||
record.setStatus(Integer.valueOf(0));
|
||||
try {
|
||||
PageHelper.startPage((int)page.getCurrentPage(), (int)page.getPageSize());
|
||||
Page gets = (Page)this.orgTypeMapper.select(record);
|
||||
List result = gets.getResult();
|
||||
Map deletableMap = OrganizationTypeCodeEnum.deletable((String)OrganizationTypeCodeEnum.UNIT.getGroup());
|
||||
for (OrganizationType organizationType : (List<cn.cloudwalk.data.organization.entity.OrganizationType>) result) {
|
||||
OrganizationTypeListResult typeResult = (OrganizationTypeListResult)BeanCopyUtils.copyProperties((Object)organizationType, OrganizationTypeListResult.class);
|
||||
typeResult.setDeletable(deletableMap.getOrDefault(organizationType.getCode(), 1));
|
||||
OrganizationTypeProperties recordQuery = new OrganizationTypeProperties();
|
||||
recordQuery.setStatus(Integer.valueOf(0));
|
||||
recordQuery.setOrganizationTypeId(organizationType.getId());
|
||||
List propertiesList = this.orgTypePropertiesMapper.select(recordQuery);
|
||||
if (!CollectionUtils.isEmpty((Collection)propertiesList)) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (OrganizationTypeProperties organizationTypeProperties : (List<cn.cloudwalk.data.organization.entity.OrganizationTypeProperties>) propertiesList) {
|
||||
builder.append("," + organizationTypeProperties.getName());
|
||||
}
|
||||
typeResult.setProperties(builder.substring(1));
|
||||
} else {
|
||||
typeResult.setProperties("");
|
||||
}
|
||||
results.add(typeResult);
|
||||
}
|
||||
CloudwalkPageAble pageAble = new CloudwalkPageAble(results, page, gets.getTotal());
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("分页查询机构类型信息失败,原因:", e);
|
||||
throw new ServiceException("53003804", this.getMessage("53003804"));
|
||||
}
|
||||
}
|
||||
|
||||
public CloudwalkResult<List<OrganizationTypeListResult>> getList(QueryOrgTypeParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId = StringUtils.isEmpty((Object)param.getBusinessId()) ? context.getCompany().getCompanyId() : param.getBusinessId();
|
||||
List codeList = OrganizationTypeCodeEnum.groupBy((String)OrganizationTypeCodeEnum.UNIT.getGroup());
|
||||
ArrayList<OrganizationTypeListResult> results = new ArrayList<OrganizationTypeListResult>();
|
||||
OrganizationTypeQueryDto record = (OrganizationTypeQueryDto)BeanCopyUtils.copyProperties((Object)param, OrganizationTypeQueryDto.class);
|
||||
record.setBusinessId(businessId);
|
||||
record.setStatus(Integer.valueOf(0));
|
||||
List result = this.orgTypeMapper.select(record);
|
||||
for (OrganizationType organizationType : (List<cn.cloudwalk.data.organization.entity.OrganizationType>) result) {
|
||||
if (!codeList.contains(organizationType.getCode())) continue;
|
||||
OrganizationTypeListResult typeResult = (OrganizationTypeListResult)BeanCopyUtils.copyProperties((Object)organizationType, OrganizationTypeListResult.class);
|
||||
OrganizationTypeProperties recordQuery = new OrganizationTypeProperties();
|
||||
recordQuery.setStatus(Integer.valueOf(0));
|
||||
recordQuery.setOrganizationTypeId(organizationType.getId());
|
||||
List propertiesList = this.orgTypePropertiesMapper.select(recordQuery);
|
||||
if (!CollectionUtils.isEmpty((Collection)propertiesList)) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (OrganizationTypeProperties organizationTypeProperties : (List<cn.cloudwalk.data.organization.entity.OrganizationTypeProperties>) propertiesList) {
|
||||
builder.append(",").append(organizationTypeProperties.getName());
|
||||
}
|
||||
typeResult.setProperties(builder.substring(1));
|
||||
} else {
|
||||
typeResult.setProperties("");
|
||||
}
|
||||
results.add(typeResult);
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
public CloudwalkResult<Boolean> defaultInitOrgType(String businessId, boolean isSuperCorp) {
|
||||
OrganizationTypeQueryDto queryDto = new OrganizationTypeQueryDto();
|
||||
queryDto.setBusinessId(businessId);
|
||||
queryDto.setCode(OrganizationTypeCodeEnum.UNIT.getCode());
|
||||
queryDto.setStatus(Integer.valueOf(0));
|
||||
List count = this.orgTypeMapper.selectByCondition(queryDto);
|
||||
if (count.size() > 0) {
|
||||
this.logger.info("类型已初始化,请勿重复调用");
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
if (isSuperCorp) {
|
||||
OrganizationType unitType = new OrganizationType();
|
||||
unitType.setName(OrganizationTypeCodeEnum.UNIT.getName());
|
||||
unitType.setCode(OrganizationTypeCodeEnum.UNIT.getCode());
|
||||
unitType.setBusinessId(businessId);
|
||||
unitType.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
unitType.setHasDefault(Integer.valueOf(0));
|
||||
unitType.setStatus(Integer.valueOf(0));
|
||||
unitType.setHasLowerLevel(Integer.valueOf(0));
|
||||
String typeId = CloudwalkDateUtils.getUUID();
|
||||
unitType.setId(typeId);
|
||||
int selective = this.orgTypeMapper.insertSelective(unitType);
|
||||
OrganizationTypeProperties propQuery = new OrganizationTypeProperties();
|
||||
propQuery.setStatus(ImageStoreConstants.COMMON_UNIT_PROPERTIES_STATUS);
|
||||
List propertiesList = this.orgTypePropertiesMapper.select(propQuery);
|
||||
for (OrganizationTypeProperties properties : (List<cn.cloudwalk.data.organization.entity.OrganizationTypeProperties>) propertiesList) {
|
||||
properties.setOrganizationTypeId(typeId);
|
||||
properties.setId(CloudwalkDateUtils.getUUID());
|
||||
properties.setBusinessId(businessId);
|
||||
this.orgTypePropertiesMapper.insertSelective(properties);
|
||||
}
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor={Exception.class})
|
||||
public String initRootOrg(String businessId, String businessName) throws ServiceException {
|
||||
OrganizationTypeQueryDto record = new OrganizationTypeQueryDto();
|
||||
record.setBusinessId("cloudwalk");
|
||||
record.setCode("ROOT");
|
||||
record.setStatus(Integer.valueOf(0));
|
||||
record.setHasDefault(Integer.valueOf(1));
|
||||
List organizationTypes = this.orgTypeMapper.select(record);
|
||||
OrganizationType organizationType = (OrganizationType)organizationTypes.get(0);
|
||||
GetsOrganizationDTO existQuery = new GetsOrganizationDTO();
|
||||
existQuery.setBusinessId(businessId);
|
||||
existQuery.setIsDel(Short.valueOf((short)0));
|
||||
existQuery.setTypeId(organizationType.getId());
|
||||
List organizationList = this.organizationMapper.gets(existQuery);
|
||||
if (!organizationList.isEmpty()) {
|
||||
return ((Organization)organizationList.get(0)).getId();
|
||||
}
|
||||
Organization organization = new Organization();
|
||||
organization.setBusinessId(businessId);
|
||||
organization.setTypeId(organizationType.getId());
|
||||
organization.setIsDel(Short.valueOf((short)0));
|
||||
organization.setName(businessName);
|
||||
String rootOrgId = CloudwalkDateUtils.getUUID();
|
||||
organization.setId(rootOrgId);
|
||||
organization.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
organization.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
organization.setIsValid(Integer.valueOf(1));
|
||||
this.organizationMapper.insertSelective(organization);
|
||||
return rootOrgId;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor={Exception.class})
|
||||
public CloudwalkResult<Boolean> initParkOrg(String businessId, String businessName, String rootOrgId) throws ServiceException {
|
||||
OrganizationTypeQueryDto record = new OrganizationTypeQueryDto();
|
||||
record.setBusinessId(businessId);
|
||||
record.setCode("PARK");
|
||||
record.setStatus(Integer.valueOf(0));
|
||||
record.setHasDefault(Integer.valueOf(1));
|
||||
List exists = this.orgTypeMapper.select(record);
|
||||
if (!exists.isEmpty()) {
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
record = new OrganizationTypeQueryDto();
|
||||
record.setBusinessId("cloudwalk");
|
||||
record.setCode("PARK");
|
||||
record.setStatus(Integer.valueOf(0));
|
||||
record.setHasDefault(Integer.valueOf(1));
|
||||
List organizationTypes = this.orgTypeMapper.select(record);
|
||||
if (!CollectionUtils.isEmpty((Collection)organizationTypes)) {
|
||||
for (OrganizationType organizationType : (List<cn.cloudwalk.data.organization.entity.OrganizationType>) organizationTypes) {
|
||||
String oldTypeId = organizationType.getId();
|
||||
String typeId = CloudwalkDateUtils.getUUID();
|
||||
organizationType.setId(typeId);
|
||||
organizationType.setBusinessId(businessId);
|
||||
this.orgTypeMapper.insertSelective(organizationType);
|
||||
OrganizationTypeProperties typePropertiesQuery = new OrganizationTypeProperties();
|
||||
typePropertiesQuery.setBusinessId("cloudwalk");
|
||||
typePropertiesQuery.setOrganizationTypeId(oldTypeId);
|
||||
typePropertiesQuery.setStatus(ImageStoreConstants.COMMON_PARK_PROPERTIES_STATUS);
|
||||
List properties = this.orgTypePropertiesMapper.select(typePropertiesQuery);
|
||||
for (OrganizationTypeProperties property : (List<cn.cloudwalk.data.organization.entity.OrganizationTypeProperties>) properties) {
|
||||
property.setId(CloudwalkDateUtils.getUUID());
|
||||
property.setBusinessId(businessId);
|
||||
property.setOrganizationTypeId(typeId);
|
||||
this.orgTypePropertiesMapper.insertSelective(property);
|
||||
}
|
||||
Organization organization = new Organization();
|
||||
organization.setBusinessId(businessId);
|
||||
organization.setTypeId(typeId);
|
||||
organization.setIsDel(Short.valueOf((short)0));
|
||||
organization.setName(businessName + organizationType.getName());
|
||||
organization.setId(CloudwalkDateUtils.getUUID());
|
||||
organization.setParentId(rootOrgId);
|
||||
organization.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
organization.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
organization.setIsValid(Integer.valueOf(1));
|
||||
this.organizationMapper.insertSelective(organization);
|
||||
}
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
extends AbstractImagStoreService
|
||||
{
|
||||
@Resource
|
||||
private ImgStoreOrganizationMapper organizationMapper;
|
||||
@Resource
|
||||
private ImgStoreOrganizationTypeMapper orgTypeMapper;
|
||||
@Resource
|
||||
private ImgStoreOrganizationTypePropertiesMapper orgTypePropertiesMapper;
|
||||
protected static final short IS_NOT_DEL = 0;
|
||||
public CloudwalkResult<CloudwalkPageAble<OrganizationTypeListResult>> page(QueryOrgTypeParam param, CloudwalkPageInfo page, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId = context.getCompany().getCompanyId();
|
||||
List<OrganizationTypeListResult> results = new ArrayList<>();
|
||||
OrganizationTypeQueryDto record = (OrganizationTypeQueryDto)BeanCopyUtils.copyProperties(param, OrganizationTypeQueryDto.class);
|
||||
record.setBusinessId(businessId);
|
||||
record.setStatus(Integer.valueOf(0));
|
||||
try {
|
||||
PageHelper.startPage(page.getCurrentPage(), page.getPageSize());
|
||||
Page<OrganizationType> gets = (Page<OrganizationType>)this.orgTypeMapper.select(record);
|
||||
List<OrganizationType> result = gets.getResult();
|
||||
Map<String, Integer> deletableMap = OrganizationTypeCodeEnum.deletable(OrganizationTypeCodeEnum.UNIT.getGroup());
|
||||
for (OrganizationType organizationType : result) {
|
||||
OrganizationTypeListResult typeResult = (OrganizationTypeListResult)BeanCopyUtils.copyProperties(organizationType, OrganizationTypeListResult.class);
|
||||
typeResult.setDeletable(deletableMap.getOrDefault(organizationType.getCode(), Integer.valueOf(1)));
|
||||
OrganizationTypeProperties recordQuery = new OrganizationTypeProperties();
|
||||
recordQuery.setStatus(Integer.valueOf(0));
|
||||
recordQuery.setOrganizationTypeId(organizationType.getId());
|
||||
List<OrganizationTypeProperties> propertiesList = this.orgTypePropertiesMapper.select(recordQuery);
|
||||
if (!CollectionUtils.isEmpty(propertiesList)) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (OrganizationTypeProperties organizationTypeProperties : propertiesList) {
|
||||
builder.append("," + organizationTypeProperties.getName());
|
||||
}
|
||||
typeResult.setProperties(builder.substring(1));
|
||||
} else {
|
||||
typeResult.setProperties("");
|
||||
}
|
||||
results.add(typeResult);
|
||||
}
|
||||
CloudwalkPageAble<OrganizationTypeListResult> pageAble = new CloudwalkPageAble(results, page, gets.getTotal());
|
||||
return CloudwalkResult.success(pageAble);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("分页查询机构类型信息失败,原因:", e);
|
||||
throw new ServiceException("53003804", getMessage("53003804"));
|
||||
}
|
||||
}
|
||||
public CloudwalkResult<List<OrganizationTypeListResult>> getList(QueryOrgTypeParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId;
|
||||
if (StringUtils.isEmpty(param.getBusinessId())) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
} else {
|
||||
businessId = param.getBusinessId();
|
||||
}
|
||||
List<String> codeList = OrganizationTypeCodeEnum.groupBy(OrganizationTypeCodeEnum.UNIT.getGroup());
|
||||
List<OrganizationTypeListResult> results = new ArrayList<>();
|
||||
OrganizationTypeQueryDto record = (OrganizationTypeQueryDto)BeanCopyUtils.copyProperties(param, OrganizationTypeQueryDto.class);
|
||||
record.setBusinessId(businessId);
|
||||
record.setStatus(Integer.valueOf(0));
|
||||
List<OrganizationType> result = this.orgTypeMapper.select(record);
|
||||
for (OrganizationType organizationType : result) {
|
||||
if (!codeList.contains(organizationType.getCode())) {
|
||||
continue;
|
||||
}
|
||||
OrganizationTypeListResult typeResult = (OrganizationTypeListResult)BeanCopyUtils.copyProperties(organizationType, OrganizationTypeListResult.class);
|
||||
OrganizationTypeProperties recordQuery = new OrganizationTypeProperties();
|
||||
recordQuery.setStatus(Integer.valueOf(0));
|
||||
recordQuery.setOrganizationTypeId(organizationType.getId());
|
||||
List<OrganizationTypeProperties> propertiesList = this.orgTypePropertiesMapper.select(recordQuery);
|
||||
if (!CollectionUtils.isEmpty(propertiesList)) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (OrganizationTypeProperties organizationTypeProperties : propertiesList) {
|
||||
builder.append(",").append(organizationTypeProperties.getName());
|
||||
}
|
||||
typeResult.setProperties(builder.substring(1));
|
||||
} else {
|
||||
typeResult.setProperties("");
|
||||
}
|
||||
results.add(typeResult);
|
||||
}
|
||||
return CloudwalkResult.success(results);
|
||||
}
|
||||
public CloudwalkResult<Boolean> defaultInitOrgType(String businessId, boolean isSuperCorp) {
|
||||
OrganizationTypeQueryDto queryDto = new OrganizationTypeQueryDto();
|
||||
queryDto.setBusinessId(businessId);
|
||||
queryDto.setCode(OrganizationTypeCodeEnum.UNIT.getCode());
|
||||
queryDto.setStatus(Integer.valueOf(0));
|
||||
List<OrganizationType> count = this.orgTypeMapper.selectByCondition(queryDto);
|
||||
if (count.size() > 0) {
|
||||
this.logger.info("类型已初始化,请勿重复调用");
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
if (isSuperCorp) {
|
||||
OrganizationType unitType = new OrganizationType();
|
||||
unitType.setName(OrganizationTypeCodeEnum.UNIT.getName());
|
||||
unitType.setCode(OrganizationTypeCodeEnum.UNIT.getCode());
|
||||
unitType.setBusinessId(businessId);
|
||||
unitType.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
unitType.setHasDefault(Integer.valueOf(0));
|
||||
unitType.setStatus(Integer.valueOf(0));
|
||||
unitType.setHasLowerLevel(Integer.valueOf(0));
|
||||
String typeId = CloudwalkDateUtils.getUUID();
|
||||
unitType.setId(typeId);
|
||||
int selective = this.orgTypeMapper.insertSelective(unitType);
|
||||
OrganizationTypeProperties propQuery = new OrganizationTypeProperties();
|
||||
propQuery.setStatus(ImageStoreConstants.COMMON_UNIT_PROPERTIES_STATUS);
|
||||
List<OrganizationTypeProperties> propertiesList = this.orgTypePropertiesMapper.select(propQuery);
|
||||
for (OrganizationTypeProperties properties : propertiesList) {
|
||||
properties.setOrganizationTypeId(typeId);
|
||||
properties.setId(CloudwalkDateUtils.getUUID());
|
||||
properties.setBusinessId(businessId);
|
||||
this.orgTypePropertiesMapper.insertSelective(properties);
|
||||
}
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
public String initRootOrg(String businessId, String businessName) throws ServiceException {
|
||||
OrganizationTypeQueryDto record = new OrganizationTypeQueryDto();
|
||||
record.setBusinessId("cloudwalk");
|
||||
record.setCode("ROOT");
|
||||
record.setStatus(Integer.valueOf(0));
|
||||
record.setHasDefault(Integer.valueOf(1));
|
||||
List<OrganizationType> organizationTypes = this.orgTypeMapper.select(record);
|
||||
OrganizationType organizationType = organizationTypes.get(0);
|
||||
GetsOrganizationDTO existQuery = new GetsOrganizationDTO();
|
||||
existQuery.setBusinessId(businessId);
|
||||
existQuery.setIsDel(Short.valueOf((short)0));
|
||||
existQuery.setTypeId(organizationType.getId());
|
||||
List<Organization> organizationList = this.organizationMapper.gets(existQuery);
|
||||
if (!organizationList.isEmpty()) {
|
||||
return ((Organization)organizationList.get(0)).getId();
|
||||
}
|
||||
Organization organization = new Organization();
|
||||
organization.setBusinessId(businessId);
|
||||
organization.setTypeId(organizationType.getId());
|
||||
organization.setIsDel(Short.valueOf((short)0));
|
||||
organization.setName(businessName);
|
||||
String rootOrgId = CloudwalkDateUtils.getUUID();
|
||||
organization.setId(rootOrgId);
|
||||
organization.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
organization.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
organization.setIsValid(Integer.valueOf(1));
|
||||
this.organizationMapper.insertSelective(organization);
|
||||
return rootOrgId;
|
||||
}
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
public CloudwalkResult<Boolean> initParkOrg(String businessId, String businessName, String rootOrgId) throws ServiceException {
|
||||
OrganizationTypeQueryDto record = new OrganizationTypeQueryDto();
|
||||
record.setBusinessId(businessId);
|
||||
record.setCode("PARK");
|
||||
record.setStatus(Integer.valueOf(0));
|
||||
record.setHasDefault(Integer.valueOf(1));
|
||||
List<OrganizationType> exists = this.orgTypeMapper.select(record);
|
||||
if (!exists.isEmpty()) {
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
record = new OrganizationTypeQueryDto();
|
||||
record.setBusinessId("cloudwalk");
|
||||
record.setCode("PARK");
|
||||
record.setStatus(Integer.valueOf(0));
|
||||
record.setHasDefault(Integer.valueOf(1));
|
||||
List<OrganizationType> organizationTypes = this.orgTypeMapper.select(record);
|
||||
if (!CollectionUtils.isEmpty(organizationTypes)) {
|
||||
for (OrganizationType organizationType : organizationTypes) {
|
||||
String oldTypeId = organizationType.getId();
|
||||
String typeId = CloudwalkDateUtils.getUUID();
|
||||
organizationType.setId(typeId);
|
||||
organizationType.setBusinessId(businessId);
|
||||
this.orgTypeMapper.insertSelective(organizationType);
|
||||
OrganizationTypeProperties typePropertiesQuery = new OrganizationTypeProperties();
|
||||
typePropertiesQuery.setBusinessId("cloudwalk");
|
||||
typePropertiesQuery.setOrganizationTypeId(oldTypeId);
|
||||
typePropertiesQuery.setStatus(ImageStoreConstants.COMMON_PARK_PROPERTIES_STATUS);
|
||||
List<OrganizationTypeProperties> properties = this.orgTypePropertiesMapper.select(typePropertiesQuery);
|
||||
for (OrganizationTypeProperties property : properties) {
|
||||
property.setId(CloudwalkDateUtils.getUUID());
|
||||
property.setBusinessId(businessId);
|
||||
property.setOrganizationTypeId(typeId);
|
||||
this.orgTypePropertiesMapper.insertSelective(property);
|
||||
}
|
||||
Organization organization = new Organization();
|
||||
organization.setBusinessId(businessId);
|
||||
organization.setTypeId(typeId);
|
||||
organization.setIsDel(Short.valueOf((short)0));
|
||||
organization.setName(businessName + organizationType.getName());
|
||||
organization.setId(CloudwalkDateUtils.getUUID());
|
||||
organization.setParentId(rootOrgId);
|
||||
organization.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
organization.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
organization.setIsValid(Integer.valueOf(1));
|
||||
this.organizationMapper.insertSelective(organization);
|
||||
}
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/OrganizationUnitTypeServiceImpl.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+775
-769
File diff suppressed because it is too large
Load Diff
+112
-103
@@ -15,7 +15,6 @@ import cn.cloudwalk.cloud.session.company.CompanyContext;
|
||||
import cn.cloudwalk.cloud.session.user.UserContext;
|
||||
import cn.cloudwalk.cwos.client.event.event.PersonCardCompareEvent;
|
||||
import cn.cloudwalk.intelligent.davinci.storage.manager.FileStorageManager;
|
||||
import cn.cloudwalk.service.organization.service.CommonPersonRegistryService;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import java.lang.reflect.Field;
|
||||
import java.text.SimpleDateFormat;
|
||||
@@ -33,108 +32,118 @@ import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springside.modules.utils.Collections3;
|
||||
|
||||
@Component
|
||||
public class PersonCardCompareEventHandler {
|
||||
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
private static final int COMPARE_RESULT_SUCCESS = 1;
|
||||
@Resource
|
||||
private PersonRegistryService personRegistryService;
|
||||
@Resource
|
||||
private IPersonAuditServcie personAuditServcie;
|
||||
@Resource
|
||||
private CommonPersonRegistryService commonPersonRegistryService;
|
||||
@Resource
|
||||
private FileStorageManager fileStorageManager;
|
||||
@Resource
|
||||
private PersonFileService personFileService;
|
||||
|
||||
@Async(value="personRegistryExecutor")
|
||||
public void handler(PersonCardCompareEvent personCardCompareEvent) {
|
||||
if (personCardCompareEvent == null || 1 != personCardCompareEvent.getCompareResult()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
String applicationId = this.commonPersonRegistryService.getApplicationId(personCardCompareEvent.getBusinessId());
|
||||
if (StringUtils.isBlank((CharSequence)applicationId) || !Objects.equals(applicationId, personCardCompareEvent.getApplicationId())) {
|
||||
this.logger.warn("PersonCardCompareEventHandler handler 应用id不匹配:[{}]", (Object)JSON.toJSONString((Object)personCardCompareEvent));
|
||||
return;
|
||||
}
|
||||
CompanyContext company = new CompanyContext();
|
||||
company.setCompanyId(personCardCompareEvent.getBusinessId());
|
||||
UserContext userContext = new UserContext();
|
||||
userContext.setCaller("default");
|
||||
userContext.setCallerName("default");
|
||||
CloudwalkCallContext context = new CloudwalkCallContext();
|
||||
context.setCompany(company);
|
||||
context.setUser(userContext);
|
||||
QueryPersonRegistryParam registryParam = new QueryPersonRegistryParam();
|
||||
registryParam.setType(RegistryTypeEnum.CERT_REGISTRY.getValue());
|
||||
registryParam.setDeviceCode(personCardCompareEvent.getDeviceId());
|
||||
registryParam.setBusinessId(personCardCompareEvent.getBusinessId());
|
||||
CloudwalkResult personPropertiesListResult = this.personRegistryService.getRegistryPropertyList(registryParam, context);
|
||||
if (personPropertiesListResult.isSuccess() && Collections3.isNotEmpty((Collection)((Collection)personPropertiesListResult.getData()))) {
|
||||
AddPersonAuditParam auditParam = this.reflectParam(personCardCompareEvent, (List)personPropertiesListResult.getData());
|
||||
auditParam.setBusinessId(personCardCompareEvent.getBusinessId());
|
||||
this.personAuditServcie.add(auditParam, context);
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("执行报错 {}: {}", (Object)e.getClass().getName(), (Object)e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private AddPersonAuditParam reflectParam(PersonCardCompareEvent eventParam, List<PersonPropertiesResult> personPropertiesList) {
|
||||
this.logger.info("PersonCardCompareEventHandler reflectParam eventParam:{}; personPropertiesList:{}", (Object)eventParam, personPropertiesList);
|
||||
AddPersonAuditParam auditParam = new AddPersonAuditParam();
|
||||
auditParam.setDeviceCode(eventParam.getDeviceId());
|
||||
auditParam.setIsBase64(Integer.valueOf(0));
|
||||
auditParam.setSource(CpPersonSourceEnum.CERT.getCode());
|
||||
auditParam.setComparePicture(eventParam.getSpotImagePath());
|
||||
boolean comparePictureBindCard = false;
|
||||
for (PersonPropertiesResult personProperties : personPropertiesList) {
|
||||
try {
|
||||
if (eventParam.getCardData() == null) continue;
|
||||
Field eventParamField = ReflectionUtils.findField(eventParam.getCardData().getClass(), (String)personProperties.getBindProp());
|
||||
eventParamField.setAccessible(true);
|
||||
Object value = ReflectionUtils.getField((Field)eventParamField, (Object)eventParam.getCardData());
|
||||
if (CertPropertyEnum.CARD_IMAGE_PATH.getValue().equals(personProperties.getBindProp()) && personProperties.getCode().equals("comparePicture")) {
|
||||
comparePictureBindCard = true;
|
||||
}
|
||||
if (CertPropertyEnum.SEX.getValue().equals(personProperties.getBindProp())) {
|
||||
int sexValue = Integer.valueOf(Optional.ofNullable(value).orElse("0").toString());
|
||||
value = 1 == sexValue ? "男" : (2 == sexValue ? "女" : "未知");
|
||||
}
|
||||
if (CertPropertyEnum.BIRTHDAY.getValue().equals(personProperties.getBindProp())) {
|
||||
String birthdayValue = Optional.ofNullable(value).orElse("").toString();
|
||||
SimpleDateFormat birthdayFormat = new SimpleDateFormat("yyyyMMdd");
|
||||
if (StringUtils.isNotBlank((CharSequence)birthdayValue)) {
|
||||
Date birthdayDate = birthdayFormat.parse(birthdayValue);
|
||||
value = String.valueOf(birthdayDate.getTime());
|
||||
}
|
||||
}
|
||||
Field auditParamField = ReflectionUtils.findField(auditParam.getClass(), (String)personProperties.getCode());
|
||||
auditParamField.setAccessible(true);
|
||||
ReflectionUtils.setField((Field)auditParamField, (Object)auditParam, (Object)value);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.warn("PersonCardCompareEventHandler setValueByFieldName ", e);
|
||||
}
|
||||
}
|
||||
if (!comparePictureBindCard) {
|
||||
try {
|
||||
byte[] downloadByte = this.fileStorageManager.fileDownload(eventParam.getSpotImagePath());
|
||||
MultipartFile multipartFile = this.personFileService.buildMultipartFile(System.currentTimeMillis() + ".jpg", downloadByte);
|
||||
CloudwalkResult uploadResult = this.personFileService.uploadCompressImage2(multipartFile);
|
||||
if (uploadResult.isSuccess()) {
|
||||
auditParam.setComparePicture((String)uploadResult.getData());
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("PersonCardCompareEventHandler handler spot image error:{}", (Object)e.getMessage());
|
||||
}
|
||||
}
|
||||
return auditParam;
|
||||
}
|
||||
public class PersonCardCompareEventHandler
|
||||
{
|
||||
protected final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
private static final int COMPARE_RESULT_SUCCESS = 1;
|
||||
@Resource
|
||||
private PersonRegistryService personRegistryService;
|
||||
@Resource
|
||||
private IPersonAuditServcie personAuditServcie;
|
||||
@Resource
|
||||
private CommonPersonRegistryService commonPersonRegistryService;
|
||||
@Resource
|
||||
private FileStorageManager fileStorageManager;
|
||||
@Resource
|
||||
private PersonFileService personFileService;
|
||||
@Async("personRegistryExecutor")
|
||||
public void handler(PersonCardCompareEvent personCardCompareEvent) {
|
||||
if (personCardCompareEvent == null || 1 != personCardCompareEvent.getCompareResult().intValue()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
String applicationId = this.commonPersonRegistryService.getApplicationId(personCardCompareEvent.getBusinessId());
|
||||
if (StringUtils.isBlank(applicationId) || !Objects.equals(applicationId, personCardCompareEvent.getApplicationId())) {
|
||||
this.logger.warn("PersonCardCompareEventHandler handler 应用id不匹配:[{}]", JSON.toJSONString(personCardCompareEvent));
|
||||
return;
|
||||
}
|
||||
CompanyContext company = new CompanyContext();
|
||||
company.setCompanyId(personCardCompareEvent.getBusinessId());
|
||||
UserContext userContext = new UserContext();
|
||||
userContext.setCaller("default");
|
||||
userContext.setCallerName("default");
|
||||
CloudwalkCallContext context = new CloudwalkCallContext();
|
||||
context.setCompany(company);
|
||||
context.setUser(userContext);
|
||||
QueryPersonRegistryParam registryParam = new QueryPersonRegistryParam();
|
||||
registryParam.setType(RegistryTypeEnum.CERT_REGISTRY.getValue());
|
||||
registryParam.setDeviceCode(personCardCompareEvent.getDeviceId());
|
||||
registryParam.setBusinessId(personCardCompareEvent.getBusinessId());
|
||||
CloudwalkResult<List<PersonPropertiesResult>> personPropertiesListResult = this.personRegistryService.getRegistryPropertyList(registryParam, context);
|
||||
if (personPropertiesListResult.isSuccess() &&
|
||||
Collections3.isNotEmpty((Collection)personPropertiesListResult.getData())) {
|
||||
AddPersonAuditParam auditParam = reflectParam(personCardCompareEvent, (List<PersonPropertiesResult>)personPropertiesListResult.getData());
|
||||
auditParam.setBusinessId(personCardCompareEvent.getBusinessId());
|
||||
this.personAuditServcie.add(auditParam, context);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
this.logger.error("执行报错 {}: {}", e.getClass().getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
private AddPersonAuditParam reflectParam(PersonCardCompareEvent eventParam, List<PersonPropertiesResult> personPropertiesList) {
|
||||
this.logger.info("PersonCardCompareEventHandler reflectParam eventParam:{}; personPropertiesList:{}", eventParam, personPropertiesList);
|
||||
AddPersonAuditParam auditParam = new AddPersonAuditParam();
|
||||
auditParam.setDeviceCode(eventParam.getDeviceId());
|
||||
auditParam.setIsBase64(Integer.valueOf(0));
|
||||
auditParam.setSource(CpPersonSourceEnum.CERT.getCode());
|
||||
auditParam.setComparePicture(eventParam.getSpotImagePath());
|
||||
boolean comparePictureBindCard = false;
|
||||
for (PersonPropertiesResult personProperties : personPropertiesList) {
|
||||
try {
|
||||
if (eventParam.getCardData() != null) {
|
||||
Field eventParamField = ReflectionUtils.findField(eventParam.getCardData().getClass(), personProperties.getBindProp());
|
||||
eventParamField.setAccessible(true);
|
||||
Object value = ReflectionUtils.getField(eventParamField, eventParam.getCardData());
|
||||
if (CertPropertyEnum.CARD_IMAGE_PATH.getValue().equals(personProperties.getBindProp()) && personProperties
|
||||
.getCode().equals("comparePicture"))
|
||||
{
|
||||
comparePictureBindCard = true;
|
||||
}
|
||||
if (CertPropertyEnum.SEX.getValue().equals(personProperties.getBindProp())) {
|
||||
int sexValue = Integer.valueOf(Optional.<T>ofNullable((T)value).orElse((T)"0").toString()).intValue();
|
||||
if (1 == sexValue) {
|
||||
value = "男";
|
||||
} else if (2 == sexValue) {
|
||||
value = "女";
|
||||
} else {
|
||||
value = "未知";
|
||||
}
|
||||
}
|
||||
if (CertPropertyEnum.BIRTHDAY.getValue().equals(personProperties.getBindProp())) {
|
||||
String birthdayValue = Optional.<T>ofNullable((T)value).orElse((T)"").toString();
|
||||
SimpleDateFormat birthdayFormat = new SimpleDateFormat("yyyyMMdd");
|
||||
if (StringUtils.isNotBlank(birthdayValue)) {
|
||||
Date birthdayDate = birthdayFormat.parse(birthdayValue);
|
||||
value = String.valueOf(birthdayDate.getTime());
|
||||
}
|
||||
}
|
||||
Field auditParamField = ReflectionUtils.findField(auditParam.getClass(), personProperties.getCode());
|
||||
auditParamField.setAccessible(true);
|
||||
ReflectionUtils.setField(auditParamField, auditParam, value);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
this.logger.warn("PersonCardCompareEventHandler setValueByFieldName ", e);
|
||||
}
|
||||
}
|
||||
if (!comparePictureBindCard) {
|
||||
try {
|
||||
byte[] downloadByte = this.fileStorageManager.fileDownload(eventParam.getSpotImagePath());
|
||||
MultipartFile multipartFile = this.personFileService.buildMultipartFile(System.currentTimeMillis() + ".jpg", downloadByte);
|
||||
CloudwalkResult<String> uploadResult = this.personFileService.uploadCompressImage2(multipartFile);
|
||||
if (uploadResult.isSuccess()) {
|
||||
auditParam.setComparePicture((String)uploadResult.getData());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
this.logger.error("PersonCardCompareEventHandler handler spot image error:{}", e.getMessage());
|
||||
}
|
||||
}
|
||||
return auditParam;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/PersonCardCompareEventHandler.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+343
-379
@@ -27,7 +27,6 @@ import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Base64;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import javax.annotation.Resource;
|
||||
import javax.imageio.ImageIO;
|
||||
@@ -39,387 +38,352 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.util.FileCopyUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@Service
|
||||
@Primary
|
||||
public class PersonFileServiceImpl
|
||||
extends AbstractImagStoreService
|
||||
implements PersonFileService {
|
||||
@Autowired
|
||||
private FileStorageManager fileStorageManager;
|
||||
@Autowired
|
||||
private FilePartManager filePartManager;
|
||||
@Resource
|
||||
private UUIDSerial uuidSerial;
|
||||
@Autowired
|
||||
private OpenCvUtils openCvUtils;
|
||||
@Resource
|
||||
private CpImageStoreToolService cpImageStoreToolService;
|
||||
@Value(value="${person.name.space}")
|
||||
private String PERSON_NAME_SPACE;
|
||||
@Value(value="${imageQualityScore}")
|
||||
private Double imgQualityScore;
|
||||
@Value(value="${image.size.min:10240}")
|
||||
private int imageSizeMin;
|
||||
@Value(value="${image.size.max:3145728}")
|
||||
private int imageSizeMax;
|
||||
@Value(value="${image.width.min:30}")
|
||||
private int imageWidthMin;
|
||||
@Value(value="${image.width.max:400}")
|
||||
private int imageWidthMax;
|
||||
@Value(value="${image.height.min:30}")
|
||||
private int imageHeightMin;
|
||||
@Value(value="${image.height.max:400}")
|
||||
private int imageHeightMax;
|
||||
@Value(value="${face.width.min:100}")
|
||||
private int faceWidthMin;
|
||||
@Value(value="${face.width.max:400}")
|
||||
private int faceWidthMax;
|
||||
@Value(value="${face.height.min:100}")
|
||||
private int faceHeightMin;
|
||||
@Value(value="${face.height.max:400}")
|
||||
private int faceHeightMax;
|
||||
|
||||
public CloudwalkResult<String> upload(String fileName, byte[] content) {
|
||||
MultipartFile multipartFile = this.buildMultipartFile(fileName, content);
|
||||
try {
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("file upload error", e);
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
}
|
||||
|
||||
public CloudwalkResult<String> upload(String fileName, InputStream inputStream) {
|
||||
try {
|
||||
byte[] content = IOUtils.toByteArray((InputStream)inputStream);
|
||||
return this.upload(fileName, content);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("file upload error", e);
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
}
|
||||
|
||||
public CloudwalkResult<byte[]> get(String filePath) {
|
||||
try {
|
||||
byte[] bytes = this.fileStorageManager.fileDownload(filePath);
|
||||
if (bytes == null) {
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
catch (Exception e) {
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
}
|
||||
|
||||
public CloudwalkResult<InputStream> download(String filePath) {
|
||||
try {
|
||||
InputStream inputStream = this.filePartManager.bigFileDownload(filePath);
|
||||
if (inputStream == null) {
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
catch (Exception e) {
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
}
|
||||
|
||||
public CloudwalkResult<List<String>> delete(List<String> filePathList) {
|
||||
FileRemoveDTO removeDTO = new FileRemoveDTO();
|
||||
removeDTO.setFileList(filePathList);
|
||||
try {
|
||||
return (CloudwalkResult) CloudwalkResult.success($$$);
|
||||
}
|
||||
catch (Exception e) {
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
}
|
||||
|
||||
public CloudwalkResult<String> uploadImage(MultipartFile file) throws ServiceException {
|
||||
String fileName = file.getOriginalFilename();
|
||||
this.checkImage(file);
|
||||
byte[] fileContent = this.rotateImage(file);
|
||||
CloudwalkResult<String> result = this.upload(fileName, fileContent);
|
||||
return result;
|
||||
}
|
||||
|
||||
public CloudwalkResult<String> uploadCompressImage(MultipartFile file) throws ServiceException {
|
||||
String originalFileName = file.getOriginalFilename();
|
||||
String fileName = originalFileName.substring(0, originalFileName.lastIndexOf(46)) + ".jpg";
|
||||
this.checkImage(file);
|
||||
byte[] fileContent = this.rotateImage(file);
|
||||
String imgBase64 = ImageUtil.encodeByte2Base64(fileContent);
|
||||
FaceDetectResult.FaceData faceData = this.detectFace(imgBase64);
|
||||
this.extractFeature(imgBase64);
|
||||
if (this.checkImageSize(fileName, fileContent).booleanValue()) {
|
||||
CloudwalkResult<String> result = this.upload(fileName, fileContent);
|
||||
return result;
|
||||
}
|
||||
BufferedImage bufferedImage = this.base64ToBufferedImage(imgBase64);
|
||||
if (null != bufferedImage) {
|
||||
int x = PersonFileServiceImpl.getX(faceData);
|
||||
int y = PersonFileServiceImpl.getY(faceData);
|
||||
int width = PersonFileServiceImpl.getWidth(faceData, bufferedImage, x);
|
||||
int height = PersonFileServiceImpl.getHeight(faceData, bufferedImage, y);
|
||||
String cropBase64 = this.openCvUtils.cropImgBase64(imgBase64, x, y, width, height);
|
||||
byte[] image = Base64.getDecoder().decode(cropBase64);
|
||||
MultipartFile multipartFile = this.resizeImage(fileName, image);
|
||||
if (null != multipartFile) {
|
||||
try {
|
||||
CloudwalkResult<String> result = this.upload(fileName, multipartFile.getBytes());
|
||||
return result;
|
||||
}
|
||||
catch (IOException e) {
|
||||
this.logger.error("上传图片异常:{}", (Object)e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
return (CloudwalkResult) CloudwalkResult.fail($$$);
|
||||
}
|
||||
|
||||
public CloudwalkResult<String> uploadCompressImage2(MultipartFile file) throws ServiceException {
|
||||
String originalFileName = file.getOriginalFilename();
|
||||
String fileName = originalFileName.substring(0, originalFileName.lastIndexOf(46)) + ".jpg";
|
||||
this.checkImage(file);
|
||||
byte[] fileContent = this.rotateImage(file);
|
||||
if (this.checkImageSize(fileName, fileContent).booleanValue()) {
|
||||
return this.uploadImage(fileName, fileContent);
|
||||
}
|
||||
byte[] resizeFileContent = this.resizeImage2(fileName, fileContent);
|
||||
return this.uploadImage(fileName, resizeFileContent);
|
||||
}
|
||||
|
||||
private CloudwalkResult<String> uploadImage(String fileName, byte[] fileContent) throws ServiceException {
|
||||
String imgBase64 = ImageUtil.encodeByte2Base64(fileContent);
|
||||
FaceDetectResult.FaceData faceData = this.detectFace(imgBase64);
|
||||
if (faceData.getWidth() >= this.faceWidthMin && faceData.getWidth() <= this.faceWidthMax && faceData.getHeight() >= this.faceHeightMin && faceData.getHeight() <= this.faceHeightMax) {
|
||||
String cropBase64 = this.cropImage(imgBase64, faceData);
|
||||
this.extractFeature(cropBase64);
|
||||
byte[] cropContent = Base64.getDecoder().decode(cropBase64);
|
||||
CloudwalkResult<String> result = this.upload(fileName, cropContent);
|
||||
return result;
|
||||
}
|
||||
throw new ServiceException("53060449", this.getMessage("53060449"));
|
||||
}
|
||||
|
||||
private String cropImage(String imgBase64, FaceDetectResult.FaceData faceData) {
|
||||
BufferedImage bufferedImage = this.base64ToBufferedImage(imgBase64);
|
||||
String cropBase64 = "";
|
||||
if (null != bufferedImage) {
|
||||
int x = PersonFileServiceImpl.getX(faceData);
|
||||
int y = PersonFileServiceImpl.getY(faceData);
|
||||
int width = PersonFileServiceImpl.getWidth(faceData, bufferedImage, x);
|
||||
int height = PersonFileServiceImpl.getHeight(faceData, bufferedImage, y);
|
||||
cropBase64 = this.openCvUtils.cropImgBase64(imgBase64, x, y, width, height);
|
||||
}
|
||||
return cropBase64;
|
||||
}
|
||||
|
||||
public static int getX(FaceDetectResult.FaceData faceData) {
|
||||
return Math.round((float)faceData.getX() - (float)faceData.getWidth() / 2.0f) < 0 ? 0 : Math.round((float)faceData.getX() - (float)faceData.getWidth() / 2.0f);
|
||||
}
|
||||
|
||||
public static int getY(FaceDetectResult.FaceData faceData) {
|
||||
return Math.round((float)faceData.getY() - (float)faceData.getHeight() / 2.0f) < 0 ? 0 : Math.round((float)faceData.getY() - (float)faceData.getHeight() / 2.0f);
|
||||
}
|
||||
|
||||
public static int getWidth(FaceDetectResult.FaceData faceData, BufferedImage bufferedImage, int x) {
|
||||
int width;
|
||||
int n = width = 2 * faceData.getWidth() > bufferedImage.getWidth() ? bufferedImage.getWidth() : 2 * faceData.getWidth();
|
||||
if (width + x > bufferedImage.getWidth()) {
|
||||
width = bufferedImage.getWidth() - x;
|
||||
}
|
||||
return width;
|
||||
}
|
||||
|
||||
public static int getHeight(FaceDetectResult.FaceData faceData, BufferedImage bufferedImage, int y) {
|
||||
int height;
|
||||
int n = height = 2 * faceData.getHeight() > bufferedImage.getHeight() ? bufferedImage.getHeight() : 2 * faceData.getHeight();
|
||||
if (height + y > bufferedImage.getHeight()) {
|
||||
height = bufferedImage.getHeight() - y;
|
||||
}
|
||||
return height;
|
||||
}
|
||||
|
||||
private BufferedImage base64ToBufferedImage(String imgBase64) {
|
||||
byte[] image = Base64.getDecoder().decode(imgBase64);
|
||||
BufferedImage bufferedImage = null;
|
||||
try (ByteArrayInputStream bais = new ByteArrayInputStream(image);){
|
||||
bufferedImage = ImageIO.read(bais);
|
||||
}
|
||||
catch (IOException e) {
|
||||
this.logger.error("获取图片大小异常:{}", (Object)e.getMessage());
|
||||
}
|
||||
return bufferedImage;
|
||||
}
|
||||
|
||||
private void checkImage(MultipartFile file) throws ServiceException {
|
||||
try {
|
||||
if (file == null || file.isEmpty() || file.getSize() > (long)ImageStoreConstants.MAX_FILE.intValue()) {
|
||||
throw new ServiceException("53060428", this.getMessage("53060428"));
|
||||
}
|
||||
String fileName = file.getOriginalFilename();
|
||||
this.logger.info("上传图片:{}", (Object)fileName);
|
||||
if (!FileUtil.isAppointFileType(fileName.substring(fileName.lastIndexOf(46) + 1), FileType.JPEG, FileType.JPG, FileType.PNG)) {
|
||||
this.logger.info("文件后缀类型不合法:{}", (Object)fileName);
|
||||
throw new ServiceException("53060429", this.getMessage("53060429"));
|
||||
}
|
||||
if (!FileUtil.isAppointFileContentType(FileUtil.getFileContentType(file.getBytes()), FileContentType.PNG, FileContentType.JPEG)) {
|
||||
this.logger.info("文件内容类型不合法");
|
||||
throw new ServiceException("53060429", this.getMessage("53060429"));
|
||||
}
|
||||
}
|
||||
catch (IOException e) {
|
||||
this.logger.error("校验上传图片异常:{}", (Object)e.getMessage());
|
||||
throw new ServiceException("80014013", this.getMessage("80014013"));
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] rotateImage(MultipartFile file) throws ServiceException {
|
||||
try {
|
||||
byte[] fileOldContent = file.getBytes();
|
||||
String fileName = file.getOriginalFilename();
|
||||
String suffix = fileName.substring(fileName.lastIndexOf(46));
|
||||
File javaFile = File.createTempFile(this.uuidSerial.uuid(), suffix);
|
||||
file.transferTo(javaFile);
|
||||
int now = ImageEditUtils.rotateAngle(javaFile);
|
||||
byte[] fileContent = fileOldContent;
|
||||
if (ImageEditUtils.isRotate(now)) {
|
||||
fileContent = this.openCvUtils.rotateImageBytes(fileOldContent, now);
|
||||
}
|
||||
return fileContent;
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("旋转图片异常:{}", (Object)e.getMessage());
|
||||
throw new ServiceException("53060430", this.getMessage("53060430"));
|
||||
}
|
||||
}
|
||||
|
||||
private void extractFeature(String imgBase64) throws ServiceException {
|
||||
AgFeatureExtractParam extractParam = new AgFeatureExtractParam();
|
||||
extractParam.setImageBase64(imgBase64);
|
||||
CloudwalkResult result = this.cpImageStoreToolService.extractFeature(extractParam);
|
||||
if (!result.isSuccess()) {
|
||||
throw new ServiceException("53060431", this.getMessage("53060431"));
|
||||
}
|
||||
if (((AgFeatureExtractResult)result.getData()).getScore() < this.imgQualityScore) {
|
||||
throw new ServiceException("53003820", this.getMessage("53003820"));
|
||||
}
|
||||
}
|
||||
|
||||
private FaceDetectResult.FaceData detectFace(String imgBase64) throws ServiceException {
|
||||
CpFaceDetectParam faceDetectParam = new CpFaceDetectParam();
|
||||
faceDetectParam.setImageBase64(imgBase64);
|
||||
CloudwalkResult result = this.cpImageStoreToolService.faceDetect(faceDetectParam);
|
||||
if (CollectionUtils.isEmpty((Collection)((FaceDetectResult)result.getData()).getFaces())) {
|
||||
throw new ServiceException("53060432", this.getMessage("53060432"));
|
||||
}
|
||||
if (((FaceDetectResult)result.getData()).getFaces().size() > 1) {
|
||||
throw new ServiceException("53060433", this.getMessage("53060433"));
|
||||
}
|
||||
return (FaceDetectResult.FaceData)((FaceDetectResult)result.getData()).getFaces().get(0);
|
||||
}
|
||||
|
||||
private Boolean checkImageSize(String fileName, byte[] bytes) throws ServiceException {
|
||||
MultipartFile file = this.buildMultipartFile(fileName, bytes);
|
||||
if (file.getSize() < (long)this.imageSizeMin) {
|
||||
throw new ServiceException("53060445", this.getMessage("53060445"));
|
||||
}
|
||||
if (file.getSize() >= (long)this.imageSizeMin && file.getSize() <= (long)this.imageSizeMax) {
|
||||
try {
|
||||
BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
|
||||
if (bufferedImage.getWidth() < this.imageWidthMin || bufferedImage.getHeight() < this.imageHeightMin) {
|
||||
throw new ServiceException("53060446", this.getMessage("53060446"));
|
||||
}
|
||||
if (bufferedImage.getWidth() >= this.imageWidthMin && bufferedImage.getWidth() <= this.imageWidthMax && bufferedImage.getHeight() >= this.imageHeightMin && bufferedImage.getHeight() <= this.imageHeightMax) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (IOException e) {
|
||||
this.logger.error("获取图片大小异常:{}", (Object)e.getMessage());
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private MultipartFile resizeImage(String fileName, byte[] bytes) {
|
||||
MultipartFile file = this.buildMultipartFile(fileName, bytes);
|
||||
BufferedImage bufferedImage = null;
|
||||
try {
|
||||
bufferedImage = ImageIO.read(file.getInputStream());
|
||||
if (file.getSize() > (long)(this.imageSizeMax * 1024) || bufferedImage.getWidth() > this.imageWidthMax || bufferedImage.getHeight() > this.imageHeightMax) {
|
||||
int width = (int)((double)bufferedImage.getWidth() * 0.8);
|
||||
int height = (int)((double)bufferedImage.getHeight() * 0.8);
|
||||
byte[] resizeByte = this.openCvUtils.resizeImageBytes(file.getBytes(), width, height);
|
||||
return this.resizeImage(fileName, resizeByte);
|
||||
}
|
||||
}
|
||||
catch (IOException e) {
|
||||
this.logger.error("压缩图片异常:{}", (Object)e.getMessage());
|
||||
}
|
||||
if (file.getSize() >= (long)(this.imageSizeMin * 1024) && file.getSize() <= (long)(this.imageSizeMax * 1024) && null != bufferedImage && bufferedImage.getWidth() >= this.imageWidthMin && bufferedImage.getWidth() <= this.imageWidthMax && bufferedImage.getHeight() >= this.imageHeightMin && bufferedImage.getHeight() <= this.imageHeightMax) {
|
||||
return file;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private byte[] resizeImage2(String fileName, byte[] bytes) {
|
||||
MultipartFile file = this.buildMultipartFile(fileName, bytes);
|
||||
try {
|
||||
BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
|
||||
BigDecimal widthScale = new BigDecimal(bufferedImage.getWidth()).divide(new BigDecimal(this.imageWidthMax), 2, 4);
|
||||
BigDecimal heightScale = new BigDecimal(bufferedImage.getHeight()).divide(new BigDecimal(this.imageHeightMax), 2, 4);
|
||||
BigDecimal scale = widthScale.compareTo(heightScale) >= 0 ? widthScale : heightScale;
|
||||
int width = new BigDecimal(bufferedImage.getWidth()).divide(scale, 2, 4).intValue();
|
||||
int height = new BigDecimal(bufferedImage.getHeight()).divide(scale, 2, 4).intValue();
|
||||
return this.openCvUtils.resizeImageBytes(file.getBytes(), width, height);
|
||||
}
|
||||
catch (IOException e) {
|
||||
this.logger.error("压缩图片异常:{}", (Object)e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public MultipartFile buildMultipartFile(final String fileName, final byte[] bytes) {
|
||||
MultipartFile file = new MultipartFile(){
|
||||
|
||||
public String getName() {
|
||||
return "file";
|
||||
}
|
||||
|
||||
public String getOriginalFilename() {
|
||||
return fileName;
|
||||
}
|
||||
|
||||
public String getContentType() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return bytes.length == 0;
|
||||
}
|
||||
|
||||
public long getSize() {
|
||||
return bytes.length;
|
||||
}
|
||||
|
||||
public byte[] getBytes() throws IOException {
|
||||
return bytes;
|
||||
}
|
||||
|
||||
public InputStream getInputStream() throws IOException {
|
||||
return new ByteArrayInputStream(bytes);
|
||||
}
|
||||
|
||||
public void transferTo(File dest) throws IOException, IllegalStateException {
|
||||
FileCopyUtils.copy((byte[])bytes, (File)dest);
|
||||
}
|
||||
};
|
||||
return file;
|
||||
}
|
||||
implements PersonFileService
|
||||
{
|
||||
@Autowired
|
||||
private FileStorageManager fileStorageManager;
|
||||
@Autowired
|
||||
private FilePartManager filePartManager;
|
||||
@Resource
|
||||
private UUIDSerial uuidSerial;
|
||||
@Autowired
|
||||
private OpenCvUtils openCvUtils;
|
||||
@Resource
|
||||
private CpImageStoreToolService cpImageStoreToolService;
|
||||
@Value("${person.name.space}")
|
||||
private String PERSON_NAME_SPACE;
|
||||
@Value("${imageQualityScore}")
|
||||
private Double imgQualityScore;
|
||||
@Value("${image.size.min:10240}")
|
||||
private int imageSizeMin;
|
||||
@Value("${image.size.max:3145728}")
|
||||
private int imageSizeMax;
|
||||
@Value("${image.width.min:30}")
|
||||
private int imageWidthMin;
|
||||
@Value("${image.width.max:400}")
|
||||
private int imageWidthMax;
|
||||
@Value("${image.height.min:30}")
|
||||
private int imageHeightMin;
|
||||
@Value("${image.height.max:400}")
|
||||
private int imageHeightMax;
|
||||
@Value("${face.width.min:100}")
|
||||
private int faceWidthMin;
|
||||
@Value("${face.width.max:400}")
|
||||
private int faceWidthMax;
|
||||
@Value("${face.height.min:100}")
|
||||
private int faceHeightMin;
|
||||
@Value("${face.height.max:400}")
|
||||
private int faceHeightMax;
|
||||
public CloudwalkResult<String> upload(String fileName, byte[] content) {
|
||||
MultipartFile multipartFile = buildMultipartFile(fileName, content);
|
||||
try {
|
||||
return CloudwalkResult.success(this.fileStorageManager.fileUpload(this.PERSON_NAME_SPACE, multipartFile));
|
||||
} catch (Exception e) {
|
||||
this.logger.error("file upload error", e);
|
||||
return CloudwalkResult.fail("80014001", getMessage("80014001"));
|
||||
}
|
||||
}
|
||||
public CloudwalkResult<String> upload(String fileName, InputStream inputStream) {
|
||||
try {
|
||||
byte[] content = IOUtils.toByteArray(inputStream);
|
||||
return upload(fileName, content);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("file upload error", e);
|
||||
return CloudwalkResult.fail("80014001", getMessage("80014001"));
|
||||
}
|
||||
}
|
||||
public CloudwalkResult<byte[]> get(String filePath) {
|
||||
try {
|
||||
byte[] bytes = this.fileStorageManager.fileDownload(filePath);
|
||||
if (bytes == null) {
|
||||
return CloudwalkResult.fail("80014016", getMessage("80014016"));
|
||||
}
|
||||
return CloudwalkResult.success(bytes);
|
||||
} catch (Exception e) {
|
||||
return CloudwalkResult.fail("80014016", getMessage("80014016"));
|
||||
}
|
||||
}
|
||||
public CloudwalkResult<InputStream> download(String filePath) {
|
||||
try {
|
||||
InputStream inputStream = this.filePartManager.bigFileDownload(filePath);
|
||||
if (inputStream == null) {
|
||||
return CloudwalkResult.fail("80014016", getMessage("80014016"));
|
||||
}
|
||||
return CloudwalkResult.success(inputStream);
|
||||
} catch (Exception e) {
|
||||
return CloudwalkResult.fail("80014016", getMessage("80014016"));
|
||||
}
|
||||
}
|
||||
public CloudwalkResult<List<String>> delete(List<String> filePathList) {
|
||||
FileRemoveDTO removeDTO = new FileRemoveDTO();
|
||||
removeDTO.setFileList(filePathList);
|
||||
try {
|
||||
return CloudwalkResult.success(this.fileStorageManager.remove(removeDTO));
|
||||
} catch (Exception e) {
|
||||
return CloudwalkResult.fail("80014017", "80014017");
|
||||
}
|
||||
}
|
||||
public CloudwalkResult<String> uploadImage(MultipartFile file) throws ServiceException {
|
||||
String fileName = file.getOriginalFilename();
|
||||
checkImage(file);
|
||||
byte[] fileContent = rotateImage(file);
|
||||
CloudwalkResult<String> result = upload(fileName, fileContent);
|
||||
return result;
|
||||
}
|
||||
public CloudwalkResult<String> uploadCompressImage(MultipartFile file) throws ServiceException {
|
||||
String originalFileName = file.getOriginalFilename();
|
||||
String fileName = originalFileName.substring(0, originalFileName.lastIndexOf('.')) + ".jpg";
|
||||
checkImage(file);
|
||||
byte[] fileContent = rotateImage(file);
|
||||
String imgBase64 = ImageUtil.encodeByte2Base64(fileContent);
|
||||
FaceDetectResult.FaceData faceData = detectFace(imgBase64);
|
||||
extractFeature(imgBase64);
|
||||
if (checkImageSize(fileName, fileContent).booleanValue()) {
|
||||
CloudwalkResult<String> result = upload(fileName, fileContent);
|
||||
return result;
|
||||
}
|
||||
BufferedImage bufferedImage = base64ToBufferedImage(imgBase64);
|
||||
if (null != bufferedImage) {
|
||||
int x = getX(faceData);
|
||||
int y = getY(faceData);
|
||||
int width = getWidth(faceData, bufferedImage, x);
|
||||
int height = getHeight(faceData, bufferedImage, y);
|
||||
String cropBase64 = this.openCvUtils.cropImgBase64(imgBase64, x, y, width, height);
|
||||
byte[] image = Base64.getDecoder().decode(cropBase64);
|
||||
MultipartFile multipartFile = resizeImage(fileName, image);
|
||||
if (null != multipartFile) {
|
||||
try {
|
||||
CloudwalkResult<String> result = upload(fileName, multipartFile.getBytes());
|
||||
return result;
|
||||
} catch (IOException e) {
|
||||
this.logger.error("上传图片异常:{}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
return CloudwalkResult.fail("53060437", getMessage("53060437"));
|
||||
}
|
||||
public CloudwalkResult<String> uploadCompressImage2(MultipartFile file) throws ServiceException {
|
||||
String originalFileName = file.getOriginalFilename();
|
||||
String fileName = originalFileName.substring(0, originalFileName.lastIndexOf('.')) + ".jpg";
|
||||
checkImage(file);
|
||||
byte[] fileContent = rotateImage(file);
|
||||
if (checkImageSize(fileName, fileContent).booleanValue()) {
|
||||
return uploadImage(fileName, fileContent);
|
||||
}
|
||||
byte[] resizeFileContent = resizeImage2(fileName, fileContent);
|
||||
return uploadImage(fileName, resizeFileContent);
|
||||
}
|
||||
private CloudwalkResult<String> uploadImage(String fileName, byte[] fileContent) throws ServiceException {
|
||||
String imgBase64 = ImageUtil.encodeByte2Base64(fileContent);
|
||||
FaceDetectResult.FaceData faceData = detectFace(imgBase64);
|
||||
if (faceData.getWidth() >= this.faceWidthMin && faceData.getWidth() <= this.faceWidthMax && faceData
|
||||
.getHeight() >= this.faceHeightMin && faceData.getHeight() <= this.faceHeightMax) {
|
||||
String cropBase64 = cropImage(imgBase64, faceData);
|
||||
extractFeature(cropBase64);
|
||||
byte[] cropContent = Base64.getDecoder().decode(cropBase64);
|
||||
CloudwalkResult<String> result = upload(fileName, cropContent);
|
||||
return result;
|
||||
}
|
||||
throw new ServiceException("53060449", getMessage("53060449"));
|
||||
}
|
||||
private String cropImage(String imgBase64, FaceDetectResult.FaceData faceData) {
|
||||
BufferedImage bufferedImage = base64ToBufferedImage(imgBase64);
|
||||
String cropBase64 = "";
|
||||
if (null != bufferedImage) {
|
||||
int x = getX(faceData);
|
||||
int y = getY(faceData);
|
||||
int width = getWidth(faceData, bufferedImage, x);
|
||||
int height = getHeight(faceData, bufferedImage, y);
|
||||
cropBase64 = this.openCvUtils.cropImgBase64(imgBase64, x, y, width, height);
|
||||
}
|
||||
return cropBase64;
|
||||
}
|
||||
public static int getX(FaceDetectResult.FaceData faceData) {
|
||||
return (Math.round(faceData.getX() - faceData.getWidth() / 2.0F) < 0) ? 0 : Math.round(faceData.getX() - faceData.getWidth() / 2.0F);
|
||||
}
|
||||
public static int getY(FaceDetectResult.FaceData faceData) {
|
||||
return (Math.round(faceData.getY() - faceData.getHeight() / 2.0F) < 0) ? 0 : Math.round(faceData.getY() - faceData.getHeight() / 2.0F);
|
||||
}
|
||||
public static int getWidth(FaceDetectResult.FaceData faceData, BufferedImage bufferedImage, int x) {
|
||||
int width = (2 * faceData.getWidth() > bufferedImage.getWidth()) ? bufferedImage.getWidth() : (2 * faceData.getWidth());
|
||||
if (width + x > bufferedImage.getWidth()) {
|
||||
width = bufferedImage.getWidth() - x;
|
||||
}
|
||||
return width;
|
||||
}
|
||||
public static int getHeight(FaceDetectResult.FaceData faceData, BufferedImage bufferedImage, int y) {
|
||||
int height = (2 * faceData.getHeight() > bufferedImage.getHeight()) ? bufferedImage.getHeight() : (2 * faceData.getHeight());
|
||||
if (height + y > bufferedImage.getHeight()) {
|
||||
height = bufferedImage.getHeight() - y;
|
||||
}
|
||||
return height;
|
||||
}
|
||||
private BufferedImage base64ToBufferedImage(String imgBase64) {
|
||||
byte[] image = Base64.getDecoder().decode(imgBase64);
|
||||
BufferedImage bufferedImage = null;
|
||||
try (ByteArrayInputStream bais = new ByteArrayInputStream(image)) {
|
||||
bufferedImage = ImageIO.read(bais);
|
||||
} catch (IOException e) {
|
||||
this.logger.error("获取图片大小异常:{}", e.getMessage());
|
||||
}
|
||||
return bufferedImage;
|
||||
}
|
||||
private void checkImage(MultipartFile file) throws ServiceException {
|
||||
try {
|
||||
if (file == null || file.isEmpty() || file.getSize() > ImageStoreConstants.MAX_FILE.intValue()) {
|
||||
throw new ServiceException("53060428", getMessage("53060428"));
|
||||
}
|
||||
String fileName = file.getOriginalFilename();
|
||||
this.logger.info("上传图片:{}", fileName);
|
||||
if (!FileUtil.isAppointFileType(fileName.substring(fileName.lastIndexOf('.') + 1), new FileType[] { FileType.JPEG, FileType.JPG, FileType.PNG })) {
|
||||
this.logger.info("文件后缀类型不合法:{}", fileName);
|
||||
throw new ServiceException("53060429", getMessage("53060429"));
|
||||
}
|
||||
if (!FileUtil.isAppointFileContentType(FileUtil.getFileContentType(file.getBytes()), new FileContentType[] { FileContentType.PNG, FileContentType.JPEG })) {
|
||||
this.logger.info("文件内容类型不合法");
|
||||
throw new ServiceException("53060429", getMessage("53060429"));
|
||||
}
|
||||
} catch (IOException e) {
|
||||
this.logger.error("校验上传图片异常:{}", e.getMessage());
|
||||
throw new ServiceException("80014013", getMessage("80014013"));
|
||||
}
|
||||
}
|
||||
private byte[] rotateImage(MultipartFile file) throws ServiceException {
|
||||
try {
|
||||
byte[] fileOldContent = file.getBytes();
|
||||
String fileName = file.getOriginalFilename();
|
||||
String suffix = fileName.substring(fileName.lastIndexOf('.'));
|
||||
File javaFile = File.createTempFile(this.uuidSerial.uuid(), suffix);
|
||||
file.transferTo(javaFile);
|
||||
int now = ImageEditUtils.rotateAngle(javaFile);
|
||||
byte[] fileContent = fileOldContent;
|
||||
if (ImageEditUtils.isRotate(now)) {
|
||||
fileContent = this.openCvUtils.rotateImageBytes(fileOldContent, now);
|
||||
}
|
||||
return fileContent;
|
||||
} catch (Exception e) {
|
||||
this.logger.error("旋转图片异常:{}", e.getMessage());
|
||||
throw new ServiceException("53060430", getMessage("53060430"));
|
||||
}
|
||||
}
|
||||
private void extractFeature(String imgBase64) throws ServiceException {
|
||||
AgFeatureExtractParam extractParam = new AgFeatureExtractParam();
|
||||
extractParam.setImageBase64(imgBase64);
|
||||
CloudwalkResult<AgFeatureExtractResult> result = this.cpImageStoreToolService.extractFeature(extractParam);
|
||||
if (!result.isSuccess()) {
|
||||
throw new ServiceException("53060431", getMessage("53060431"));
|
||||
}
|
||||
if (((AgFeatureExtractResult)result.getData()).getScore().doubleValue() < this.imgQualityScore.doubleValue()) {
|
||||
throw new ServiceException("53003820", getMessage("53003820"));
|
||||
}
|
||||
}
|
||||
private FaceDetectResult.FaceData detectFace(String imgBase64) throws ServiceException {
|
||||
CpFaceDetectParam faceDetectParam = new CpFaceDetectParam();
|
||||
faceDetectParam.setImageBase64(imgBase64);
|
||||
CloudwalkResult<FaceDetectResult> result = this.cpImageStoreToolService.faceDetect(faceDetectParam);
|
||||
if (CollectionUtils.isEmpty(((FaceDetectResult)result.getData()).getFaces())) {
|
||||
throw new ServiceException("53060432", getMessage("53060432"));
|
||||
}
|
||||
if (((FaceDetectResult)result.getData()).getFaces().size() > 1) {
|
||||
throw new ServiceException("53060433", getMessage("53060433"));
|
||||
}
|
||||
return ((FaceDetectResult)result.getData()).getFaces().get(0);
|
||||
}
|
||||
private Boolean checkImageSize(String fileName, byte[] bytes) throws ServiceException {
|
||||
MultipartFile file = buildMultipartFile(fileName, bytes);
|
||||
if (file.getSize() < this.imageSizeMin) {
|
||||
throw new ServiceException("53060445", getMessage("53060445"));
|
||||
}
|
||||
if (file.getSize() >= this.imageSizeMin && file.getSize() <= this.imageSizeMax) {
|
||||
try {
|
||||
BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
|
||||
if (bufferedImage.getWidth() < this.imageWidthMin || bufferedImage.getHeight() < this.imageHeightMin) {
|
||||
throw new ServiceException("53060446", getMessage("53060446"));
|
||||
}
|
||||
if (bufferedImage.getWidth() >= this.imageWidthMin && bufferedImage.getWidth() <= this.imageWidthMax && bufferedImage
|
||||
.getHeight() >= this.imageHeightMin && bufferedImage.getHeight() <= this.imageHeightMax) {
|
||||
return Boolean.valueOf(true);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
this.logger.error("获取图片大小异常:{}", e.getMessage());
|
||||
}
|
||||
}
|
||||
return Boolean.valueOf(false);
|
||||
}
|
||||
private MultipartFile resizeImage(String fileName, byte[] bytes) {
|
||||
MultipartFile file = buildMultipartFile(fileName, bytes);
|
||||
BufferedImage bufferedImage = null;
|
||||
try {
|
||||
bufferedImage = ImageIO.read(file.getInputStream());
|
||||
if (file.getSize() > (this.imageSizeMax * 1024) || bufferedImage.getWidth() > this.imageWidthMax || bufferedImage.getHeight() > this.imageHeightMax) {
|
||||
int width = (int)(bufferedImage.getWidth() * 0.8D);
|
||||
int height = (int)(bufferedImage.getHeight() * 0.8D);
|
||||
byte[] resizeByte = this.openCvUtils.resizeImageBytes(file.getBytes(), width, height);
|
||||
return resizeImage(fileName, resizeByte);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
this.logger.error("压缩图片异常:{}", e.getMessage());
|
||||
}
|
||||
if (file.getSize() >= (this.imageSizeMin * 1024) && file.getSize() <= (this.imageSizeMax * 1024) && null != bufferedImage && bufferedImage
|
||||
.getWidth() >= this.imageWidthMin && bufferedImage.getWidth() <= this.imageWidthMax && bufferedImage
|
||||
.getHeight() >= this.imageHeightMin && bufferedImage.getHeight() <= this.imageHeightMax) {
|
||||
return file;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
private byte[] resizeImage2(String fileName, byte[] bytes) {
|
||||
MultipartFile file = buildMultipartFile(fileName, bytes);
|
||||
try {
|
||||
BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
|
||||
BigDecimal widthScale = (new BigDecimal(bufferedImage.getWidth())).divide(new BigDecimal(this.imageWidthMax), 2, 4);
|
||||
BigDecimal heightScale = (new BigDecimal(bufferedImage.getHeight())).divide(new BigDecimal(this.imageHeightMax), 2, 4);
|
||||
BigDecimal scale = (widthScale.compareTo(heightScale) >= 0) ? widthScale : heightScale;
|
||||
int width = (new BigDecimal(bufferedImage.getWidth())).divide(scale, 2, 4).intValue();
|
||||
int height = (new BigDecimal(bufferedImage.getHeight())).divide(scale, 2, 4).intValue();
|
||||
return this.openCvUtils.resizeImageBytes(file.getBytes(), width, height);
|
||||
} catch (IOException e) {
|
||||
this.logger.error("压缩图片异常:{}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
public MultipartFile buildMultipartFile(final String fileName, final byte[] bytes) {
|
||||
MultipartFile file = new MultipartFile()
|
||||
{
|
||||
public String getName() {
|
||||
return "file";
|
||||
}
|
||||
public String getOriginalFilename() {
|
||||
return fileName;
|
||||
}
|
||||
public String getContentType() {
|
||||
return null;
|
||||
}
|
||||
public boolean isEmpty() {
|
||||
return (bytes.length == 0);
|
||||
}
|
||||
public long getSize() {
|
||||
return bytes.length;
|
||||
}
|
||||
public byte[] getBytes() throws IOException {
|
||||
return bytes;
|
||||
}
|
||||
public InputStream getInputStream() throws IOException {
|
||||
return new ByteArrayInputStream(bytes);
|
||||
}
|
||||
public void transferTo(File dest) throws IOException, IllegalStateException {
|
||||
FileCopyUtils.copy(bytes, dest);
|
||||
}
|
||||
};
|
||||
return file;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/PersonFileServiceImpl.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+37
-36
@@ -7,48 +7,49 @@ import cn.cloudwalk.cloud.utils.CloudwalkDateUtils;
|
||||
import cn.cloudwalk.data.organization.entity.PersonZoneRef;
|
||||
import cn.cloudwalk.data.organization.entity.PersonZoneRefExample;
|
||||
import cn.cloudwalk.data.organization.mapper.PersonZoneRefMapper;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
@Service
|
||||
public class PersonZoneRefServiceImpl
|
||||
implements PersonZoneRefService {
|
||||
@Autowired
|
||||
private PersonZoneRefMapper personZoneRefMapper;
|
||||
|
||||
@Transactional(rollbackFor={Exception.class})
|
||||
public void add(String personId, List<String> zoneIdList, String userId) {
|
||||
for (String zoneId : zoneIdList) {
|
||||
PersonZoneRef personZoneRef = new PersonZoneRef();
|
||||
personZoneRef.setPersonId(personId);
|
||||
personZoneRef.setZoneId(zoneId);
|
||||
personZoneRef.setId(CloudwalkDateUtils.getUUID());
|
||||
personZoneRef.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
personZoneRef.setCreateUserId(userId);
|
||||
this.personZoneRefMapper.insertSelective(personZoneRef);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly=true)
|
||||
public List<PersonZoneRefResult> getList(String personId) {
|
||||
PersonZoneRefExample personZoneRefExample = new PersonZoneRefExample();
|
||||
personZoneRefExample.createCriteria().andPersonIdEqualTo(personId);
|
||||
List personZoneRefs = this.personZoneRefMapper.selectByExample(personZoneRefExample);
|
||||
if (CollectionUtils.isEmpty((Collection)personZoneRefs)) {
|
||||
return null;
|
||||
}
|
||||
return BeanCopyUtils.copy((Collection)personZoneRefs, PersonZoneRefResult.class);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor={Exception.class})
|
||||
public void delete(String personId) {
|
||||
PersonZoneRefExample personZoneRefExample = new PersonZoneRefExample();
|
||||
personZoneRefExample.createCriteria().andPersonIdEqualTo(personId);
|
||||
this.personZoneRefMapper.deleteByExample(personZoneRefExample);
|
||||
}
|
||||
implements PersonZoneRefService
|
||||
{
|
||||
@Autowired
|
||||
private PersonZoneRefMapper personZoneRefMapper;
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
public void add(String personId, List<String> zoneIdList, String userId) {
|
||||
for (String zoneId : zoneIdList) {
|
||||
PersonZoneRef personZoneRef = new PersonZoneRef();
|
||||
personZoneRef.setPersonId(personId);
|
||||
personZoneRef.setZoneId(zoneId);
|
||||
personZoneRef.setId(CloudwalkDateUtils.getUUID());
|
||||
personZoneRef.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
personZoneRef.setCreateUserId(userId);
|
||||
this.personZoneRefMapper.insertSelective(personZoneRef);
|
||||
}
|
||||
}
|
||||
@Transactional(readOnly = true)
|
||||
public List<PersonZoneRefResult> getList(String personId) {
|
||||
PersonZoneRefExample personZoneRefExample = new PersonZoneRefExample();
|
||||
personZoneRefExample.createCriteria().andPersonIdEqualTo(personId);
|
||||
List<PersonZoneRef> personZoneRefs = this.personZoneRefMapper.selectByExample(personZoneRefExample);
|
||||
if (CollectionUtils.isEmpty(personZoneRefs)) {
|
||||
return null;
|
||||
}
|
||||
return BeanCopyUtils.copy(personZoneRefs, PersonZoneRefResult.class);
|
||||
}
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
public void delete(String personId) {
|
||||
PersonZoneRefExample personZoneRefExample = new PersonZoneRefExample();
|
||||
personZoneRefExample.createCriteria().andPersonIdEqualTo(personId);
|
||||
this.personZoneRefMapper.deleteByExample(personZoneRefExample);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/PersonZoneRefServiceImpl.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+177
-170
@@ -12,7 +12,6 @@ import cn.cloudwalk.data.organization.mapper.DevicePersonSyncLogMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.GroupPersonRefMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonMapper;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import javax.annotation.Resource;
|
||||
@@ -24,175 +23,183 @@ import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
@Component
|
||||
public class PictureResultEventHandler {
|
||||
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
private static final String DEVICE_REPORT_KEY = "lock_device_report_";
|
||||
@Resource
|
||||
private GroupPersonRefMapper groupPersonRefMapper;
|
||||
@Resource
|
||||
private DevicePersonSyncLogMapper devicePersonSyncLogMapper;
|
||||
@Resource
|
||||
private ImgStorePersonMapper imgStorePersonMapper;
|
||||
@Value(value="${device.report.approach.time.diff.milliseconds:1000}")
|
||||
private long approachTime;
|
||||
@Value(value="${cloudwalk.person.sync-log-expire-time:10}")
|
||||
private long syncLogExpireTime;
|
||||
@Autowired
|
||||
private StringRedisTemplate redisTemplate;
|
||||
|
||||
@Async(value="deviceReportTaskExecutor")
|
||||
public void handler(PictureResultEvent event) {
|
||||
if (null == event) {
|
||||
return;
|
||||
}
|
||||
this.logger.debug("Kafka消费图片注册结果数据:[{}]", (Object)JSON.toJSONString((Object)event));
|
||||
try {
|
||||
String deviceId = event.getDeviceId();
|
||||
List imageDataList = event.getImageData();
|
||||
for (ImageData imageData : imageDataList) {
|
||||
ImgStorePerson queryPerson = new ImgStorePerson();
|
||||
queryPerson.setImageId(imageData.getFaceId());
|
||||
List dbPersonList = this.imgStorePersonMapper.query(queryPerson);
|
||||
if (CollectionUtils.isEmpty((Collection)dbPersonList)) {
|
||||
this.logger.warn("根据人脸[{}]查询人员,不存在人员记录", (Object)imageData.getFaceId());
|
||||
continue;
|
||||
}
|
||||
ImgStorePerson dbPerson = (ImgStorePerson)dbPersonList.get(0);
|
||||
DevicePersonSyncLogDTO devicePersonSyncLogDTO = new DevicePersonSyncLogDTO();
|
||||
devicePersonSyncLogDTO.setDeviceId(deviceId);
|
||||
devicePersonSyncLogDTO.setImageStoreId(imageData.getGroupId());
|
||||
devicePersonSyncLogDTO.setPersonId(dbPerson.getId());
|
||||
List syncLogs = this.devicePersonSyncLogMapper.query(devicePersonSyncLogDTO);
|
||||
this.logger.debug("根据设备[{}]图库[{}]人员[{}]查询同步记录日志:[{}]", new Object[]{deviceId, imageData.getGroupId(), dbPerson.getId(), JSON.toJSONString((Object)syncLogs)});
|
||||
if (CollectionUtils.isEmpty((Collection)syncLogs)) {
|
||||
this.logger.warn("不存在同步记录日志");
|
||||
continue;
|
||||
}
|
||||
DevicePersonSyncLog dbSyncLog = (DevicePersonSyncLog)syncLogs.get(0);
|
||||
QueryGroupPersonDTO queryGroupPersonDTO = new QueryGroupPersonDTO();
|
||||
queryGroupPersonDTO.setImageStoreId(imageData.getGroupId());
|
||||
queryGroupPersonDTO.setPersonId(dbPerson.getId());
|
||||
List groupPersonRefs = this.groupPersonRefMapper.query(queryGroupPersonDTO);
|
||||
this.logger.debug("根据图库[{}]人员[{}]查询图库人员关系记录:[{}]", new Object[]{imageData.getGroupId(), dbPerson.getId(), JSON.toJSONString((Object)groupPersonRefs)});
|
||||
if (CollectionUtils.isEmpty((Collection)groupPersonRefs)) {
|
||||
this.logger.warn("不存在图库人员记录");
|
||||
continue;
|
||||
}
|
||||
GroupPersonRef dbGroupPersonRef = (GroupPersonRef)groupPersonRefs.get(0);
|
||||
if (null != imageData.getLastUpdateTime()) {
|
||||
this.logger.debug("设备[{}]上报注册结果存在同步时间[{}]", (Object)deviceId, (Object)imageData.getLastUpdateTime());
|
||||
if (this.lockDeviceReport(deviceId, dbGroupPersonRef.getImageStoreId(), dbGroupPersonRef.getPersonId())) {
|
||||
this.handleSyncTime(imageData, dbGroupPersonRef, dbSyncLog);
|
||||
this.unclockDeviceReport(deviceId, dbGroupPersonRef.getImageStoreId(), dbGroupPersonRef.getPersonId());
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(1000L);
|
||||
this.handleSyncTime(imageData, dbGroupPersonRef, dbSyncLog);
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("PictureResultEventHandler lock device report sleep error:{}", (Object)e.getMessage());
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
this.logger.debug("设备[{}]上报注册结果不存在同步时间", (Object)deviceId);
|
||||
this.handleNoSyncTime(event.getReportTime(), imageData, dbSyncLog);
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("执行报错 {}: {}", (Object)e.getClass().getName(), (Object)e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void handleSyncTime(ImageData imageData, GroupPersonRef dbGroupPersonRef, DevicePersonSyncLog dbSyncLog) {
|
||||
if (null == dbGroupPersonRef.getLastUpdateTime()) {
|
||||
this.logger.warn("数据库图库人员关系记录[{}]同步时间为空", (Object)dbGroupPersonRef.getId());
|
||||
return;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (imageData.getLastUpdateTime() >= dbGroupPersonRef.getLastUpdateTime()) {
|
||||
this.logger.debug("上报注册结果的同步时间[{}]大于等于数据库同步时间[{}]", (Object)imageData.getLastUpdateTime(), (Object)dbGroupPersonRef.getLastUpdateTime());
|
||||
sb.append("上报注册结果同步时间[" + imageData.getLastUpdateTime() + "]大于等于数据库同步时间[" + dbGroupPersonRef.getLastUpdateTime() + "],并且上报注册结果同步时间[" + imageData.getLastUpdateTime() + "]大于等于同步记录最近同步时间[" + dbSyncLog.getLastReportTime() + "],更新count=0");
|
||||
dbSyncLog.setUpdateInfo(sb.toString());
|
||||
this.updateStatusAndCount(imageData, dbSyncLog);
|
||||
} else {
|
||||
this.logger.debug("上报注册结果的同步时间[{}]小于数据库同步时间[{}]", (Object)imageData.getLastUpdateTime(), (Object)dbGroupPersonRef.getLastUpdateTime());
|
||||
sb.append("上报注册结果的同步时间[" + imageData.getLastUpdateTime() + "]小于数据库同步时间[" + dbGroupPersonRef.getLastUpdateTime() + "]");
|
||||
if (dbSyncLog.getCount() == 0) {
|
||||
sb.append(",count=0,上报注册结果同步时间[" + imageData.getLastUpdateTime() + "]大于等于同步记录最近同步时间[" + dbSyncLog.getLastReportTime() + "],更新count=0");
|
||||
dbSyncLog.setUpdateInfo(sb.toString());
|
||||
this.updateStatusAndCount(imageData, dbSyncLog);
|
||||
} else if (dbSyncLog.getCount() == 1) {
|
||||
sb.append(",count=1,更新同步状态:设备未拉取,count--");
|
||||
this.updateStatusAndCountDec(SyncStatusEnum.NOT_PULL.getValue(), imageData, dbSyncLog, sb.toString(), imageData.getLastUpdateTime());
|
||||
} else if (dbSyncLog.getCount() > 1) {
|
||||
sb.append(",count>1,更新同步状态:设备已拉取,count--");
|
||||
this.updateStatusAndCountDec(SyncStatusEnum.PULL.getValue(), imageData, dbSyncLog, sb.toString(), imageData.getLastUpdateTime());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void handleNoSyncTime(Long reportTime, ImageData imageData, DevicePersonSyncLog dbSyncLog) {
|
||||
int syncStatus;
|
||||
int n = syncStatus = imageData.getCode().equals("00000000") ? SyncStatusEnum.SYNC_SUCCESS.getValue() : SyncStatusEnum.SYNC_FAIL.getValue();
|
||||
if (SyncStatusEnum.SYNC_SUCCESS.getValue() == dbSyncLog.getStatus().intValue() || SyncStatusEnum.SYNC_FAIL.getValue() == dbSyncLog.getStatus().intValue()) {
|
||||
this.logger.debug("数据库同步记录[{}]是上报状态[{}]", (Object)dbSyncLog.getId(), (Object)dbSyncLog.getStatus());
|
||||
if (syncStatus != dbSyncLog.getStatus()) {
|
||||
this.logger.debug("上报状态与同步记录[{}]不一致,上报状态[{}],同步记录状态[{}]", new Object[]{dbSyncLog.getId(), syncStatus, dbSyncLog.getStatus()});
|
||||
if (null == reportTime || null != dbSyncLog.getLastUpdateTime() && Math.abs(reportTime - dbSyncLog.getLastUpdateTime()) <= this.approachTime) {
|
||||
this.logger.warn("上报时间[{}]与同步记录表上报时间[{}]相近,不更新同步记录[{}]", new Object[]{reportTime, dbSyncLog.getLastReportTime(), dbSyncLog.getId()});
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
this.logger.debug("更新同步记录[{}],同步状态[{}]和count[{}]", new Object[]{dbSyncLog.getId(), syncStatus, dbSyncLog.getCount() - 1});
|
||||
this.updateStatusAndCountDec(syncStatus, imageData, dbSyncLog, "设备上报注册结果不存在同步时间,更新同步记录", reportTime);
|
||||
}
|
||||
|
||||
private synchronized boolean lockDeviceReport(String deviceId, String imageStoreId, String personId) {
|
||||
String value = deviceId + "_" + imageStoreId + "_" + personId;
|
||||
String key = DEVICE_REPORT_KEY + value;
|
||||
if (this.redisTemplate.hasKey((Object)key).booleanValue()) {
|
||||
return false;
|
||||
}
|
||||
this.redisTemplate.opsForValue().set((Object)key, (Object)value, this.syncLogExpireTime, TimeUnit.SECONDS);
|
||||
return true;
|
||||
}
|
||||
|
||||
private synchronized boolean unclockDeviceReport(String deviceId, String imageStoreId, String personId) {
|
||||
String value = deviceId + "_" + imageStoreId + "_" + personId;
|
||||
String key = DEVICE_REPORT_KEY + value;
|
||||
if (this.redisTemplate.hasKey((Object)key).booleanValue()) {
|
||||
this.redisTemplate.delete((Object)key);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void updateStatusAndCount(ImageData imageData, DevicePersonSyncLog dbSyncLog) {
|
||||
int syncStatus;
|
||||
int n = syncStatus = imageData.getCode().equals("00000000") ? SyncStatusEnum.SYNC_SUCCESS.getValue() : SyncStatusEnum.SYNC_FAIL.getValue();
|
||||
if (null == dbSyncLog.getLastReportTime() || imageData.getLastUpdateTime() >= dbSyncLog.getLastReportTime()) {
|
||||
this.logger.debug("上报注册结果同步时间[{}]大于等于同步记录最近同步时间[{}]", (Object)imageData.getLastUpdateTime(), (Object)dbSyncLog.getLastReportTime());
|
||||
dbSyncLog.setStatus(Integer.valueOf(syncStatus));
|
||||
dbSyncLog.setCount(Integer.valueOf(0));
|
||||
dbSyncLog.setCode(imageData.getCode());
|
||||
dbSyncLog.setErrorMessage(imageData.getMessage());
|
||||
dbSyncLog.setLastReportTime(imageData.getLastUpdateTime());
|
||||
this.devicePersonSyncLogMapper.updateStatusAndCount(dbSyncLog);
|
||||
}
|
||||
}
|
||||
|
||||
private void updateStatusAndCountDec(int status, ImageData imageData, DevicePersonSyncLog dbSyncLog, String updateInfo, Long lastReportTime) {
|
||||
dbSyncLog.setStatus(Integer.valueOf(status));
|
||||
dbSyncLog.setCode(imageData.getCode());
|
||||
dbSyncLog.setErrorMessage(imageData.getMessage());
|
||||
dbSyncLog.setUpdateInfo(updateInfo);
|
||||
dbSyncLog.setLastReportTime(lastReportTime);
|
||||
this.devicePersonSyncLogMapper.updateStatusAndCountDec(dbSyncLog);
|
||||
}
|
||||
public class PictureResultEventHandler
|
||||
{
|
||||
protected final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
private static final String DEVICE_REPORT_KEY = "lock_device_report_";
|
||||
@Resource
|
||||
private GroupPersonRefMapper groupPersonRefMapper;
|
||||
@Resource
|
||||
private DevicePersonSyncLogMapper devicePersonSyncLogMapper;
|
||||
@Resource
|
||||
private ImgStorePersonMapper imgStorePersonMapper;
|
||||
@Value("${device.report.approach.time.diff.milliseconds:1000}")
|
||||
private long approachTime;
|
||||
@Value("${cloudwalk.person.sync-log-expire-time:10}")
|
||||
private long syncLogExpireTime;
|
||||
@Autowired
|
||||
private StringRedisTemplate redisTemplate;
|
||||
@Async("deviceReportTaskExecutor")
|
||||
public void handler(PictureResultEvent event) {
|
||||
if (null == event) {
|
||||
return;
|
||||
}
|
||||
this.logger.debug("Kafka消费图片注册结果数据:[{}]", JSON.toJSONString(event));
|
||||
try {
|
||||
String deviceId = event.getDeviceId();
|
||||
List<ImageData> imageDataList = event.getImageData();
|
||||
for (ImageData imageData : imageDataList) {
|
||||
ImgStorePerson queryPerson = new ImgStorePerson();
|
||||
queryPerson.setImageId(imageData.getFaceId());
|
||||
List<ImgStorePerson> dbPersonList = this.imgStorePersonMapper.query(queryPerson);
|
||||
if (CollectionUtils.isEmpty(dbPersonList)) {
|
||||
this.logger.warn("根据人脸[{}]查询人员,不存在人员记录", imageData.getFaceId());
|
||||
continue;
|
||||
}
|
||||
ImgStorePerson dbPerson = dbPersonList.get(0);
|
||||
DevicePersonSyncLogDTO devicePersonSyncLogDTO = new DevicePersonSyncLogDTO();
|
||||
devicePersonSyncLogDTO.setDeviceId(deviceId);
|
||||
devicePersonSyncLogDTO.setImageStoreId(imageData.getGroupId());
|
||||
devicePersonSyncLogDTO.setPersonId(dbPerson.getId());
|
||||
List<DevicePersonSyncLog> syncLogs = this.devicePersonSyncLogMapper.query(devicePersonSyncLogDTO);
|
||||
this.logger.debug("根据设备[{}]图库[{}]人员[{}]查询同步记录日志:[{}]", new Object[] { deviceId, imageData.getGroupId(), dbPerson.getId(),
|
||||
JSON.toJSONString(syncLogs) });
|
||||
if (CollectionUtils.isEmpty(syncLogs)) {
|
||||
this.logger.warn("不存在同步记录日志");
|
||||
continue;
|
||||
}
|
||||
DevicePersonSyncLog dbSyncLog = syncLogs.get(0);
|
||||
QueryGroupPersonDTO queryGroupPersonDTO = new QueryGroupPersonDTO();
|
||||
queryGroupPersonDTO.setImageStoreId(imageData.getGroupId());
|
||||
queryGroupPersonDTO.setPersonId(dbPerson.getId());
|
||||
List<GroupPersonRef> groupPersonRefs = this.groupPersonRefMapper.query(queryGroupPersonDTO);
|
||||
this.logger.debug("根据图库[{}]人员[{}]查询图库人员关系记录:[{}]", new Object[] { imageData.getGroupId(), dbPerson.getId(),
|
||||
JSON.toJSONString(groupPersonRefs) });
|
||||
if (CollectionUtils.isEmpty(groupPersonRefs)) {
|
||||
this.logger.warn("不存在图库人员记录");
|
||||
continue;
|
||||
}
|
||||
GroupPersonRef dbGroupPersonRef = groupPersonRefs.get(0);
|
||||
if (null != imageData.getLastUpdateTime()) {
|
||||
this.logger.debug("设备[{}]上报注册结果存在同步时间[{}]", deviceId, imageData.getLastUpdateTime());
|
||||
if (lockDeviceReport(deviceId, dbGroupPersonRef.getImageStoreId(), dbGroupPersonRef
|
||||
.getPersonId())) {
|
||||
handleSyncTime(imageData, dbGroupPersonRef, dbSyncLog);
|
||||
unclockDeviceReport(deviceId, dbGroupPersonRef.getImageStoreId(), dbGroupPersonRef
|
||||
.getPersonId()); continue;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(1000L);
|
||||
handleSyncTime(imageData, dbGroupPersonRef, dbSyncLog);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("PictureResultEventHandler lock device report sleep error:{}", e.getMessage());
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
this.logger.debug("设备[{}]上报注册结果不存在同步时间", deviceId);
|
||||
handleNoSyncTime(event.getReportTime(), imageData, dbSyncLog);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
this.logger.error("执行报错 {}: {}", e.getClass().getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
private void handleSyncTime(ImageData imageData, GroupPersonRef dbGroupPersonRef, DevicePersonSyncLog dbSyncLog) {
|
||||
if (null == dbGroupPersonRef.getLastUpdateTime()) {
|
||||
this.logger.warn("数据库图库人员关系记录[{}]同步时间为空", dbGroupPersonRef.getId());
|
||||
return;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (imageData.getLastUpdateTime().longValue() >= dbGroupPersonRef.getLastUpdateTime().longValue()) {
|
||||
this.logger.debug("上报注册结果的同步时间[{}]大于等于数据库同步时间[{}]", imageData.getLastUpdateTime(), dbGroupPersonRef
|
||||
.getLastUpdateTime());
|
||||
sb.append("上报注册结果同步时间[" + imageData.getLastUpdateTime() + "]大于等于数据库同步时间[" + dbGroupPersonRef
|
||||
.getLastUpdateTime() + "],并且上报注册结果同步时间[" + imageData.getLastUpdateTime() + "]大于等于同步记录最近同步时间[" + dbSyncLog
|
||||
.getLastReportTime() + "],更新count=0");
|
||||
dbSyncLog.setUpdateInfo(sb.toString());
|
||||
updateStatusAndCount(imageData, dbSyncLog);
|
||||
} else {
|
||||
this.logger.debug("上报注册结果的同步时间[{}]小于数据库同步时间[{}]", imageData.getLastUpdateTime(), dbGroupPersonRef
|
||||
.getLastUpdateTime());
|
||||
sb.append("上报注册结果的同步时间[" + imageData.getLastUpdateTime() + "]小于数据库同步时间[" + dbGroupPersonRef
|
||||
.getLastUpdateTime() + "]");
|
||||
if (dbSyncLog.getCount().intValue() == 0) {
|
||||
sb.append(",count=0,上报注册结果同步时间[" + imageData.getLastUpdateTime() + "]大于等于同步记录最近同步时间[" + dbSyncLog
|
||||
.getLastReportTime() + "],更新count=0");
|
||||
dbSyncLog.setUpdateInfo(sb.toString());
|
||||
updateStatusAndCount(imageData, dbSyncLog);
|
||||
} else if (dbSyncLog.getCount().intValue() == 1) {
|
||||
sb.append(",count=1,更新同步状态:设备未拉取,count--");
|
||||
updateStatusAndCountDec(SyncStatusEnum.NOT_PULL.getValue(), imageData, dbSyncLog, sb.toString(), imageData.getLastUpdateTime());
|
||||
} else if (dbSyncLog.getCount().intValue() > 1) {
|
||||
sb.append(",count>1,更新同步状态:设备已拉取,count--");
|
||||
updateStatusAndCountDec(SyncStatusEnum.PULL.getValue(), imageData, dbSyncLog, sb.toString(), imageData.getLastUpdateTime());
|
||||
}
|
||||
}
|
||||
}
|
||||
private void handleNoSyncTime(Long reportTime, ImageData imageData, DevicePersonSyncLog dbSyncLog) {
|
||||
int syncStatus = imageData.getCode().equals("00000000") ? SyncStatusEnum.SYNC_SUCCESS.getValue() : SyncStatusEnum.SYNC_FAIL.getValue();
|
||||
if (SyncStatusEnum.SYNC_SUCCESS.getValue() == dbSyncLog.getStatus().intValue() || SyncStatusEnum.SYNC_FAIL
|
||||
.getValue() == dbSyncLog.getStatus().intValue()) {
|
||||
this.logger.debug("数据库同步记录[{}]是上报状态[{}]", dbSyncLog.getId(), dbSyncLog.getStatus());
|
||||
if (syncStatus != dbSyncLog.getStatus().intValue()) {
|
||||
this.logger.debug("上报状态与同步记录[{}]不一致,上报状态[{}],同步记录状态[{}]", new Object[] { dbSyncLog.getId(), Integer.valueOf(syncStatus), dbSyncLog
|
||||
.getStatus() });
|
||||
if (null == reportTime || (null != dbSyncLog.getLastUpdateTime() &&
|
||||
Math.abs(reportTime.longValue() - dbSyncLog.getLastUpdateTime().longValue()) <= this.approachTime)) {
|
||||
this.logger.warn("上报时间[{}]与同步记录表上报时间[{}]相近,不更新同步记录[{}]", new Object[] { reportTime, dbSyncLog.getLastReportTime(), dbSyncLog
|
||||
.getId() });
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
this.logger.debug("更新同步记录[{}],同步状态[{}]和count[{}]", new Object[] { dbSyncLog.getId(), Integer.valueOf(syncStatus), Integer.valueOf(dbSyncLog.getCount().intValue() - 1) });
|
||||
updateStatusAndCountDec(syncStatus, imageData, dbSyncLog, "设备上报注册结果不存在同步时间,更新同步记录", reportTime);
|
||||
}
|
||||
private synchronized boolean lockDeviceReport(String deviceId, String imageStoreId, String personId) {
|
||||
String value = deviceId + "_" + imageStoreId + "_" + personId;
|
||||
String key = "lock_device_report_" + value;
|
||||
if (this.redisTemplate.hasKey(key).booleanValue()) {
|
||||
return false;
|
||||
}
|
||||
this.redisTemplate.opsForValue().set(key, value, this.syncLogExpireTime, TimeUnit.SECONDS);
|
||||
return true;
|
||||
}
|
||||
private synchronized boolean unclockDeviceReport(String deviceId, String imageStoreId, String personId) {
|
||||
String value = deviceId + "_" + imageStoreId + "_" + personId;
|
||||
String key = "lock_device_report_" + value;
|
||||
if (this.redisTemplate.hasKey(key).booleanValue()) {
|
||||
this.redisTemplate.delete(key);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
private void updateStatusAndCount(ImageData imageData, DevicePersonSyncLog dbSyncLog) {
|
||||
int syncStatus = imageData.getCode().equals("00000000") ? SyncStatusEnum.SYNC_SUCCESS.getValue() : SyncStatusEnum.SYNC_FAIL.getValue();
|
||||
if (null == dbSyncLog.getLastReportTime() || imageData.getLastUpdateTime().longValue() >= dbSyncLog.getLastReportTime().longValue()) {
|
||||
this.logger.debug("上报注册结果同步时间[{}]大于等于同步记录最近同步时间[{}]", imageData.getLastUpdateTime(), dbSyncLog
|
||||
.getLastReportTime());
|
||||
dbSyncLog.setStatus(Integer.valueOf(syncStatus));
|
||||
dbSyncLog.setCount(Integer.valueOf(0));
|
||||
dbSyncLog.setCode(imageData.getCode());
|
||||
dbSyncLog.setErrorMessage(imageData.getMessage());
|
||||
dbSyncLog.setLastReportTime(imageData.getLastUpdateTime());
|
||||
this.devicePersonSyncLogMapper.updateStatusAndCount(dbSyncLog);
|
||||
}
|
||||
}
|
||||
private void updateStatusAndCountDec(int status, ImageData imageData, DevicePersonSyncLog dbSyncLog, String updateInfo, Long lastReportTime) {
|
||||
dbSyncLog.setStatus(Integer.valueOf(status));
|
||||
dbSyncLog.setCode(imageData.getCode());
|
||||
dbSyncLog.setErrorMessage(imageData.getMessage());
|
||||
dbSyncLog.setUpdateInfo(updateInfo);
|
||||
dbSyncLog.setLastReportTime(lastReportTime);
|
||||
this.devicePersonSyncLogMapper.updateStatusAndCountDec(dbSyncLog);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/PictureResultEventHandler.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+131
-131
@@ -2,6 +2,7 @@ package cn.cloudwalk.service.organization.service;
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.aggregate.group.param.AgFeatureExtractParam;
|
||||
import cn.cloudwalk.client.aggregate.group.param.AgImageUploadParam;
|
||||
import cn.cloudwalk.client.aggregate.group.result.AgFeatureExtractResult;
|
||||
import cn.cloudwalk.client.aggregate.group.result.AgImageUploadResult;
|
||||
import cn.cloudwalk.client.aggregate.group.service.AgImageService;
|
||||
import cn.cloudwalk.client.organization.common.enums.CustEditEnum;
|
||||
@@ -34,139 +35,138 @@ import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.ObjectUtils;
|
||||
|
||||
@Service
|
||||
public class PictureRevisionServiceImpl
|
||||
extends AbstractImagStoreService
|
||||
implements PictureRevisionService {
|
||||
@Resource
|
||||
private PineappleEngineClient pineappleClient;
|
||||
@Resource
|
||||
private ImgStorePersonMapper imgStorePersonMapper;
|
||||
@Resource
|
||||
private FileStorageManager fileStorageManager;
|
||||
@Resource
|
||||
private PersonPropertiesSwitchMapper personPropertiesSwitchMapper;
|
||||
@Resource
|
||||
private CpImageStorePersonService cpImageStorePersonService;
|
||||
@Resource
|
||||
private CpImageStoreToolService cpImageStoreToolService;
|
||||
@Resource
|
||||
private AgImageService agImageService;
|
||||
@Value(value="${imageQualityScore}")
|
||||
private Double imgQualityScore;
|
||||
|
||||
@Async(value="pictureRevisionExecutor")
|
||||
public void personPicRevision(String personId, CloudwalkCallContext cloudwalkContext) throws ServiceException {
|
||||
String img;
|
||||
this.logger.info("防止人员未入数据库即开始修图,休眠30秒");
|
||||
try {
|
||||
TimeUnit.MILLISECONDS.sleep(500L);
|
||||
}
|
||||
catch (InterruptedException e) {
|
||||
this.logger.error("休眠失败,失败原因:{}", (Object)e.getMessage());
|
||||
throw new ServiceException(e.getMessage());
|
||||
}
|
||||
PersonPropertiesSwitch personPropertiesSwitch = this.personPropertiesSwitchMapper.selectByBusinessId(cloudwalkContext.getCompany().getCompanyId());
|
||||
if (ObjectUtils.isEmpty((Object)personPropertiesSwitch) || !personPropertiesSwitch.getSwitchParam().booleanValue() || personPropertiesSwitch.getStatus() != 0) {
|
||||
this.logger.error("租户id为{}的用户修图功能未开启", (Object)cloudwalkContext.getCompany().getCompanyId());
|
||||
throw new ServiceException("修图功能未开启");
|
||||
}
|
||||
ImgStorePerson person = this.imgStorePersonMapper.selectByPrimaryKey(personId);
|
||||
if (ObjectUtils.isEmpty((Object)person)) {
|
||||
this.logger.error("id为{}的人员不存在", (Object)personId);
|
||||
throw new ServiceException("人员不存在");
|
||||
}
|
||||
if (ObjectUtils.isEmpty((Object)person.getComparePicture())) {
|
||||
this.logger.error("id为{}的人员不存在比对照片", (Object)personId);
|
||||
throw new ServiceException("人员不存在比对照片");
|
||||
}
|
||||
try {
|
||||
byte[] bytes = this.fileStorageManager.fileDownload(person.getComparePicture());
|
||||
img = ImageUtil.encodeByte2Base64(bytes);
|
||||
if (ObjectUtils.isEmpty((Object)img)) {
|
||||
this.logger.error("图片下载失败");
|
||||
throw new ServiceException("图片下载失败");
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("下载图片异常:{}", (Object)e.getMessage());
|
||||
throw new ServiceException("80014016", this.getMessage("80014016"));
|
||||
}
|
||||
int customType = personPropertiesSwitch.getShapeParam() != false ? CustEditEnum.FT_MORPH.getCode() : 0;
|
||||
customType = personPropertiesSwitch.getSkinColorParam() != false ? customType + CustEditEnum.FT_SKINALL.getCode() : customType;
|
||||
int n = customType = personPropertiesSwitch.getDefectsParam() != false ? customType + CustEditEnum.FT_BLEMISH.getCode() : customType;
|
||||
if (customType != 0) {
|
||||
RevisionParam revisionParam = RevisionParam.builder().customType(Integer.valueOf(customType)).img(img).build();
|
||||
img = this.pictureRevision(revisionParam);
|
||||
}
|
||||
if (personPropertiesSwitch.getBackgroundParam().booleanValue()) {
|
||||
ChangeBackgroundParam changeBackgroundParam = ChangeBackgroundParam.builder().imgType(String.valueOf(personPropertiesSwitch.getBackgroundObject())).img(img).build();
|
||||
img = this.changeBackground(changeBackgroundParam);
|
||||
}
|
||||
if (!ObjectUtils.isEmpty((Object)personPropertiesSwitch.getSizeParam())) {
|
||||
CropParam cropParam = CropParam.builder().cardType(personPropertiesSwitch.getSizeParam()).img(img).build();
|
||||
img = this.cropImg(cropParam);
|
||||
}
|
||||
String imgPath = this.cpImageStorePersonService.uploadBase64File(img);
|
||||
AgImageUploadParam uploadParam = new AgImageUploadParam();
|
||||
uploadParam.setType("person");
|
||||
uploadParam.setPath(imgPath);
|
||||
CloudwalkResult imageAddResult = this.agImageService.uploadImage(uploadParam, cloudwalkContext);
|
||||
if (!imageAddResult.isSuccess()) {
|
||||
throw new ServiceException(imageAddResult.getCode(), imageAddResult.getMessage());
|
||||
}
|
||||
ImgStorePerson personUpdate = new ImgStorePerson();
|
||||
personUpdate.setId(personId);
|
||||
personUpdate.setImageId(((AgImageUploadResult)imageAddResult.getData()).getId());
|
||||
personUpdate.setComparePicture(person.getComparePicture());
|
||||
personUpdate.setShowPicture(imgPath);
|
||||
AgFeatureExtractParam featureExtractParam = new AgFeatureExtractParam();
|
||||
featureExtractParam.setImageBase64(img);
|
||||
CloudwalkResult result = this.cpImageStoreToolService.extractFeature(featureExtractParam);
|
||||
this.logger.info("scoreResult:{}", (Object)JSONObject.toJSONString((Object)result));
|
||||
Long time = System.currentTimeMillis();
|
||||
personUpdate.setLastUpdateTime(time);
|
||||
this.imgStorePersonMapper.updateByPrimaryKeySelective(personUpdate);
|
||||
}
|
||||
|
||||
public String pictureRevision(RevisionParam param) throws ServiceException {
|
||||
this.logger.info("开始修图,开始时间:{}", (Object)new Date());
|
||||
long beginTime = System.currentTimeMillis();
|
||||
PicRevisionParam picRevisionParam = PicRevisionParam.builder().imgA(param.getImg()).angle(param.getCustomType()).build();
|
||||
PictureRevisionResult pictureRevisionResult = this.pineappleClient.pictureRevision(picRevisionParam);
|
||||
if (ObjectUtils.isEmpty((Object)pictureRevisionResult) || pictureRevisionResult.getResult() != 0 || ObjectUtils.isEmpty((Object)pictureRevisionResult.getImgDest())) {
|
||||
this.logger.error("修图失败,失败原因:{}", (Object)pictureRevisionResult.getInfo());
|
||||
throw new ServiceException(pictureRevisionResult.getResult().toString(), pictureRevisionResult.getInfo());
|
||||
}
|
||||
this.logger.info("修图成功,耗时{}", (Object)(System.currentTimeMillis() - beginTime));
|
||||
return pictureRevisionResult.getImgDest();
|
||||
}
|
||||
|
||||
public String changeBackground(ChangeBackgroundParam param) throws ServiceException {
|
||||
this.logger.info("开始换背景,开始时间:{}", (Object)new Date());
|
||||
long beginTime = System.currentTimeMillis();
|
||||
PicChangeBackgroundParam engineParam = PicChangeBackgroundParam.builder().imgA(param.getImg()).backgroundType(param.getImgType()).build();
|
||||
PictureRevisionResult pictureRevisionResult = this.pineappleClient.pictureChangeBackground(engineParam);
|
||||
if (ObjectUtils.isEmpty((Object)pictureRevisionResult) || pictureRevisionResult.getResult() != 0 || ObjectUtils.isEmpty((Object)pictureRevisionResult.getImgDest())) {
|
||||
this.logger.error("换背景失败,失败原因:{}", (Object)pictureRevisionResult.getInfo());
|
||||
throw new ServiceException(pictureRevisionResult.getResult().toString(), pictureRevisionResult.getInfo());
|
||||
}
|
||||
this.logger.info("换背景成功,耗时{}", (Object)(System.currentTimeMillis() - beginTime));
|
||||
return pictureRevisionResult.getImgDest();
|
||||
}
|
||||
|
||||
public String cropImg(CropParam param) throws ServiceException {
|
||||
this.logger.info("开始裁剪,开始时间:{}", (Object)new Date());
|
||||
long beginTime = System.currentTimeMillis();
|
||||
PicCropParam picRevisionParam = PicCropParam.builder().imgA(param.getImg()).cropType(param.getCardType()).build();
|
||||
PictureRevisionResult pictureRevisionResult = this.pineappleClient.pictureCrop(picRevisionParam);
|
||||
if (ObjectUtils.isEmpty((Object)pictureRevisionResult) || pictureRevisionResult.getResult() != 0 || ObjectUtils.isEmpty((Object)pictureRevisionResult.getImgDest())) {
|
||||
this.logger.error("裁剪失败,失败原因:{}", (Object)pictureRevisionResult.getInfo());
|
||||
throw new ServiceException(pictureRevisionResult.getResult().toString(), pictureRevisionResult.getInfo());
|
||||
}
|
||||
this.logger.info("裁剪成功,耗时{}", (Object)(System.currentTimeMillis() - beginTime));
|
||||
return pictureRevisionResult.getImgDest();
|
||||
}
|
||||
implements PictureRevisionService
|
||||
{
|
||||
@Resource
|
||||
private PineappleEngineClient pineappleClient;
|
||||
@Resource
|
||||
private ImgStorePersonMapper imgStorePersonMapper;
|
||||
@Resource
|
||||
private FileStorageManager fileStorageManager;
|
||||
@Resource
|
||||
private PersonPropertiesSwitchMapper personPropertiesSwitchMapper;
|
||||
@Resource
|
||||
private CpImageStorePersonService cpImageStorePersonService;
|
||||
@Resource
|
||||
private CpImageStoreToolService cpImageStoreToolService;
|
||||
@Resource
|
||||
private AgImageService agImageService;
|
||||
@Value("${imageQualityScore}")
|
||||
private Double imgQualityScore;
|
||||
@Async("pictureRevisionExecutor")
|
||||
public void personPicRevision(String personId, CloudwalkCallContext cloudwalkContext) throws ServiceException {
|
||||
String img;
|
||||
this.logger.info("防止人员未入数据库即开始修图,休眠30秒");
|
||||
try {
|
||||
TimeUnit.MILLISECONDS.sleep(500L);
|
||||
} catch (InterruptedException e) {
|
||||
this.logger.error("休眠失败,失败原因:{}", e.getMessage());
|
||||
throw new ServiceException(e.getMessage());
|
||||
}
|
||||
PersonPropertiesSwitch personPropertiesSwitch = this.personPropertiesSwitchMapper.selectByBusinessId(cloudwalkContext.getCompany().getCompanyId());
|
||||
if (ObjectUtils.isEmpty(personPropertiesSwitch) || !personPropertiesSwitch.getSwitchParam().booleanValue() || personPropertiesSwitch.getStatus().shortValue() != 0) {
|
||||
this.logger.error("租户id为{}的用户修图功能未开启", cloudwalkContext.getCompany().getCompanyId());
|
||||
throw new ServiceException("修图功能未开启");
|
||||
}
|
||||
ImgStorePerson person = this.imgStorePersonMapper.selectByPrimaryKey(personId);
|
||||
if (ObjectUtils.isEmpty(person)) {
|
||||
this.logger.error("id为{}的人员不存在", personId);
|
||||
throw new ServiceException("人员不存在");
|
||||
}
|
||||
if (ObjectUtils.isEmpty(person.getComparePicture())) {
|
||||
this.logger.error("id为{}的人员不存在比对照片", personId);
|
||||
throw new ServiceException("人员不存在比对照片");
|
||||
}
|
||||
try {
|
||||
byte[] bytes = this.fileStorageManager.fileDownload(person.getComparePicture());
|
||||
img = ImageUtil.encodeByte2Base64(bytes);
|
||||
if (ObjectUtils.isEmpty(img)) {
|
||||
this.logger.error("图片下载失败");
|
||||
throw new ServiceException("图片下载失败");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
this.logger.error("下载图片异常:{}", e.getMessage());
|
||||
throw new ServiceException("80014016", getMessage("80014016"));
|
||||
}
|
||||
int customType = personPropertiesSwitch.getShapeParam().booleanValue() ? CustEditEnum.FT_MORPH.getCode() : 0;
|
||||
customType = personPropertiesSwitch.getSkinColorParam().booleanValue() ? (customType + CustEditEnum.FT_SKINALL.getCode()) : customType;
|
||||
customType = personPropertiesSwitch.getDefectsParam().booleanValue() ? (customType + CustEditEnum.FT_BLEMISH.getCode()) : customType;
|
||||
if (customType != 0) {
|
||||
RevisionParam revisionParam = RevisionParam.builder().customType(Integer.valueOf(customType)).img(img).build();
|
||||
img = pictureRevision(revisionParam);
|
||||
}
|
||||
if (personPropertiesSwitch.getBackgroundParam().booleanValue()) {
|
||||
ChangeBackgroundParam changeBackgroundParam = ChangeBackgroundParam.builder().imgType(String.valueOf(personPropertiesSwitch.getBackgroundObject())).img(img).build();
|
||||
img = changeBackground(changeBackgroundParam);
|
||||
}
|
||||
if (!ObjectUtils.isEmpty(personPropertiesSwitch.getSizeParam())) {
|
||||
CropParam cropParam = CropParam.builder().cardType(personPropertiesSwitch.getSizeParam()).img(img).build();
|
||||
img = cropImg(cropParam);
|
||||
}
|
||||
String imgPath = this.cpImageStorePersonService.uploadBase64File(img);
|
||||
AgImageUploadParam uploadParam = new AgImageUploadParam();
|
||||
uploadParam.setType("person");
|
||||
uploadParam.setPath(imgPath);
|
||||
CloudwalkResult<AgImageUploadResult> imageAddResult = this.agImageService.uploadImage(uploadParam, cloudwalkContext);
|
||||
if (!imageAddResult.isSuccess()) {
|
||||
throw new ServiceException(imageAddResult.getCode(), imageAddResult.getMessage());
|
||||
}
|
||||
ImgStorePerson personUpdate = new ImgStorePerson();
|
||||
personUpdate.setId(personId);
|
||||
personUpdate.setImageId(((AgImageUploadResult)imageAddResult.getData()).getId());
|
||||
personUpdate.setComparePicture(person.getComparePicture());
|
||||
personUpdate.setShowPicture(imgPath);
|
||||
AgFeatureExtractParam featureExtractParam = new AgFeatureExtractParam();
|
||||
featureExtractParam.setImageBase64(img);
|
||||
CloudwalkResult<AgFeatureExtractResult> result = this.cpImageStoreToolService.extractFeature(featureExtractParam);
|
||||
this.logger.info("scoreResult:{}", JSONObject.toJSONString(result));
|
||||
Long time = Long.valueOf(System.currentTimeMillis());
|
||||
personUpdate.setLastUpdateTime(time);
|
||||
this.imgStorePersonMapper.updateByPrimaryKeySelective(personUpdate);
|
||||
}
|
||||
public String pictureRevision(RevisionParam param) throws ServiceException {
|
||||
this.logger.info("开始修图,开始时间:{}", new Date());
|
||||
long beginTime = System.currentTimeMillis();
|
||||
PicRevisionParam picRevisionParam = PicRevisionParam.builder().imgA(param.getImg()).angle(param.getCustomType()).build();
|
||||
PictureRevisionResult pictureRevisionResult = this.pineappleClient.pictureRevision(picRevisionParam);
|
||||
if (ObjectUtils.isEmpty(pictureRevisionResult) || pictureRevisionResult.getResult().intValue() != 0 || ObjectUtils.isEmpty(pictureRevisionResult.getImgDest())) {
|
||||
this.logger.error("修图失败,失败原因:{}", pictureRevisionResult.getInfo());
|
||||
throw new ServiceException(pictureRevisionResult.getResult().toString(), pictureRevisionResult.getInfo());
|
||||
}
|
||||
this.logger.info("修图成功,耗时{}", Long.valueOf(System.currentTimeMillis() - beginTime));
|
||||
return pictureRevisionResult.getImgDest();
|
||||
}
|
||||
public String changeBackground(ChangeBackgroundParam param) throws ServiceException {
|
||||
this.logger.info("开始换背景,开始时间:{}", new Date());
|
||||
long beginTime = System.currentTimeMillis();
|
||||
PicChangeBackgroundParam engineParam = PicChangeBackgroundParam.builder().imgA(param.getImg()).backgroundType(param.getImgType()).build();
|
||||
PictureRevisionResult pictureRevisionResult = this.pineappleClient.pictureChangeBackground(engineParam);
|
||||
if (ObjectUtils.isEmpty(pictureRevisionResult) || pictureRevisionResult.getResult().intValue() != 0 || ObjectUtils.isEmpty(pictureRevisionResult.getImgDest())) {
|
||||
this.logger.error("换背景失败,失败原因:{}", pictureRevisionResult.getInfo());
|
||||
throw new ServiceException(pictureRevisionResult.getResult().toString(), pictureRevisionResult.getInfo());
|
||||
}
|
||||
this.logger.info("换背景成功,耗时{}", Long.valueOf(System.currentTimeMillis() - beginTime));
|
||||
return pictureRevisionResult.getImgDest();
|
||||
}
|
||||
public String cropImg(CropParam param) throws ServiceException {
|
||||
this.logger.info("开始裁剪,开始时间:{}", new Date());
|
||||
long beginTime = System.currentTimeMillis();
|
||||
PicCropParam picRevisionParam = PicCropParam.builder().imgA(param.getImg()).cropType(param.getCardType()).build();
|
||||
PictureRevisionResult pictureRevisionResult = this.pineappleClient.pictureCrop(picRevisionParam);
|
||||
if (ObjectUtils.isEmpty(pictureRevisionResult) || pictureRevisionResult.getResult().intValue() != 0 || ObjectUtils.isEmpty(pictureRevisionResult.getImgDest())) {
|
||||
this.logger.error("裁剪失败,失败原因:{}", pictureRevisionResult.getInfo());
|
||||
throw new ServiceException(pictureRevisionResult.getResult().toString(), pictureRevisionResult.getInfo());
|
||||
}
|
||||
this.logger.info("裁剪成功,耗时{}", Long.valueOf(System.currentTimeMillis() - beginTime));
|
||||
return pictureRevisionResult.getImgDest();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/PictureRevisionServiceImpl.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+264
@@ -0,0 +1,264 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.device.mgn.atomic.param.CoreDeviceQueryParam;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.result.AtomicDeviceGetResult;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.service.AtomicDeviceService;
|
||||
import cn.cloudwalk.client.organization.common.enums.DefaultPropertyEnum;
|
||||
import cn.cloudwalk.client.organization.common.enums.RegistryTypeEnum;
|
||||
import cn.cloudwalk.client.organization.common.enums.StatusEnum;
|
||||
import cn.cloudwalk.client.organization.common.enums.UniquePropertyEnum;
|
||||
import cn.cloudwalk.client.organization.service.store.param.AddPersonRegistryParam;
|
||||
import cn.cloudwalk.client.organization.service.store.param.QueryPersonRegistryParam;
|
||||
import cn.cloudwalk.client.organization.service.store.result.DeviceResult;
|
||||
import cn.cloudwalk.client.organization.service.store.result.PersonPropertiesResult;
|
||||
import cn.cloudwalk.client.organization.service.store.result.PersonRegistryResult;
|
||||
import cn.cloudwalk.client.organization.service.store.service.IPersonRegistryHandler;
|
||||
import cn.cloudwalk.cloud.annotation.CloudwalkParamsValidate;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkCallContext;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.cloud.utils.BeanCopyUtils;
|
||||
import cn.cloudwalk.data.organization.entity.ImgStorePersonProperties;
|
||||
import cn.cloudwalk.data.organization.entity.PersonRegistry;
|
||||
import cn.cloudwalk.data.organization.entity.PersonRegistryDevice;
|
||||
import cn.cloudwalk.data.organization.entity.PersonRegistryProperties;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonPropertiesMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.PersonRegistryDeviceMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.PersonRegistryPropertiesMapper;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.google.common.collect.Lists;
|
||||
import java.util.Collection;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Resource;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springside.modules.utils.Collections3;
|
||||
@Service("SelfRegistryHandler")
|
||||
public class SelfRegistryHandler
|
||||
extends AbstractImagStoreService
|
||||
implements IPersonRegistryHandler
|
||||
{
|
||||
@Resource
|
||||
private CommonPersonRegistryService commonPersonRegistryService;
|
||||
@Resource
|
||||
private AtomicDeviceService atomicDeviceService;
|
||||
@Resource
|
||||
private ImgStorePersonPropertiesMapper imgStorePersonPropertiesMapper;
|
||||
@Resource
|
||||
private PersonRegistryPropertiesMapper personRegistryPropertiesMapper;
|
||||
@Resource
|
||||
private PersonRegistryDeviceMapper personRegistryDeviceMapper;
|
||||
@CloudwalkParamsValidate
|
||||
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class}, value = "transactionManager")
|
||||
public CloudwalkResult<Boolean> save(AddPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId = context.getCompany().getCompanyId();
|
||||
param.setBusinessId(businessId);
|
||||
CloudwalkResult<Boolean> result = validateParams(param, context);
|
||||
if (!result.isSuccess()) {
|
||||
return result;
|
||||
}
|
||||
PersonRegistry personRegistry = this.commonPersonRegistryService.getByBusinessAndType(businessId, RegistryTypeEnum.SELF_REGISTRY.getValue());
|
||||
if (null != personRegistry) {
|
||||
param.setId(personRegistry.getId());
|
||||
update(param, context);
|
||||
} else {
|
||||
insert(param, context);
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.valueOf(true));
|
||||
}
|
||||
private CloudwalkResult<Boolean> validateParams(AddPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
if (null == param.getCodeStatus()) {
|
||||
return CloudwalkResult.fail("53014502",
|
||||
getMessage("53014502"));
|
||||
}
|
||||
if (CollectionUtils.isEmpty(param.getPropertyIdList())) {
|
||||
return CloudwalkResult.fail("53014503",
|
||||
getMessage("53014503"));
|
||||
}
|
||||
List<ImgStorePersonProperties> dbPersonProList = this.imgStorePersonPropertiesMapper.selectByIds(param.getBusinessId(), param.getPropertyIdList());
|
||||
if (CollectionUtils.isEmpty(dbPersonProList) || dbPersonProList.size() != param.getPropertyIdList().size()) {
|
||||
this.logger.warn("注册属性不属于人员基本属性,注册属性Id列表:[{}]", JSONObject.toJSONString(param.getPropertyIdList()));
|
||||
return CloudwalkResult.fail("53014508",
|
||||
getMessage("53014508"));
|
||||
}
|
||||
for (DefaultPropertyEnum default_property : DefaultPropertyEnum.values()) {
|
||||
Optional<ImgStorePersonProperties> requiredOptional = dbPersonProList.stream().filter(property -> default_property.getValue().equals(property.getCode())).findFirst();
|
||||
if (!requiredOptional.isPresent()) {
|
||||
this.logger.warn("{}未勾选,注册属性Id列表:[{}]", default_property.getDescription(),
|
||||
JSONObject.toJSONString(param.getPropertyIdList()));
|
||||
return CloudwalkResult.fail("53014511", "注册属性" + default_property
|
||||
.getDescription() + "必须勾选");
|
||||
}
|
||||
}
|
||||
if (Objects.equals(param.getDeviceStatus(), StatusEnum.CLOSE.getValue()) ||
|
||||
Objects.equals(param.getCodeStatus(), StatusEnum.CLOSE.getValue())) {
|
||||
ImgStorePersonProperties queryPersonPro = new ImgStorePersonProperties();
|
||||
queryPersonPro.setBusinessId(param.getBusinessId());
|
||||
queryPersonPro.setStatus(StatusEnum.VALID.getValue());
|
||||
queryPersonPro.setHasRequired(StatusEnum.REQUIRED.getValue());
|
||||
List<ImgStorePersonProperties> requiredPersonProList = this.imgStorePersonPropertiesMapper.select(queryPersonPro);
|
||||
if (!CollectionUtils.isEmpty(requiredPersonProList)) {
|
||||
List<String> requiredPersonProIdList = Collections3.extractToList(requiredPersonProList, "id");
|
||||
dbPersonProList = (List<ImgStorePersonProperties>)dbPersonProList.stream().filter(pro -> requiredPersonProIdList.contains(pro.getId())).collect(Collectors.toList());
|
||||
if (dbPersonProList.size() != requiredPersonProList.size()) {
|
||||
this.logger.warn("设备注册审核和扫码注册审核未同时打开,有未勾选的必填属性,注册属性Id列表:[{}]",
|
||||
JSONObject.toJSONString(param.getPropertyIdList()));
|
||||
return CloudwalkResult.fail("53014511",
|
||||
getMessage("53014511"));
|
||||
}
|
||||
}
|
||||
}
|
||||
this.commonPersonRegistryService.validateOrg(param);
|
||||
this.commonPersonRegistryService.validateLabel(param);
|
||||
this.commonPersonRegistryService.validateDevice(param, context);
|
||||
return CloudwalkResult.success(Boolean.valueOf(true));
|
||||
}
|
||||
private CloudwalkResult<Boolean> insert(AddPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String id = getPrimaryId();
|
||||
this.commonPersonRegistryService.insertPersonRegistry(id, param, context);
|
||||
this.commonPersonRegistryService.batchInsertPersonRegistryProperty(id, param);
|
||||
this.commonPersonRegistryService.batchInsertPersonRegistryDevice(id, param, context, Boolean.valueOf(false));
|
||||
return CloudwalkResult.success(Boolean.valueOf(true));
|
||||
}
|
||||
private CloudwalkResult<Boolean> update(AddPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
this.commonPersonRegistryService.updatePersonRegistry(param, context);
|
||||
this.commonPersonRegistryService.batchUpdatePersonRegistryProperty(param);
|
||||
this.commonPersonRegistryService.batchUpdatePersonRegistryDevice(param, context, Boolean.valueOf(false));
|
||||
return CloudwalkResult.success(Boolean.valueOf(true));
|
||||
}
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<PersonRegistryResult> detail(QueryPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId = param.getBusinessId();
|
||||
if (StringUtils.isBlank(businessId)) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
PersonRegistryResult result = new PersonRegistryResult();
|
||||
ImgStorePersonProperties queryPersonPro = new ImgStorePersonProperties();
|
||||
queryPersonPro.setBusinessId(businessId);
|
||||
queryPersonPro.setStatus(StatusEnum.VALID.getValue());
|
||||
List<ImgStorePersonProperties> personPropertyList = this.imgStorePersonPropertiesMapper.select(queryPersonPro);
|
||||
if (CollectionUtils.isEmpty(personPropertyList)) {
|
||||
this.logger.warn("不存在人员属性");
|
||||
return CloudwalkResult.fail("53014524",
|
||||
getMessage("53014524"));
|
||||
}
|
||||
List<PersonPropertiesResult> proResultList = BeanCopyUtils.copy(personPropertyList, PersonPropertiesResult.class);
|
||||
proResultList.forEach(propertyResult -> {
|
||||
if (DefaultPropertyEnum.hasProperty(propertyResult.getCode())) {
|
||||
propertyResult.setHasChecked(StatusEnum.CHECKED.getValue());
|
||||
propertyResult.setHasDisabled(StatusEnum.DISABLED.getValue());
|
||||
}
|
||||
});
|
||||
proResultList = (List<PersonPropertiesResult>)proResultList.stream().sorted(Comparator.comparing(PersonPropertiesResult::getOrderNum)).collect(Collectors.toList());
|
||||
result.setPropertyList(proResultList);
|
||||
PersonRegistry dbPersonRegistry = this.commonPersonRegistryService.getByBusinessAndType(businessId, RegistryTypeEnum.SELF_REGISTRY.getValue());
|
||||
if (null != dbPersonRegistry) {
|
||||
result = (PersonRegistryResult)BeanCopyUtils.copyProperties(dbPersonRegistry, PersonRegistryResult.class);
|
||||
result.setPropertyList(proResultList);
|
||||
this.commonPersonRegistryService.setOrg(dbPersonRegistry, result);
|
||||
this.commonPersonRegistryService.setLabel(dbPersonRegistry, result);
|
||||
List<PersonRegistryDevice> dbPersonRegistryDeviceList = this.personRegistryDeviceMapper.select(dbPersonRegistry.getId(), null);
|
||||
if (!CollectionUtils.isEmpty(dbPersonRegistryDeviceList)) {
|
||||
CoreDeviceQueryParam coreDeviceQueryParam = new CoreDeviceQueryParam();
|
||||
coreDeviceQueryParam.setBusinessId(businessId);
|
||||
coreDeviceQueryParam
|
||||
.setDeviceCodes(Collections3.extractToList(dbPersonRegistryDeviceList, "deviceCode"));
|
||||
CloudwalkResult<List<AtomicDeviceGetResult>> deviceGetResult = this.atomicDeviceService.list(coreDeviceQueryParam, context);
|
||||
if (!CollectionUtils.isEmpty((Collection)deviceGetResult.getData())) {
|
||||
List<DeviceResult> deviceResultList = Lists.newArrayListWithCapacity(((List)deviceGetResult.getData()).size());
|
||||
((List)deviceGetResult.getData()).forEach(device -> {
|
||||
DeviceResult deviceResult = new DeviceResult();
|
||||
deviceResult.setDeviceCode(device.getDeviceCode());
|
||||
deviceResult.setDeviceName(device.getDeviceName());
|
||||
deviceResultList.add(deviceResult);
|
||||
});
|
||||
result.setDeviceList(deviceResultList);
|
||||
}
|
||||
}
|
||||
List<PersonRegistryProperties> dbPersonRegistryProList = this.personRegistryPropertiesMapper.select(dbPersonRegistry.getId(), null);
|
||||
List<String> personPropertyIdList = Collections3.extractToList(dbPersonRegistryProList, "personPropertyId");
|
||||
result.getPropertyList().forEach(propertyResult -> {
|
||||
if (personPropertyIdList.contains(propertyResult.getId())) {
|
||||
propertyResult.setHasChecked(StatusEnum.CHECKED.getValue());
|
||||
}
|
||||
});
|
||||
}
|
||||
return CloudwalkResult.success(result);
|
||||
}
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<List<PersonPropertiesResult>> getRegistryPropertyList(QueryPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId = param.getBusinessId();
|
||||
if (StringUtils.isBlank(businessId)) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
PersonRegistry dbPersonRegistry = (PersonRegistry)this.commonPersonRegistryService.getResultByBusinessAndType(businessId, RegistryTypeEnum.SELF_REGISTRY.getValue()).getData();
|
||||
this.commonPersonRegistryService.validateDevice(param, dbPersonRegistry);
|
||||
return CloudwalkResult.success(getPersonPropertyList(dbPersonRegistry, true));
|
||||
}
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<List<PersonPropertiesResult>> getAuditPropertyList(QueryPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId = param.getBusinessId();
|
||||
if (StringUtils.isBlank(businessId)) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
PersonRegistry dbPersonRegistry = (PersonRegistry)this.commonPersonRegistryService.getResultByBusinessAndType(businessId, RegistryTypeEnum.SELF_REGISTRY.getValue()).getData();
|
||||
return CloudwalkResult.success(getPersonPropertyList(dbPersonRegistry, false));
|
||||
}
|
||||
private List<PersonPropertiesResult> getPersonPropertyList(PersonRegistry personRegistry, boolean isChecked) {
|
||||
List<PersonRegistryProperties> dbPersonRegistryProList = this.personRegistryPropertiesMapper.select(personRegistry.getId(), null);
|
||||
List<String> personProIdList = Collections3.extractToList(dbPersonRegistryProList, "personPropertyId");
|
||||
ImgStorePersonProperties queryPersonPro = new ImgStorePersonProperties();
|
||||
queryPersonPro.setBusinessId(personRegistry.getBusinessId());
|
||||
queryPersonPro.setStatus(StatusEnum.VALID.getValue());
|
||||
List<ImgStorePersonProperties> dbPersonProList = this.imgStorePersonPropertiesMapper.select(queryPersonPro);
|
||||
List<PersonPropertiesResult> proResultList = BeanCopyUtils.copy(dbPersonProList, PersonPropertiesResult.class);
|
||||
List<PersonPropertiesResult> defaultProList = BeanCopyUtils.copy(dbPersonProList, PersonPropertiesResult.class);
|
||||
proResultList = (List<PersonPropertiesResult>)proResultList.stream().filter(proResult -> (personProIdList.contains(proResult.getId()) == isChecked)).collect(Collectors.toList());
|
||||
defaultProList = (List<PersonPropertiesResult>)defaultProList.stream().filter(proResult -> DefaultPropertyEnum.hasProperty(proResult.getCode())).collect(Collectors.toList());
|
||||
if (isChecked) {
|
||||
proResultList.removeAll(defaultProList);
|
||||
proResultList.addAll(defaultProList);
|
||||
proResultList.forEach(proResult -> {
|
||||
proResult.setHasChecked(StatusEnum.CHECKED.getValue());
|
||||
if (DefaultPropertyEnum.hasProperty(proResult.getCode())) {
|
||||
proResult.setHasDisabled(StatusEnum.DISABLED.getValue());
|
||||
}
|
||||
});
|
||||
} else {
|
||||
proResultList.removeAll(defaultProList);
|
||||
}
|
||||
proResultList = (List<PersonPropertiesResult>)proResultList.stream().sorted(Comparator.comparing(PersonPropertiesResult::getOrderNum)).collect(Collectors.toList());
|
||||
return proResultList;
|
||||
}
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<PersonPropertiesResult> getUniqueRegistryProperty(QueryPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
String businessId = param.getBusinessId();
|
||||
if (StringUtils.isBlank(businessId)) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
PersonRegistry dbPersonRegistry = (PersonRegistry)this.commonPersonRegistryService.getResultByBusinessAndType(businessId, RegistryTypeEnum.SELF_REGISTRY.getValue()).getData();
|
||||
List<PersonPropertiesResult> propertyList = getPersonPropertyList(dbPersonRegistry, true);
|
||||
AtomicReference<PersonPropertiesResult> result = new AtomicReference<>();
|
||||
propertyList.stream().filter(property -> UniquePropertyEnum.hasProperty(property.getCode()))
|
||||
.findFirst().ifPresent(personPropertiesResult -> result.set(personPropertiesResult));
|
||||
return CloudwalkResult.success(result.get());
|
||||
}
|
||||
public CloudwalkResult<PersonPropertiesResult> getBindProperty(QueryPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/SelfRegistryHandler.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
+103
-104
@@ -1,5 +1,4 @@
|
||||
package cn.cloudwalk.service.organization.service.corp;
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.common.enums.OrganizationTypeCodeEnum;
|
||||
import cn.cloudwalk.client.organization.param.corp.EnterpriseInfoQueryParam;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
@@ -28,109 +27,109 @@ import java.util.stream.Collectors;
|
||||
import javax.annotation.Resource;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
public class UnitInfoInitServiceImpl {
|
||||
@Resource
|
||||
private EnterpriseFeignClient enterpriseFeignClient;
|
||||
@Resource
|
||||
private OrganizationUnitTypeServiceImpl organizationUnitTypeService;
|
||||
@Resource
|
||||
private ImgStoreOrganizationMapper organizationMapper;
|
||||
@Resource
|
||||
private OrganizationExtendMapper organizationExtendMapper;
|
||||
@Resource
|
||||
private ImgStoreOrganizationTypeMapper orgTypeMapper;
|
||||
@Resource
|
||||
private ImgStoreOrganizationTypePropertiesMapper orgTypePropertiesMapper;
|
||||
private static final String CORP_TYPE_COMMON = "1";
|
||||
private static final String CORP_TYPE_ADMIN = "0";
|
||||
|
||||
@Transactional(rollbackFor={Exception.class})
|
||||
public void init(EnterpriseChangeEvent enterprise) throws ServiceException {
|
||||
String businessId = enterprise.getBusinessId();
|
||||
String businessName = enterprise.getBusinessName();
|
||||
EnterpriseBasicParam param = new EnterpriseBasicParam();
|
||||
param.setId(businessId);
|
||||
CloudwalkResult<EnterpriseDetailResult> detail = this.enterpriseFeignClient.detail(param);
|
||||
for (int waitTimes = 10; !"00000000".equals(detail.getCode()) && waitTimes > 0; --waitTimes) {
|
||||
try {
|
||||
TimeUnit.SECONDS.sleep(2L);
|
||||
}
|
||||
catch (InterruptedException interruptedException) {
|
||||
// empty catch block
|
||||
}
|
||||
detail = this.enterpriseFeignClient.detail(param);
|
||||
}
|
||||
EnterpriseDetailResult corpDetail = (EnterpriseDetailResult)detail.getData();
|
||||
boolean isSuperCorp = Objects.equals(CORP_TYPE_ADMIN, corpDetail.getExt3());
|
||||
if (isSuperCorp) {
|
||||
this.initOrganizationType(businessId, businessName);
|
||||
} else {
|
||||
EnterpriseInfoQueryParam queryParam = new EnterpriseInfoQueryParam();
|
||||
queryParam.setCorpType(CORP_TYPE_ADMIN);
|
||||
CloudwalkResult<List<EnterpriseInfoResult>> queryResult = this.enterpriseFeignClient.query(queryParam);
|
||||
List list = ((List)queryResult.getData()).stream().filter(it -> CORP_TYPE_ADMIN.equals(it.getExt3())).collect(Collectors.toList());
|
||||
for (EnterpriseInfoResult superEnterprise : list) {
|
||||
this.initOrganizationInSuperCorp(superEnterprise, corpDetail);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void initOrganizationInSuperCorp(EnterpriseInfoResult superEnterprise, EnterpriseDetailResult corpDetail) throws ServiceException {
|
||||
String superEnterpriseId = superEnterprise.getId();
|
||||
OrganizationTypeQueryDto typeQueryDto = new OrganizationTypeQueryDto();
|
||||
typeQueryDto.setBusinessId(superEnterpriseId);
|
||||
typeQueryDto.setStatus(Integer.valueOf(0));
|
||||
typeQueryDto.setCode(OrganizationTypeCodeEnum.UNIT.getCode());
|
||||
List organizationTypeList = this.orgTypeMapper.selectByCondition(typeQueryDto);
|
||||
if (organizationTypeList.isEmpty()) {
|
||||
this.initOrganizationType(superEnterprise.getId(), superEnterprise.getName());
|
||||
}
|
||||
organizationTypeList = this.orgTypeMapper.selectByCondition(typeQueryDto);
|
||||
OrganizationType type = (OrganizationType)organizationTypeList.get(0);
|
||||
List parentNode = Optional.ofNullable(this.organizationMapper.getParentNode(superEnterpriseId)).orElse(Collections.emptyList());
|
||||
if (parentNode.size() != 1) {
|
||||
this.initOrganizationType(superEnterprise.getId(), superEnterprise.getName());
|
||||
}
|
||||
String rootId = ((Organization)parentNode.get(0)).getId();
|
||||
Organization organization = new Organization();
|
||||
organization.setId(corpDetail.getId());
|
||||
organization.setBusinessId(superEnterpriseId);
|
||||
organization.setTypeId(type.getId());
|
||||
organization.setName(corpDetail.getCorpName());
|
||||
organization.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
organization.setParentId(rootId);
|
||||
organization.setIsValid(Integer.valueOf(1));
|
||||
organization.setIsDel(Short.valueOf((short)0));
|
||||
this.organizationMapper.insertSelective(organization);
|
||||
OrganizationExtendDTO extendDTO = new OrganizationExtendDTO();
|
||||
extendDTO.setId(CloudwalkDateUtils.getUUID());
|
||||
extendDTO.setOrganizationId(corpDetail.getId());
|
||||
extendDTO.setBusinessId(superEnterpriseId);
|
||||
extendDTO.setCarportNum(Integer.valueOf(0));
|
||||
extendDTO.setEmployeeCarNumber(Integer.valueOf(0));
|
||||
extendDTO.setEmployeeNumber(Integer.valueOf(0));
|
||||
extendDTO.setOrgCarNumber(Integer.valueOf(0));
|
||||
extendDTO.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.organizationExtendMapper.insertSelective(extendDTO);
|
||||
}
|
||||
|
||||
public void appendOrganization(String businessId) {
|
||||
}
|
||||
|
||||
public void updateOrganization(String businessId, EnterpriseChangeEvent event) {
|
||||
Organization organization = new Organization();
|
||||
organization.setName(event.getBusinessName());
|
||||
organization.setId(event.getBusinessId());
|
||||
this.organizationMapper.updateByPrimaryKey(organization);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor={Exception.class})
|
||||
public void initOrganizationType(String superEnterpriseId, String businessName) throws ServiceException {
|
||||
String rootTypeId = this.organizationUnitTypeService.initRootOrg(superEnterpriseId, businessName);
|
||||
this.organizationUnitTypeService.initParkOrg(superEnterpriseId, businessName, rootTypeId);
|
||||
this.organizationUnitTypeService.defaultInitOrgType(superEnterpriseId, true);
|
||||
}
|
||||
public class UnitInfoInitServiceImpl
|
||||
{
|
||||
@Resource
|
||||
private EnterpriseFeignClient enterpriseFeignClient;
|
||||
@Resource
|
||||
private OrganizationUnitTypeServiceImpl organizationUnitTypeService;
|
||||
@Resource
|
||||
private ImgStoreOrganizationMapper organizationMapper;
|
||||
@Resource
|
||||
private OrganizationExtendMapper organizationExtendMapper;
|
||||
@Resource
|
||||
private ImgStoreOrganizationTypeMapper orgTypeMapper;
|
||||
@Resource
|
||||
private ImgStoreOrganizationTypePropertiesMapper orgTypePropertiesMapper;
|
||||
private static final String CORP_TYPE_COMMON = "1";
|
||||
private static final String CORP_TYPE_ADMIN = "0";
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
public void init(EnterpriseChangeEvent enterprise) throws ServiceException {
|
||||
String businessId = enterprise.getBusinessId();
|
||||
String businessName = enterprise.getBusinessName();
|
||||
EnterpriseBasicParam param = new EnterpriseBasicParam();
|
||||
param.setId(businessId);
|
||||
CloudwalkResult<EnterpriseDetailResult> detail = this.enterpriseFeignClient.detail(param);
|
||||
int waitTimes = 10;
|
||||
while (!"00000000".equals(detail.getCode()) && waitTimes > 0) {
|
||||
try {
|
||||
TimeUnit.SECONDS.sleep(2L);
|
||||
} catch (InterruptedException interruptedException) {}
|
||||
detail = this.enterpriseFeignClient.detail(param);
|
||||
waitTimes--;
|
||||
}
|
||||
EnterpriseDetailResult corpDetail = (EnterpriseDetailResult)detail.getData();
|
||||
boolean isSuperCorp = Objects.equals("0", corpDetail.getExt3());
|
||||
if (isSuperCorp) {
|
||||
initOrganizationType(businessId, businessName);
|
||||
} else {
|
||||
EnterpriseInfoQueryParam queryParam = new EnterpriseInfoQueryParam();
|
||||
queryParam.setCorpType("0");
|
||||
CloudwalkResult<List<EnterpriseInfoResult>> queryResult = this.enterpriseFeignClient.query(queryParam);
|
||||
List<EnterpriseInfoResult> list = (List<EnterpriseInfoResult>)((List)queryResult.getData()).stream().filter(it -> "0".equals(it.getExt3())).collect(Collectors.toList());
|
||||
for (EnterpriseInfoResult superEnterprise : list) {
|
||||
initOrganizationInSuperCorp(superEnterprise, corpDetail);
|
||||
}
|
||||
}
|
||||
}
|
||||
public void initOrganizationInSuperCorp(EnterpriseInfoResult superEnterprise, EnterpriseDetailResult corpDetail) throws ServiceException {
|
||||
String superEnterpriseId = superEnterprise.getId();
|
||||
OrganizationTypeQueryDto typeQueryDto = new OrganizationTypeQueryDto();
|
||||
typeQueryDto.setBusinessId(superEnterpriseId);
|
||||
typeQueryDto.setStatus(Integer.valueOf(0));
|
||||
typeQueryDto.setCode(OrganizationTypeCodeEnum.UNIT.getCode());
|
||||
List<OrganizationType> organizationTypeList = this.orgTypeMapper.selectByCondition(typeQueryDto);
|
||||
if (organizationTypeList.isEmpty())
|
||||
{
|
||||
initOrganizationType(superEnterprise.getId(), superEnterprise.getName());
|
||||
}
|
||||
organizationTypeList = this.orgTypeMapper.selectByCondition(typeQueryDto);
|
||||
OrganizationType type = organizationTypeList.get(0);
|
||||
List<Organization> parentNode = Optional.<List<Organization>>ofNullable(this.organizationMapper.getParentNode(superEnterpriseId)).orElse(Collections.emptyList());
|
||||
if (parentNode.size() != 1)
|
||||
{
|
||||
initOrganizationType(superEnterprise.getId(), superEnterprise.getName());
|
||||
}
|
||||
String rootId = ((Organization)parentNode.get(0)).getId();
|
||||
Organization organization = new Organization();
|
||||
organization.setId(corpDetail.getId());
|
||||
organization.setBusinessId(superEnterpriseId);
|
||||
organization.setTypeId(type.getId());
|
||||
organization.setName(corpDetail.getCorpName());
|
||||
organization.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
organization.setParentId(rootId);
|
||||
organization.setIsValid(Integer.valueOf(1));
|
||||
organization.setIsDel(Short.valueOf((short)0));
|
||||
this.organizationMapper.insertSelective(organization);
|
||||
OrganizationExtendDTO extendDTO = new OrganizationExtendDTO();
|
||||
extendDTO.setId(CloudwalkDateUtils.getUUID());
|
||||
extendDTO.setOrganizationId(corpDetail.getId());
|
||||
extendDTO.setBusinessId(superEnterpriseId);
|
||||
extendDTO.setCarportNum(Integer.valueOf(0));
|
||||
extendDTO.setEmployeeCarNumber(Integer.valueOf(0));
|
||||
extendDTO.setEmployeeNumber(Integer.valueOf(0));
|
||||
extendDTO.setOrgCarNumber(Integer.valueOf(0));
|
||||
extendDTO.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.organizationExtendMapper.insertSelective(extendDTO);
|
||||
}
|
||||
public void appendOrganization(String businessId) {}
|
||||
public void updateOrganization(String businessId, EnterpriseChangeEvent event) {
|
||||
Organization organization = new Organization();
|
||||
organization.setName(event.getBusinessName());
|
||||
organization.setId(event.getBusinessId());
|
||||
this.organizationMapper.updateByPrimaryKey(organization);
|
||||
}
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
public void initOrganizationType(String superEnterpriseId, String businessName) throws ServiceException {
|
||||
String rootTypeId = this.organizationUnitTypeService.initRootOrg(superEnterpriseId, businessName);
|
||||
this.organizationUnitTypeService.initParkOrg(superEnterpriseId, businessName, rootTypeId);
|
||||
this.organizationUnitTypeService.defaultInitOrgType(superEnterpriseId, true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Location: /media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/部署包/ninca_common_component_organization_01-ninca_common_component_organization/ninca-common-component-organization-V2.9.2_20210730/BOOT-INF/lib/cwos-component-organization-service-v2.9.2_xinghewan.jar!/cn/cloudwalk/service/organization/service/corp/UnitInfoInitServiceImpl.class
|
||||
* Java compiler version: 8 (52.0)
|
||||
* JD-Core Version: 1.1.3
|
||||
*/
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
-6
@@ -1,6 +0,0 @@
|
||||
cn/cloudwalk/service/organization/service/feign/ElevatorFeignClient.class
|
||||
cn/cloudwalk/service/organization/common/FlushList.class
|
||||
cn/cloudwalk/service/organization/service/feign/CrkAccessFeignClient.class
|
||||
cn/cloudwalk/service/organization/service/OrganizationServiceImpl.class
|
||||
cn/cloudwalk/service/organization/common/AbstractImagStoreService.class
|
||||
cn/cloudwalk/service/organization/common/FlushHandler.class
|
||||
|
||||
+7
@@ -90,9 +90,13 @@
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/service/feign/ImageStoreSyncClient.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/service/common/AbstractFallback.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/service/feign/VehicleFeignClient.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/service/AreaTypeServiceImpl.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/listener/ComponentOrganizationEventListener.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/service/CpImageStoreServiceImpl.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/service/PortalUserServiceImpl.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/service/feign/ElevatorAppFeignClientFallback.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/service/ImgPersonBatchServiceImpl.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/service/SelfRegistryHandler.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/service/feign/ElevatorAppFeignClient.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/common/ByteUtil.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/export/CommonRecordExcelCreater.java
|
||||
@@ -107,9 +111,12 @@
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/common/FolderUtil.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/service/feign/ElevatorFeignClient.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/common/ImageEditUtils.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/service/ImgPersonBatchDetailServiceImpl.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/service/OrganizationTypeServiceImpl.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/export/CommonAppExportFileHandler.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/service/feign/DeviceAppFeignClient.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/schedule/BatchImportContext.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/service/CpDeviceImagePersonServiceImpl.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/config/ChannelFileReader.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/common/PathUtils.java
|
||||
/media/zebra/9e8fa357-7db6-4d70-88ed-d5de5a059a663/星河湾星中星/源码/maven-ninca-common-component-organization/cwos-component-organization-service/src/main/java/cn/cloudwalk/service/organization/task/DeviceNotificationTask.java
|
||||
|
||||
Reference in New Issue
Block a user