mirror of
https://github.com/hpd840321/starRiverProperty.git
synced 2026-06-18 12:50:30 +08:00
Initial commit: reorganized source tree
- backend/: 13 Maven modules (cw-elevator-application, cloudwalk-cloud, intelligent-cwoscomponent, ninca-crk, etc.) - frontend/: 4 Vue projects (elevator-front, cwos-portal, alarm-front, front_acs) + decompiled + scripts - scripts/: build, test-env, tools (Docker Compose, service templates, API parity) - docs/: AGENTS.md, superpowers specs, architecture docs - .gitignore: standard Java/Maven exclusions Moved from legacy maven-*/ root layout to backend/ organized structure.
This commit is contained in:
+90
@@ -0,0 +1,90 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.cloud.context.CloudwalkCallContext;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkCallContextBuilder;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkSessionContextHolder;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkSessionObject;
|
||||
import cn.hutool.core.date.DateTime;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
|
||||
public abstract class AbstractImagStoreService {
|
||||
private static final String DATE_FORMAT = "yyyyMMdd";
|
||||
private static final int GENGRAL_CODE_LENGTH = 6;
|
||||
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
@Autowired private MessageSource messageSource;
|
||||
@Autowired private CloudwalkSessionContextHolder cloudwalkSessionContextHolder;
|
||||
|
||||
public String getMessage(String code) {
|
||||
return this.messageSource.getMessage(code, null, "", LocaleContextHolder.getLocale());
|
||||
}
|
||||
|
||||
public String getPrimaryId() {
|
||||
return UUID.randomUUID().toString().replaceAll("-", "");
|
||||
}
|
||||
|
||||
public String createGeneralCode() {
|
||||
return new DateTime().toString(DATE_FORMAT) + ToolUtil.randomNum(5);
|
||||
}
|
||||
|
||||
public CloudwalkCallContext getCloudwalkContext() {
|
||||
CloudwalkSessionObject session = this.cloudwalkSessionContextHolder.getSession();
|
||||
if (session == null) {
|
||||
session =
|
||||
new CloudwalkSessionObject(new String[] {"system", "cloudwalk", "system", "default"});
|
||||
this.cloudwalkSessionContextHolder.putSession(session);
|
||||
}
|
||||
session.getCompany().setCompanyName("default");
|
||||
return CloudwalkCallContextBuilder.buildContext(this.cloudwalkSessionContextHolder);
|
||||
}
|
||||
|
||||
public boolean storage(String path, byte[] content) {
|
||||
boolean isSuccess = true;
|
||||
File f = new File(path);
|
||||
f.getParentFile().mkdirs();
|
||||
ByteBuffer buffer = ByteBuffer.wrap(content);
|
||||
try (FileOutputStream out = new FileOutputStream(f)) {
|
||||
FileChannel channel = out.getChannel();
|
||||
channel.write(buffer);
|
||||
} catch (IOException e) {
|
||||
isSuccess = false;
|
||||
}
|
||||
return isSuccess;
|
||||
}
|
||||
|
||||
public short checkGroupPersonStatus(Long expiryBeginDate, Long expiryEndDate) {
|
||||
long time = System.currentTimeMillis();
|
||||
if (expiryBeginDate != null
|
||||
&& expiryEndDate != null
|
||||
&& time >= expiryBeginDate.longValue()
|
||||
&& time <= expiryEndDate.longValue()) {
|
||||
return 0;
|
||||
}
|
||||
if (expiryBeginDate != null && time < expiryBeginDate.longValue()) {
|
||||
return 1;
|
||||
}
|
||||
if (expiryEndDate != null && time > expiryEndDate.longValue()) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
|
||||
Set<Object> seen = ConcurrentHashMap.newKeySet();
|
||||
return t -> seen.add(keyExtractor.apply(t));
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
|
||||
// 业务服务
|
||||
import javax.xml.bind.DatatypeConverter;
|
||||
|
||||
public class Base64Utils {
|
||||
private Base64Utils() {}
|
||||
|
||||
public static byte[] getBytes(String base64) {
|
||||
return DatatypeConverter.parseBase64Binary((String) base64);
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
|
||||
// 业务服务
|
||||
public class ByteUtil {
|
||||
private ByteUtil() {}
|
||||
|
||||
public static String bytesToHexString(byte[] src) {
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
if (src == null || src.length <= 0) {
|
||||
return null;
|
||||
}
|
||||
for (int i = 0; i < src.length; ++i) {
|
||||
int v = src[i] & 0xFF;
|
||||
String hv = Integer.toHexString(v);
|
||||
if (hv.length() < 2) {
|
||||
stringBuilder.append(0);
|
||||
}
|
||||
stringBuilder.append(hv);
|
||||
}
|
||||
return stringBuilder.toString();
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
|
||||
// 业务服务
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "cloudwalk.common-app.download")
|
||||
public class CommonDownloadDataConfig {
|
||||
private String downDir;
|
||||
private int excelMaxRows;
|
||||
private int exportAllCount;
|
||||
private String compressionType;
|
||||
private Boolean hasContainImage;
|
||||
|
||||
public String getDownDir() {
|
||||
return this.downDir;
|
||||
}
|
||||
|
||||
public int getExcelMaxRows() {
|
||||
return this.excelMaxRows;
|
||||
}
|
||||
|
||||
public int getExportAllCount() {
|
||||
return this.exportAllCount;
|
||||
}
|
||||
|
||||
public String getCompressionType() {
|
||||
return this.compressionType;
|
||||
}
|
||||
|
||||
public Boolean getHasContainImage() {
|
||||
return this.hasContainImage;
|
||||
}
|
||||
|
||||
public void setDownDir(String downDir) {
|
||||
this.downDir = downDir;
|
||||
}
|
||||
|
||||
public void setExcelMaxRows(int excelMaxRows) {
|
||||
this.excelMaxRows = excelMaxRows;
|
||||
}
|
||||
|
||||
public void setExportAllCount(int exportAllCount) {
|
||||
this.exportAllCount = exportAllCount;
|
||||
}
|
||||
|
||||
public void setCompressionType(String compressionType) {
|
||||
this.compressionType = compressionType;
|
||||
}
|
||||
|
||||
public void setHasContainImage(Boolean hasContainImage) {
|
||||
this.hasContainImage = hasContainImage;
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
|
||||
// 业务服务
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "cloudwalk.component-organization.kafka")
|
||||
public class ComponentInnerKafkaConfig {
|
||||
private String serviceCode;
|
||||
private Properties producer;
|
||||
private Properties consumer;
|
||||
|
||||
public String getServiceCode() {
|
||||
return this.serviceCode;
|
||||
}
|
||||
|
||||
public void setServiceCode(String serviceCode) {
|
||||
this.serviceCode = serviceCode;
|
||||
}
|
||||
|
||||
public Properties getProducer() {
|
||||
return this.producer;
|
||||
}
|
||||
|
||||
public void setProducer(Properties producer) {
|
||||
this.producer = producer;
|
||||
}
|
||||
|
||||
public Properties getConsumer() {
|
||||
return this.consumer;
|
||||
}
|
||||
|
||||
public void setConsumer(Properties consumer) {
|
||||
this.consumer = consumer;
|
||||
}
|
||||
|
||||
public static class Properties {
|
||||
private String bootstrapServers;
|
||||
private String groupId;
|
||||
|
||||
public String getBootstrapServers() {
|
||||
return this.bootstrapServers;
|
||||
}
|
||||
|
||||
public void setBootstrapServers(String bootstrapServers) {
|
||||
this.bootstrapServers = bootstrapServers;
|
||||
}
|
||||
|
||||
public String getGroupId() {
|
||||
return this.groupId;
|
||||
}
|
||||
|
||||
public void setGroupId(String groupId) {
|
||||
this.groupId = groupId;
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
|
||||
// 业务服务
|
||||
public class CwosConst {
|
||||
public static final String RESULT_CODE_SUCCESS = "00000000";
|
||||
public static final String RESULT_CODE_FAIL = "99999999";
|
||||
public static final String RESULT_CODE_EMPTY_REPO = "20030000";
|
||||
public static final String RESULT_CODE_FACE_NOT_EXIST = "20010006";
|
||||
public static final String FEATUREATTR = "{}";
|
||||
public static final String RESULT_CODE_REPO_EXISTS = "20010000";
|
||||
public static final String RESULT_CODE_REPO_NOT_EXISTS = "20010004";
|
||||
public static final String ALGO_VERSION =
|
||||
"recog_model=./models_cpu/recoModels_180814_rt_pa_101/CWR_Config3.0_1_n.xml";
|
||||
|
||||
private CwosConst() {}
|
||||
}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
|
||||
// 业务服务
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.DateUtil;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
|
||||
public final class ExcelUtils {
|
||||
public static final String NA_EXCEL = "#N/A!";
|
||||
protected static final Logger LOGGER = Logger.getLogger(ExcelUtils.class);
|
||||
private static final String YYYY_MM_DD = "yyyy-MM-dd";
|
||||
|
||||
private ExcelUtils() {}
|
||||
|
||||
public static void readFromExcel(
|
||||
List<List<String>> result,
|
||||
InputStream inputStream,
|
||||
Integer sheetNumber,
|
||||
Integer skipRowIndex,
|
||||
Integer skipColIndex,
|
||||
boolean format) {
|
||||
int beginRowIndex = ExcelUtils.getBeginIndex(skipRowIndex);
|
||||
int beginColIndex = ExcelUtils.getBeginIndex(skipColIndex);
|
||||
try (HSSFWorkbook workbook = new HSSFWorkbook(inputStream); ) {
|
||||
Sheet sheet = workbook.getSheetAt(sheetNumber.intValue());
|
||||
int rowSize = ExcelUtils.getLastRowIndex(sheet);
|
||||
for (int r = beginRowIndex; r < rowSize; ++r) {
|
||||
ArrayList<String> list = new ArrayList<String>();
|
||||
Row row = sheet.getRow(r);
|
||||
if (row == null) {
|
||||
result.add(list);
|
||||
continue;
|
||||
}
|
||||
String cellStr = "";
|
||||
for (int c = beginColIndex; c < row.getLastCellNum(); ++c) {
|
||||
Cell cell = row.getCell(c);
|
||||
cellStr =
|
||||
cell == null
|
||||
? NA_EXCEL
|
||||
: (format
|
||||
? ExcelUtils.getCellFormatValue(cell)
|
||||
: ExcelUtils.getCellStringValue(cell));
|
||||
list.add(cellStr);
|
||||
}
|
||||
result.add(list);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOGGER.error((Object) "", e);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Exception decompiling
|
||||
*/
|
||||
public static int readFromExcelDataSize(
|
||||
File excelFile, Integer sheetNumber, Integer skipRowIndex) {
|
||||
/*
|
||||
* 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 int getBeginIndex(Integer skipIndex) {
|
||||
int beginIndex = 0;
|
||||
if (skipIndex != null) {
|
||||
beginIndex = skipIndex;
|
||||
}
|
||||
if (beginIndex < 0) {
|
||||
beginIndex = 0;
|
||||
}
|
||||
return beginIndex;
|
||||
}
|
||||
|
||||
public static String getCellFormatValue(Cell cell) {
|
||||
String cellvalue = "";
|
||||
if (cell != null) {
|
||||
switch (cell.getCellType()) {
|
||||
case 3:
|
||||
{
|
||||
cellvalue = "";
|
||||
break;
|
||||
}
|
||||
case 4:
|
||||
{
|
||||
cellvalue = String.valueOf(cell.getBooleanCellValue());
|
||||
break;
|
||||
}
|
||||
case 0:
|
||||
case 2:
|
||||
{
|
||||
if (DateUtil.isCellDateFormatted((Cell) cell)) {
|
||||
Date date = cell.getDateCellValue();
|
||||
SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD);
|
||||
cellvalue = sdf.format(date);
|
||||
break;
|
||||
}
|
||||
cellvalue = String.valueOf(cell.getNumericCellValue());
|
||||
break;
|
||||
}
|
||||
default:
|
||||
{
|
||||
cellvalue = cell.getRichStringCellValue().getString();
|
||||
}
|
||||
}
|
||||
}
|
||||
return cellvalue;
|
||||
}
|
||||
|
||||
public static String getCellStringValue(Cell cell) {
|
||||
cell.setCellType(1);
|
||||
String cellvalue = "";
|
||||
switch (cell.getCellType()) {
|
||||
case 3:
|
||||
{
|
||||
cellvalue = "";
|
||||
break;
|
||||
}
|
||||
default:
|
||||
{
|
||||
cellvalue = cell.getRichStringCellValue().getString();
|
||||
}
|
||||
}
|
||||
return cellvalue;
|
||||
}
|
||||
|
||||
public static int getLastRowIndex(Sheet sheet) {
|
||||
int nIndex = -1;
|
||||
if (sheet == null) {
|
||||
return nIndex;
|
||||
}
|
||||
nIndex =
|
||||
sheet.getPhysicalNumberOfRows() == 0 && sheet.getLastRowNum() == 0
|
||||
? 0
|
||||
: sheet.getLastRowNum() + 1;
|
||||
return nIndex;
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
|
||||
// 业务服务
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class FileCompressUtil {
|
||||
private static final Logger log = LoggerFactory.getLogger(FileCompressUtil.class);
|
||||
|
||||
private FileCompressUtil() {}
|
||||
|
||||
public static String compressToZip(String sourceFilePath, String zipFilePath, String zipFilename)
|
||||
throws IOException {
|
||||
return FileCompressUtil.compressToZip(sourceFilePath, zipFilePath, zipFilename, true);
|
||||
}
|
||||
|
||||
public static String compressToZip(
|
||||
String sourceFilePath, String zipFilePath, String zipFilename, boolean withFolderName)
|
||||
throws IOException {
|
||||
File sourceFile = new File(sourceFilePath);
|
||||
File zipPath = new File(zipFilePath);
|
||||
if (!zipPath.exists()) {
|
||||
zipPath.mkdirs();
|
||||
}
|
||||
File zipFile = new File(zipPath + File.separator + zipFilename);
|
||||
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile)); ) {
|
||||
FileCompressUtil.writeZip(sourceFile, "", zos, withFolderName);
|
||||
}
|
||||
return zipFile.getPath();
|
||||
}
|
||||
|
||||
public static void writeZip(
|
||||
File file, String parentPath, ZipOutputStream zos, boolean withFolderName)
|
||||
throws IOException {
|
||||
if (file.isDirectory()) {
|
||||
File[] files;
|
||||
parentPath = parentPath + file.getName() + File.separator;
|
||||
for (File f : files = file.listFiles()) {
|
||||
FileCompressUtil.writeZip(f, parentPath, zos, withFolderName);
|
||||
}
|
||||
} else {
|
||||
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); ) {
|
||||
int len;
|
||||
String zipParentPath =
|
||||
withFolderName
|
||||
? parentPath
|
||||
: parentPath.substring(parentPath.indexOf(File.separator) + 1);
|
||||
ZipEntry zipEntry = new ZipEntry(zipParentPath + file.getName());
|
||||
zos.putNextEntry(zipEntry);
|
||||
byte[] buffer = new byte[10240];
|
||||
while ((len = bis.read(buffer, 0, buffer.length)) != -1) {
|
||||
zos.write(buffer, 0, len);
|
||||
zos.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
|
||||
// 业务服务
|
||||
public enum FileContentType {
|
||||
JPEG("FFD8FF", "jpeg and jpg"),
|
||||
PNG("89504E47", "png"),
|
||||
BMP("424D", "bmp");
|
||||
|
||||
private String type;
|
||||
private String description;
|
||||
|
||||
private FileContentType(String type, String description) {
|
||||
this.type = type;
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return this.type;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return this.description;
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
|
||||
// 业务服务
|
||||
public enum FileType {
|
||||
JPEG("jpeg", "jpeg"),
|
||||
JPG("jpg", "jpg"),
|
||||
PNG("png", "png"),
|
||||
BMP("bmp", "bmp");
|
||||
|
||||
private String type;
|
||||
private String description;
|
||||
|
||||
private FileType(String type, String description) {
|
||||
this.type = type;
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return this.type;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return this.description;
|
||||
}
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
|
||||
// 业务服务
|
||||
import au.com.bytecode.opencsv.CSVReader;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
import cn.cloudwalk.service.organization.common.ByteUtil;
|
||||
import cn.cloudwalk.service.organization.common.FileContentType;
|
||||
import cn.cloudwalk.service.organization.common.FileType;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
public final class FileUtil {
|
||||
private FileUtil() {}
|
||||
|
||||
public static List<File> findExpecteFormatdFile(
|
||||
String filePattern, File folder, List<File> list) {
|
||||
Object[] files;
|
||||
if (list == null) {
|
||||
list = new ArrayList<File>();
|
||||
}
|
||||
if (ArrayUtils.isNotEmpty((Object[]) (files = folder.listFiles()))) {
|
||||
for (Object f : files) {
|
||||
if (f == null) continue;
|
||||
if (((File) f).isFile() && ((File) f).getName().toLowerCase().matches(filePattern)) {
|
||||
list.add((File) f);
|
||||
continue;
|
||||
}
|
||||
if (!((File) f).isDirectory()) continue;
|
||||
FileUtil.findExpecteFormatdFile(filePattern, (File) f, list);
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List<File> findExpecteFormatdFile(String filePattern, File folder) {
|
||||
return FileUtil.findExpecteFormatdFile(filePattern, folder, null);
|
||||
}
|
||||
|
||||
public static boolean readCsvFile(File csv, List<List<String>> result, String csvConfigJson)
|
||||
throws ServiceException {
|
||||
JSONObject csvConfig = JSON.parseObject((String) csvConfigJson);
|
||||
String charset = csvConfig.getString("charset");
|
||||
char separateChar = csvConfig.getString("separateChar").charAt(0);
|
||||
char quoteChar = csvConfig.getString("quoteChar").charAt(0);
|
||||
try (FileInputStream fis = new FileInputStream(csv);
|
||||
InputStreamReader isr = new InputStreamReader((InputStream) fis, charset);
|
||||
CSVReader reader = new CSVReader((Reader) isr, separateChar, quoteChar); ) {
|
||||
String[] data;
|
||||
while ((data = reader.readNext()) != null) {
|
||||
result.add(Arrays.asList(data));
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new ServiceException(e);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean isAppointFileType(String inputFileType, FileType... fileTypes) {
|
||||
if (inputFileType == null || "".equals(inputFileType)) {
|
||||
return false;
|
||||
}
|
||||
boolean isAppoint = false;
|
||||
for (FileType fileType : fileTypes) {
|
||||
if (!fileType.getType().equalsIgnoreCase(inputFileType)) continue;
|
||||
isAppoint = true;
|
||||
break;
|
||||
}
|
||||
return isAppoint;
|
||||
}
|
||||
|
||||
public static boolean isAppointFileContentType(
|
||||
String inputFileContentType, FileContentType... fileContentTypes) {
|
||||
if (inputFileContentType == null || "".equals(inputFileContentType)) {
|
||||
return false;
|
||||
}
|
||||
boolean isAppoint = false;
|
||||
for (FileContentType fileContentType : fileContentTypes) {
|
||||
String fileContentTypeUpper;
|
||||
String inputFileContentTypeUpper = inputFileContentType.toUpperCase();
|
||||
if (inputFileContentTypeUpper.indexOf(
|
||||
fileContentTypeUpper = fileContentType.getType().toUpperCase())
|
||||
== -1
|
||||
&& fileContentTypeUpper.indexOf(inputFileContentTypeUpper) == -1) continue;
|
||||
isAppoint = true;
|
||||
break;
|
||||
}
|
||||
return isAppoint;
|
||||
}
|
||||
|
||||
public static String getFileContentType(byte[] fileBytes) {
|
||||
if (fileBytes == null || fileBytes.length < 4) {
|
||||
return null;
|
||||
}
|
||||
byte[] b = new byte[4];
|
||||
for (int i = 0; i < b.length; ++i) {
|
||||
b[i] = fileBytes[i];
|
||||
}
|
||||
String value = ByteUtil.bytesToHexString(b);
|
||||
return value;
|
||||
}
|
||||
|
||||
public static String getBase64File(String base64) {
|
||||
String[] content = base64.split(",");
|
||||
if (content.length == 2) {
|
||||
base64 = content[content.length - 1];
|
||||
return base64;
|
||||
}
|
||||
return base64;
|
||||
}
|
||||
|
||||
public static InputStream base64ToInputStream(String base64) {
|
||||
try {
|
||||
if (StringUtils.isNotEmpty((CharSequence) base64)) {
|
||||
return new ByteArrayInputStream(
|
||||
Base64.decodeBase64((String) FileUtil.getBase64File(base64)));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String inputStream2base64(InputStream is) {
|
||||
try {
|
||||
byte[] bs = IOUtils.toByteArray((InputStream) is);
|
||||
return Base64.encodeBase64String((byte[]) bs);
|
||||
} catch (IOException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String url2base64(String url) {
|
||||
return FileUtil.inputStream2base64(FileUtil.download(url));
|
||||
}
|
||||
|
||||
public static InputStream download(String url) {
|
||||
try {
|
||||
URL u = new URL(url);
|
||||
return u.openStream();
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static long getFileSizeFromBase64(String base64) {
|
||||
if (base64.contains(",")) {
|
||||
base64 = base64.substring(base64.indexOf(44));
|
||||
}
|
||||
if (base64.contains("=")) {
|
||||
base64 = base64.substring(0, base64.indexOf(61));
|
||||
}
|
||||
long length = base64.length();
|
||||
return length - length / 8L * 2L;
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
|
||||
// 业务服务
|
||||
import java.util.List;
|
||||
|
||||
public interface FlushHandler<E> {
|
||||
public void onFlush(List<E> var1);
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.service.organization.common.FlushHandler;
|
||||
import com.google.common.collect.Lists;
|
||||
import java.util.ArrayList;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
public class FlushList<E> extends ArrayList<E> {
|
||||
private FlushHandler<E> handler;
|
||||
private ArrayList<E> subList = null;
|
||||
private int flushSize;
|
||||
|
||||
public FlushList(FlushHandler<E> handler, int flushSize) {
|
||||
this.handler = handler;
|
||||
this.flushSize = flushSize;
|
||||
this.subList = new ArrayList(flushSize);
|
||||
}
|
||||
|
||||
public FlushHandler<E> getHandler() {
|
||||
return this.handler;
|
||||
}
|
||||
|
||||
public void setHandler(FlushHandler<E> handler) {
|
||||
this.handler = handler;
|
||||
}
|
||||
|
||||
public int getFlushSize() {
|
||||
return this.flushSize;
|
||||
}
|
||||
|
||||
public void setFlushSize(int flushSize) {
|
||||
this.flushSize = flushSize;
|
||||
}
|
||||
|
||||
/*
|
||||
* WARNING - Removed try catching itself - possible behaviour change.
|
||||
*/
|
||||
@Override
|
||||
public boolean add(E e) {
|
||||
boolean result = this.subList.add(e);
|
||||
if (this.subList.size() == this.getFlushSize()) {
|
||||
ArrayList dest = null;
|
||||
FlushList flushList = this;
|
||||
synchronized (flushList) {
|
||||
dest = Lists.newArrayList(this.subList);
|
||||
this.subList.clear();
|
||||
}
|
||||
this.handler.onFlush(dest);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/*
|
||||
* WARNING - Removed try catching itself - possible behaviour change.
|
||||
*/
|
||||
public void flush() {
|
||||
if (!CollectionUtils.isEmpty(this.subList)) {
|
||||
ArrayList dest = null;
|
||||
FlushList flushList = this;
|
||||
synchronized (flushList) {
|
||||
dest = Lists.newArrayList(this.subList);
|
||||
this.subList.clear();
|
||||
}
|
||||
this.handler.onFlush(dest);
|
||||
}
|
||||
}
|
||||
}
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
|
||||
// 业务服务
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.file.CopyOption;
|
||||
import java.nio.file.FileVisitResult;
|
||||
import java.nio.file.FileVisitor;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.SimpleFileVisitor;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.nio.file.attribute.FileAttribute;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class FolderUtil {
|
||||
private static final Logger log = LoggerFactory.getLogger(FolderUtil.class);
|
||||
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
|
||||
public static void doDelete(File file) {
|
||||
if (file.exists() && !file.delete()) {
|
||||
log.error("文件删除失败");
|
||||
}
|
||||
}
|
||||
|
||||
public static void copyFolder(String srcFolder, String destFolder) throws IOException {
|
||||
final Path srcPath = Paths.get(srcFolder, new String[0]);
|
||||
final Path destPath = Paths.get(destFolder, srcPath.toFile().getName());
|
||||
if (!srcPath.toFile().exists()) {
|
||||
return;
|
||||
}
|
||||
if (!destPath.toFile().exists()) {
|
||||
Files.createDirectories(destPath, new FileAttribute[0]);
|
||||
}
|
||||
Files.walkFileTree(
|
||||
srcPath,
|
||||
(FileVisitor<? super Path>)
|
||||
new SimpleFileVisitor<Path>() {
|
||||
|
||||
@Override
|
||||
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
|
||||
throws IOException {
|
||||
Path dest = destPath.resolve(srcPath.relativize(file));
|
||||
if (!dest.getParent().toFile().exists()) {
|
||||
Files.createDirectories(dest.getParent(), new FileAttribute[0]);
|
||||
}
|
||||
Files.copy(file, dest, new CopyOption[0]);
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static void deleteFolder(String foleder) throws IOException {
|
||||
File file = new File(foleder);
|
||||
if (file.exists()) {
|
||||
File[] files = file.listFiles();
|
||||
int len = files.length;
|
||||
for (int i = 0; i < len; ++i) {
|
||||
if (files[i].isDirectory()) {
|
||||
FolderUtil.deleteFolder(files[i].getPath());
|
||||
continue;
|
||||
}
|
||||
FolderUtil.doDelete(files[i]);
|
||||
}
|
||||
FolderUtil.doDelete(file);
|
||||
}
|
||||
}
|
||||
|
||||
public static Desk getDeskUsageIfo(String path) throws IOException {
|
||||
Desk desk = new Desk();
|
||||
Runtime rt = Runtime.getRuntime();
|
||||
Process p = rt.exec("df -hl " + path);
|
||||
try (BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); ) {
|
||||
String str = null;
|
||||
String[] strArray = null;
|
||||
int line = 0;
|
||||
while ((str = in.readLine()) != null) {
|
||||
if (++line != 2) continue;
|
||||
int m = 0;
|
||||
for (String para : strArray = str.split(" ")) {
|
||||
if (para.trim().length() == 0) continue;
|
||||
++m;
|
||||
if (para.endsWith("G") || para.endsWith("Gi")) {
|
||||
if (m == 2) {
|
||||
desk.setSize(para);
|
||||
}
|
||||
if (m == 3) {
|
||||
desk.setUsed(para);
|
||||
}
|
||||
if (m == 4) {
|
||||
desk.setAvail(para);
|
||||
}
|
||||
}
|
||||
if (!para.endsWith("%") || m != 5) continue;
|
||||
desk.setUseRate(para);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("exception:{}", (Object) e.getMessage());
|
||||
}
|
||||
return desk;
|
||||
}
|
||||
|
||||
public static class Desk {
|
||||
private String size;
|
||||
private String used;
|
||||
private String avail;
|
||||
private String useRate;
|
||||
|
||||
public int getSize() {
|
||||
return this.replaceG(this.size);
|
||||
}
|
||||
|
||||
public void setSize(String size) {
|
||||
this.size = size;
|
||||
}
|
||||
|
||||
public int getUsed() {
|
||||
return this.replaceG(this.size);
|
||||
}
|
||||
|
||||
public void setUsed(String used) {
|
||||
this.used = used;
|
||||
}
|
||||
|
||||
public int getAvail() {
|
||||
return this.replaceG(this.avail);
|
||||
}
|
||||
|
||||
public void setAvail(String avail) {
|
||||
this.avail = avail;
|
||||
}
|
||||
|
||||
public String getUseRate() {
|
||||
return this.useRate;
|
||||
}
|
||||
|
||||
public void setUseRate(String useRate) {
|
||||
this.useRate = useRate;
|
||||
}
|
||||
|
||||
private int replaceG(String para) {
|
||||
String newPara = "0";
|
||||
if (para != null && !"".equals(para)) {
|
||||
newPara =
|
||||
para.endsWith("G")
|
||||
? para.replace("G", "")
|
||||
: (para.endsWith("Gi") ? para.replace("Gi", "") : para);
|
||||
}
|
||||
return Integer.valueOf(newPara);
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "总磁盘空间:"
|
||||
+ this.size
|
||||
+ ",已使用:"
|
||||
+ this.used
|
||||
+ ",剩余可用:"
|
||||
+ this.avail
|
||||
+ ",使用率达:"
|
||||
+ this.useRate;
|
||||
}
|
||||
}
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
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 net.coobird.thumbnailator.Thumbnails;
|
||||
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;
|
||||
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() {}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
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() {}
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JavaType;
|
||||
import com.fasterxml.jackson.databind.Module;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import com.google.common.collect.Lists;
|
||||
import java.io.IOException;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.TimeZone;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/** 与 {@code cwos-component-organization-service-v2.9.2_xinghewan.jar} / {@code jar.src} 对齐。 */
|
||||
public class JsonUtils {
|
||||
private static final Logger log = LoggerFactory.getLogger(JsonUtils.class);
|
||||
private static final ThreadLocal<ObjectMapper> MAPPER;
|
||||
|
||||
static {
|
||||
MAPPER =
|
||||
ThreadLocal.withInitial(
|
||||
() -> {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
|
||||
objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
|
||||
objectMapper.registerModule((Module) new JavaTimeModule());
|
||||
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
objectMapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
|
||||
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
|
||||
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
objectMapper.setTimeZone(TimeZone.getTimeZone(ZoneOffset.ofHours(8)));
|
||||
return objectMapper;
|
||||
});
|
||||
}
|
||||
|
||||
private JsonUtils() {}
|
||||
|
||||
private static ObjectMapper objectMapper() {
|
||||
return MAPPER.get();
|
||||
}
|
||||
|
||||
public static String toJson(Object obj) {
|
||||
ObjectMapper mapper = objectMapper();
|
||||
try {
|
||||
return mapper.writeValueAsString(obj);
|
||||
} catch (JsonProcessingException e) {
|
||||
log.error("toJson错误", (Throwable) e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> T toObj(String json, Class<T> clazz) {
|
||||
ObjectMapper mapper = objectMapper();
|
||||
try {
|
||||
return (T) mapper.readValue(json, clazz);
|
||||
} catch (IOException e) {
|
||||
log.error("toObj错误", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> List<T> toObjList(String jsonArr, Class<T> clazz) {
|
||||
ObjectMapper mapper = objectMapper();
|
||||
JavaType javaType =
|
||||
mapper.getTypeFactory().constructParametricType(ArrayList.class, new Class[] {clazz});
|
||||
try {
|
||||
return (List<T>) mapper.readValue(jsonArr, javaType);
|
||||
} catch (IOException e) {
|
||||
log.error("parseArray 错误", e);
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
|
||||
public static List<String> toStrList(String jsonArr) {
|
||||
if (StringUtils.isBlank(jsonArr)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
JSONArray jsonArray = JSON.parseArray(jsonArr);
|
||||
List<String> list = Lists.newArrayListWithCapacity(jsonArray.size());
|
||||
jsonArray.stream().forEach(i -> list.add(i.toString()));
|
||||
return list;
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
|
||||
// 业务服务
|
||||
import java.io.OutputStream;
|
||||
import org.apache.commons.fileupload.FileItem;
|
||||
import org.apache.commons.fileupload.disk.DiskFileItem;
|
||||
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.multipart.commons.CommonsMultipartFile;
|
||||
|
||||
public class MultipartFileUtils {
|
||||
private static final Logger log = LoggerFactory.getLogger(MultipartFileUtils.class);
|
||||
|
||||
private MultipartFileUtils() {}
|
||||
|
||||
public static MultipartFile getMultipartFile(String fileName, byte[] bytes) {
|
||||
DiskFileItem fileItem =
|
||||
(DiskFileItem) new DiskFileItemFactory().createItem("media", "text/plain", true, fileName);
|
||||
fileItem.setFieldName("file");
|
||||
CommonsMultipartFile mfile = null;
|
||||
try {
|
||||
OutputStream os = fileItem.getOutputStream();
|
||||
os.write(bytes);
|
||||
mfile = new CommonsMultipartFile((FileItem) fileItem);
|
||||
} catch (Exception e) {
|
||||
log.error("获得MultipartFile异常:{}", e);
|
||||
}
|
||||
return mfile;
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import okhttp3.Call;
|
||||
import okhttp3.MediaType;
|
||||
import okhttp3.MultipartBody;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.RequestBody;
|
||||
import okhttp3.Response;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/** 与 {@code cwos-component-organization-service-v2.9.2_xinghewan.jar} / {@code jar.src} 对齐。 */
|
||||
public class OkhttpUtil {
|
||||
private static final Logger log = LoggerFactory.getLogger(OkhttpUtil.class);
|
||||
|
||||
private static final OkHttpClient CLIENT;
|
||||
|
||||
private static final MediaType MEDIATYPE_JSON =
|
||||
MediaType.parse("application/json; charset=utf-8");
|
||||
|
||||
private static int connectTimeout = 5;
|
||||
private static int writeTimeout = 10;
|
||||
private static int readTimeout = 10;
|
||||
|
||||
static {
|
||||
CLIENT =
|
||||
new OkHttpClient.Builder()
|
||||
.connectTimeout(connectTimeout, TimeUnit.SECONDS)
|
||||
.writeTimeout(writeTimeout, TimeUnit.SECONDS)
|
||||
.readTimeout(readTimeout, TimeUnit.SECONDS)
|
||||
.build();
|
||||
}
|
||||
|
||||
private OkhttpUtil() {
|
||||
throw new IllegalStateException("Utility class");
|
||||
}
|
||||
|
||||
public static String get(String url) {
|
||||
Request request = new Request.Builder().url(url).get().build();
|
||||
return buildRequest(request);
|
||||
}
|
||||
|
||||
public static byte[] getImage(String url) {
|
||||
byte[] bytes;
|
||||
Request request = new Request.Builder().url(url).get().build();
|
||||
|
||||
Call call = CLIENT.newCall(request);
|
||||
|
||||
try {
|
||||
Response execute = call.execute();
|
||||
bytes = execute.body().bytes();
|
||||
} catch (IOException e) {
|
||||
log.info("获得图片异常:{}", e.getMessage());
|
||||
return new byte[0];
|
||||
}
|
||||
|
||||
return bytes;
|
||||
}
|
||||
|
||||
public static String uploadImage(String url, byte[] bytes, String name) {
|
||||
RequestBody fileBody =
|
||||
RequestBody.create(MediaType.parse("application/octet-stream"), bytes);
|
||||
|
||||
MultipartBody body =
|
||||
new MultipartBody.Builder()
|
||||
.setType(MultipartBody.FORM)
|
||||
.addFormDataPart("file", name, fileBody)
|
||||
.build();
|
||||
|
||||
Request request = new Request.Builder().post(body).url(url).build();
|
||||
|
||||
try {
|
||||
return CLIENT.newCall(request).execute().body().string();
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String get(String url, Map<String, String> params) {
|
||||
StringBuilder paramStr = new StringBuilder();
|
||||
if (params != null && !params.isEmpty()) {
|
||||
params.forEach((k, v) -> paramStr.append(k).append("=").append(v).append("&"));
|
||||
}
|
||||
url = url + paramStr;
|
||||
|
||||
return get(url);
|
||||
}
|
||||
|
||||
public static String postJson(String url, Object params) {
|
||||
RequestBody requestBody =
|
||||
RequestBody.create(MEDIATYPE_JSON, JsonUtils.toJson(params));
|
||||
|
||||
Request request = new Request.Builder().url(url).post(requestBody).build();
|
||||
|
||||
return buildRequest(request);
|
||||
}
|
||||
|
||||
public static String postJson(String url, String params) {
|
||||
RequestBody requestBody = RequestBody.create(MEDIATYPE_JSON, params);
|
||||
|
||||
Request request = new Request.Builder().url(url).post(requestBody).build();
|
||||
|
||||
return buildRequest(request);
|
||||
}
|
||||
|
||||
public static String postJson(String url, String params, Map<String, String> headers) {
|
||||
RequestBody requestBody = RequestBody.create(MEDIATYPE_JSON, params);
|
||||
|
||||
Request.Builder builder = new Request.Builder().url(url).post(requestBody);
|
||||
|
||||
if (headers != null) {
|
||||
headers.forEach(builder::addHeader);
|
||||
}
|
||||
Request request = builder.build();
|
||||
|
||||
return buildRequest(request);
|
||||
}
|
||||
|
||||
private static String buildRequest(Request request) {
|
||||
Call call = CLIENT.newCall(request);
|
||||
String resp = null;
|
||||
try {
|
||||
Response execute = call.execute();
|
||||
resp = execute.body().string();
|
||||
} catch (IOException e) {
|
||||
log.error(
|
||||
"请求失败, {} e={},message={}",
|
||||
request.url().encodedPath(),
|
||||
e.getClass().getName(),
|
||||
e.getMessage());
|
||||
}
|
||||
return resp;
|
||||
}
|
||||
}
|
||||
+291
@@ -0,0 +1,291 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
|
||||
import cn.cloudwalk.data.organization.dto.ImageInfoDto;
|
||||
import com.google.common.base.Preconditions;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Base64;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.bytedeco.javacpp.Loader;
|
||||
import org.bytedeco.javacpp.opencv_java;
|
||||
import org.opencv.core.Mat;
|
||||
import org.opencv.core.MatOfByte;
|
||||
import org.opencv.core.Point;
|
||||
import org.opencv.core.Size;
|
||||
import org.opencv.imgcodecs.Imgcodecs;
|
||||
import org.opencv.imgproc.Imgproc;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 与现场 {@code cwos-component-organization-service-v2.9.2_xinghewan} 字节码及 {@code jar.src} 逻辑对齐。
|
||||
*
|
||||
* <p>JD-Core 反编译件见 {@code cwos-component-organization-service-v2.9.2_xinghewan.jar.src/.../OpenCvUtils.java}(其中 {@code init = true}
|
||||
* 为反编译瑕疵;{@code javap -p} 显示字段为默认 {@code false},与本实现一致)。
|
||||
*/
|
||||
@Component
|
||||
public class OpenCvUtils implements CommandLineRunner {
|
||||
|
||||
private Logger logger = LoggerFactory.getLogger(OpenCvUtils.class);
|
||||
|
||||
@Value("${cloudwalk.image.compress.width:400}")
|
||||
private Integer compressWidth;
|
||||
|
||||
private boolean init;
|
||||
|
||||
@Override
|
||||
public void run(String... strings) throws Exception {
|
||||
new Thread(
|
||||
() -> {
|
||||
logger.info("apps org load opencv start");
|
||||
Loader.load(opencv_java.class);
|
||||
init = true;
|
||||
logger.info("apps org load opencv end");
|
||||
})
|
||||
.start();
|
||||
}
|
||||
|
||||
private ImageInfoDto getGraphicsCompressBytes(byte[] bytes) {
|
||||
Mat src = null;
|
||||
try {
|
||||
src = byteArrayImage2Mat(bytes);
|
||||
ImageInfoDto imageInfoDto = new ImageInfoDto();
|
||||
imageInfoDto.setWidth(src.cols());
|
||||
imageInfoDto.setHeight(src.rows());
|
||||
imageInfoDto.initCompressValue(compressWidth.intValue());
|
||||
return imageInfoDto;
|
||||
} finally {
|
||||
if (src != null) {
|
||||
src.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public ImageInfoDto getGraphicsCompressBase64(String base64Img) {
|
||||
if (!init) {
|
||||
ImageInfoDto imageInfoDto1 = new ImageInfoDto();
|
||||
imageInfoDto1.setBase64(base64Img);
|
||||
imageInfoDto1.setBase64Compress(base64Img);
|
||||
return imageInfoDto1;
|
||||
}
|
||||
Mat src = null;
|
||||
Mat compress = null;
|
||||
try {
|
||||
src = byteArrayImage2Mat(Base64.getDecoder().decode(base64Img));
|
||||
ImageInfoDto imageInfoDto = new ImageInfoDto();
|
||||
imageInfoDto.setWidth(src.cols());
|
||||
imageInfoDto.setHeight(src.rows());
|
||||
imageInfoDto.setBase64(base64Img);
|
||||
imageInfoDto.initCompressValue(compressWidth.intValue());
|
||||
if (imageInfoDto.getScale() != null) {
|
||||
compress =
|
||||
resizeImage(
|
||||
src,
|
||||
imageInfoDto.getHeightCompress().intValue(),
|
||||
imageInfoDto.getWidthCompress().intValue());
|
||||
imageInfoDto.setBase64Compress(
|
||||
Base64.getEncoder().encodeToString(encodeMat(compress, ".jpg")));
|
||||
}
|
||||
return imageInfoDto;
|
||||
} finally {
|
||||
if (src != null) {
|
||||
src.release();
|
||||
}
|
||||
if (compress != null) {
|
||||
compress.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public ImageInfoDto cropAndCompressImgBase64(String base64Img, int x, int y, int width, int height) {
|
||||
Mat src = null;
|
||||
Mat sub = null;
|
||||
Mat compress = null;
|
||||
try {
|
||||
src = byteArrayImage2Mat(Base64.getDecoder().decode(base64Img));
|
||||
sub = subImageXY(src, x, y, width, height);
|
||||
ImageInfoDto imageInfoDto = new ImageInfoDto();
|
||||
imageInfoDto.setWidth(width);
|
||||
imageInfoDto.setHeight(height);
|
||||
imageInfoDto.setBase64(Base64.getEncoder().encodeToString(encodeMat(sub, ".jpg")));
|
||||
imageInfoDto.initCompressValue(compressWidth.intValue());
|
||||
if (imageInfoDto.getScale() != null) {
|
||||
compress =
|
||||
resizeImage(
|
||||
sub,
|
||||
imageInfoDto.getHeightCompress().intValue(),
|
||||
imageInfoDto.getWidthCompress().intValue());
|
||||
imageInfoDto.setBase64Compress(
|
||||
Base64.getEncoder().encodeToString(encodeMat(compress, ".jpg")));
|
||||
}
|
||||
return imageInfoDto;
|
||||
} finally {
|
||||
if (src != null) {
|
||||
src.release();
|
||||
}
|
||||
if (sub != null) {
|
||||
sub.release();
|
||||
}
|
||||
if (compress != null) {
|
||||
compress.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String cropImgBase64(String base64Img, int x, int y, int width, int height) {
|
||||
if (!init) {
|
||||
return base64Img;
|
||||
}
|
||||
Mat src = null;
|
||||
Mat sub = null;
|
||||
try {
|
||||
src = byteArrayImage2Mat(Base64.getDecoder().decode(base64Img));
|
||||
sub = subImageXY(src, x, y, width, height);
|
||||
return Base64.getEncoder().encodeToString(encodeMat(sub, ".jpg"));
|
||||
} finally {
|
||||
if (src != null) {
|
||||
src.release();
|
||||
}
|
||||
if (sub != null) {
|
||||
sub.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public InputStream resizeImageInputStream(InputStream inputStream, int width, int height)
|
||||
throws IOException {
|
||||
if (!init) {
|
||||
return inputStream;
|
||||
}
|
||||
byte[] bytes = IOUtils.toByteArray(inputStream);
|
||||
return new ByteArrayInputStream(resizeImageBytes(bytes, width, height));
|
||||
}
|
||||
|
||||
public String resizeImageBase64(String base64Img, int width, int height) {
|
||||
if (!init) {
|
||||
return base64Img;
|
||||
}
|
||||
return Base64.getEncoder()
|
||||
.encodeToString(resizeImageBytes(Base64.getDecoder().decode(base64Img), width, height));
|
||||
}
|
||||
|
||||
public byte[] resizeImageBytes(byte[] bytes) {
|
||||
if (!init) {
|
||||
return bytes;
|
||||
}
|
||||
ImageInfoDto imageInfoDto = getGraphicsCompressBytes(bytes);
|
||||
if (imageInfoDto.getScale() != null) {
|
||||
return resizeImageBytes(
|
||||
bytes,
|
||||
imageInfoDto.getWidthCompress().intValue(),
|
||||
imageInfoDto.getHeightCompress().intValue());
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
public byte[] resizeImageBytes(byte[] bytes, int width, int height) {
|
||||
if (!init) {
|
||||
return bytes;
|
||||
}
|
||||
Mat src = null;
|
||||
Mat compress = null;
|
||||
try {
|
||||
src = byteArrayImage2Mat(bytes);
|
||||
compress = resizeImage(src, height, width);
|
||||
return encodeMat(compress, ".jpg");
|
||||
} finally {
|
||||
if (src != null) {
|
||||
src.release();
|
||||
}
|
||||
if (compress != null) {
|
||||
compress.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Mat byteArrayImage2Mat(byte[] rawData) {
|
||||
MatOfByte mob = null;
|
||||
try {
|
||||
mob = new MatOfByte(rawData);
|
||||
return Imgcodecs.imdecode(mob, -1);
|
||||
} finally {
|
||||
if (mob != null) {
|
||||
mob.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] encodeMat(Mat matrix, String ext) {
|
||||
MatOfByte mob = null;
|
||||
try {
|
||||
mob = new MatOfByte();
|
||||
Imgcodecs.imencode(ext, matrix, mob);
|
||||
return mob.toArray();
|
||||
} finally {
|
||||
if (mob != null) {
|
||||
mob.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Mat resizeImage(Mat sourceMat, int height, int width) {
|
||||
if (sourceMat.height() == height && sourceMat.width() == width) {
|
||||
return sourceMat;
|
||||
}
|
||||
Mat dstMat = new Mat();
|
||||
Imgproc.resize(sourceMat, dstMat, new Size(width, height));
|
||||
return dstMat;
|
||||
}
|
||||
|
||||
private Mat subImageXY(Mat src, int x, int y, int width, int height) {
|
||||
Preconditions.checkArgument(x <= src.cols(), "x must be within source image width");
|
||||
Preconditions.checkArgument(x + width <= src.cols(), "x + width must be within source image width");
|
||||
Preconditions.checkArgument(y <= src.rows(), "y must be within source image height");
|
||||
Preconditions.checkArgument(y + height <= src.rows(), "y + height must be within source image height");
|
||||
return src.submat(y, y + height, x, x + width);
|
||||
}
|
||||
|
||||
/** 与现场一致:{@code warpAffine} 最后一参为字面量 {@code 10}(JD-Core / CFR 输出口径)。 */
|
||||
public static Mat rotate(Mat src, double angle) {
|
||||
double radians = angle * Math.PI / 180.0;
|
||||
double sin = Math.abs(Math.sin(radians));
|
||||
double cos = Math.abs(Math.cos(radians));
|
||||
int srcWidth = src.width();
|
||||
int srcHeight = src.height();
|
||||
int dstWidth = (int) ((double) srcWidth * cos + (double) srcHeight * sin);
|
||||
int dstHeight = (int) ((double) srcWidth * sin + (double) srcHeight * cos);
|
||||
Mat dst = new Mat(dstHeight, dstWidth, src.type());
|
||||
Point center = new Point((double) (src.cols() / 2), (double) (src.rows() / 2));
|
||||
Mat rotMatrix = Imgproc.getRotationMatrix2D(center, angle, 1.0);
|
||||
double widthOffset = (double) (dstWidth - srcWidth) / 2.0;
|
||||
double heightOffset = (double) (dstHeight - srcHeight) / 2.0;
|
||||
rotMatrix.put(0, 2, rotMatrix.get(0, 2)[0] + widthOffset);
|
||||
rotMatrix.put(1, 2, rotMatrix.get(1, 2)[0] + heightOffset);
|
||||
Imgproc.warpAffine(src, dst, rotMatrix, dst.size(), 10);
|
||||
return dst;
|
||||
}
|
||||
|
||||
public byte[] rotateImageBytes(byte[] bytes, double angele) {
|
||||
if (!init) {
|
||||
return bytes;
|
||||
}
|
||||
Mat src = null;
|
||||
Mat compress = null;
|
||||
try {
|
||||
src = byteArrayImage2Mat(bytes);
|
||||
compress = rotate(src, angele);
|
||||
return encodeMat(compress, ".jpg");
|
||||
} finally {
|
||||
if (src != null) {
|
||||
src.release();
|
||||
}
|
||||
if (compress != null) {
|
||||
compress.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
|
||||
// 业务服务
|
||||
import com.google.common.collect.Lists;
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.HashMap;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
public final class PathUtils {
|
||||
private PathUtils() {}
|
||||
|
||||
public static String paths(String fileName, String... paths) {
|
||||
String filePath = fileName;
|
||||
if (ArrayUtils.isNotEmpty((Object[]) paths)) {
|
||||
filePath =
|
||||
StringUtils.join((Object[]) paths, (char) File.separatorChar) + File.separator + fileName;
|
||||
}
|
||||
return PathUtils.checkPathSafe(filePath);
|
||||
}
|
||||
|
||||
public static String joinPaths(String... paths) {
|
||||
String filePath = StringUtils.join((Object[]) paths, (char) File.separatorChar);
|
||||
if (File.separatorChar == '\\') {
|
||||
return PathUtils.checkPathSafe(filePath.replaceAll("[/|\\\\]{2,}", "\\\\"));
|
||||
}
|
||||
return PathUtils.checkPathSafe(filePath.replaceAll("[/|\\\\]{2,}", File.separator));
|
||||
}
|
||||
|
||||
public static String checkPathSafe(String path) {
|
||||
HashMap<String, String> map = new HashMap<String, String>();
|
||||
map.put("a", "a");
|
||||
map.put("b", "b");
|
||||
map.put("c", "c");
|
||||
map.put("d", "d");
|
||||
map.put("e", "e");
|
||||
map.put("f", "f");
|
||||
map.put("g", "g");
|
||||
map.put("h", "h");
|
||||
map.put("i", "i");
|
||||
map.put("j", "j");
|
||||
map.put("k", "k");
|
||||
map.put("l", "l");
|
||||
map.put("m", "m");
|
||||
map.put("n", "n");
|
||||
map.put("o", "o");
|
||||
map.put("p", "p");
|
||||
map.put("q", "q");
|
||||
map.put("r", "r");
|
||||
map.put("s", "s");
|
||||
map.put("t", "t");
|
||||
map.put("u", "u");
|
||||
map.put("v", "v");
|
||||
map.put("w", "w");
|
||||
map.put("x", "x");
|
||||
map.put("y", "y");
|
||||
map.put("z", "z");
|
||||
map.put("A", "A");
|
||||
map.put("B", "B");
|
||||
map.put("C", "C");
|
||||
map.put("D", "D");
|
||||
map.put("E", "E");
|
||||
map.put("F", "F");
|
||||
map.put("G", "G");
|
||||
map.put("H", "H");
|
||||
map.put("I", "I");
|
||||
map.put("J", "J");
|
||||
map.put("K", "K");
|
||||
map.put("L", "L");
|
||||
map.put("M", "M");
|
||||
map.put("N", "N");
|
||||
map.put("O", "O");
|
||||
map.put("P", "P");
|
||||
map.put("Q", "Q");
|
||||
map.put("R", "R");
|
||||
map.put("S", "S");
|
||||
map.put("T", "T");
|
||||
map.put("U", "U");
|
||||
map.put("V", "V");
|
||||
map.put("W", "W");
|
||||
map.put("X", "X");
|
||||
map.put("Y", "Y");
|
||||
map.put("Z", "Z");
|
||||
map.put(":", ":");
|
||||
map.put("/", "/");
|
||||
map.put("\\", "\\");
|
||||
map.put("1", "1");
|
||||
map.put("2", "2");
|
||||
map.put("3", "3");
|
||||
map.put("4", "4");
|
||||
map.put("5", "5");
|
||||
map.put("6", "6");
|
||||
map.put("7", "7");
|
||||
map.put("8", "8");
|
||||
map.put("9", "9");
|
||||
map.put("0", "0");
|
||||
map.put(".", ".");
|
||||
map.put("-", "-");
|
||||
map.put("_", "_");
|
||||
map.put("@", "@");
|
||||
StringBuilder temp = new StringBuilder();
|
||||
for (int i = 0; i < path.length(); ++i) {
|
||||
if (path.charAt(i) >= '一' && path.charAt(i) <= '龥') {
|
||||
temp.append(path.charAt(i));
|
||||
}
|
||||
if (map.get(path.charAt(i) + "") == null) continue;
|
||||
temp.append((String) map.get(path.charAt(i) + ""));
|
||||
}
|
||||
path = temp.toString();
|
||||
return path;
|
||||
}
|
||||
|
||||
public static String datePaths(String fileName, String... paths) {
|
||||
Calendar calendar = GregorianCalendar.getInstance();
|
||||
ArrayList pathList = Lists.newArrayList((Object[]) paths);
|
||||
pathList.add(String.valueOf(calendar.get(1)));
|
||||
pathList.add(String.valueOf(calendar.get(2) + 1));
|
||||
pathList.add(String.valueOf(calendar.get(5)));
|
||||
String[] pathArray = new String[pathList.size()];
|
||||
pathList.toArray(pathArray);
|
||||
return PathUtils.paths(fileName, pathArray);
|
||||
}
|
||||
|
||||
public static String paths(File dir, String... paths) {
|
||||
if (ArrayUtils.isNotEmpty((Object[]) paths)) {
|
||||
String subPaths = StringUtils.join((Object[]) paths, (char) File.separatorChar);
|
||||
return new File(dir, subPaths).getAbsolutePath();
|
||||
}
|
||||
return PathUtils.checkPathSafe(dir.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
+345
@@ -0,0 +1,345 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import java.beans.BeanInfo;
|
||||
import java.beans.IntrospectionException;
|
||||
import java.beans.Introspector;
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import javax.servlet.ServletInputStream;
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
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(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));
|
||||
}
|
||||
}
|
||||
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
package cn.cloudwalk.service.organization.common;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.cloud.utils.CloudwalkDateUtils;
|
||||
import cn.cloudwalk.service.organization.common.PathUtils;
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.Closeable;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.Enumeration;
|
||||
import java.util.Locale;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
import org.apache.poi.util.IOUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public final class ZipUtil {
|
||||
private static final int BUFFER_SIZE = 0xA00000;
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(ZipUtil.class);
|
||||
|
||||
private ZipUtil() {}
|
||||
|
||||
public static File unzipFile(File file, String encoding) throws Exception {
|
||||
if (file.exists()) {
|
||||
if (file.isFile() && file.getName().toLowerCase(Locale.getDefault()).endsWith(".zip")) {
|
||||
File folder = new File(file.getParentFile(), CloudwalkDateUtils.getUUID());
|
||||
folder.mkdirs();
|
||||
ZipUtil.unzip(file, folder, encoding);
|
||||
return folder;
|
||||
}
|
||||
if (file.isDirectory()) {
|
||||
return file;
|
||||
}
|
||||
}
|
||||
throw new FileNotFoundException();
|
||||
}
|
||||
|
||||
public static void unzip(File zip, File folder, String encoding) throws Exception {
|
||||
InputStream inputStream = null;
|
||||
BufferedInputStream bis = null;
|
||||
FileOutputStream out = null;
|
||||
BufferedOutputStream bos = null;
|
||||
try (ZipFile zipFile = new ZipFile(zip, Charset.forName(encoding)); ) {
|
||||
Enumeration<? extends ZipEntry> emu = zipFile.entries();
|
||||
while (emu.hasMoreElements()) {
|
||||
int count;
|
||||
ZipEntry entry = emu.nextElement();
|
||||
if (entry.isDirectory()) {
|
||||
new File(folder, PathUtils.checkPathSafe(entry.getName())).mkdirs();
|
||||
continue;
|
||||
}
|
||||
inputStream = zipFile.getInputStream(entry);
|
||||
bis = new BufferedInputStream(inputStream);
|
||||
File file = new File(folder, PathUtils.checkPathSafe(entry.getName()));
|
||||
File parent = file.getParentFile();
|
||||
if (parent != null && !parent.exists()) {
|
||||
parent.mkdirs();
|
||||
}
|
||||
out = new FileOutputStream(file);
|
||||
bos = new BufferedOutputStream(out, 0xA00000);
|
||||
byte[] data = new byte[0xA00000];
|
||||
while ((count = bis.read(data, 0, 0xA00000)) != -1) {
|
||||
bos.write(data, 0, count);
|
||||
}
|
||||
bos.flush();
|
||||
IOUtils.closeQuietly((Closeable) bos);
|
||||
IOUtils.closeQuietly((Closeable) bis);
|
||||
IOUtils.closeQuietly((Closeable) out);
|
||||
IOUtils.closeQuietly((Closeable) inputStream);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw e;
|
||||
} finally {
|
||||
IOUtils.closeQuietly(bos);
|
||||
IOUtils.closeQuietly(bis);
|
||||
IOUtils.closeQuietly(out);
|
||||
IOUtils.closeQuietly(inputStream);
|
||||
}
|
||||
}
|
||||
|
||||
public static void zipMultiFile(
|
||||
String filepath, String zipPath, boolean dirFlag, String encoding) {
|
||||
File file = new File(filepath);
|
||||
File zipFile = new File(zipPath);
|
||||
try (FileOutputStream out = new FileOutputStream(zipFile);
|
||||
ZipOutputStream zipOut =
|
||||
new ZipOutputStream((OutputStream) out, Charset.forName(encoding)); ) {
|
||||
if (file.isDirectory()) {
|
||||
File[] files;
|
||||
File[] var11 = files = file.listFiles();
|
||||
int var10 = files.length;
|
||||
for (int var9 = 0; var9 < var10; ++var9) {
|
||||
File fileSec = var11[var9];
|
||||
if (dirFlag) {
|
||||
ZipUtil.recursionZip(zipOut, fileSec, file.getName() + File.separator);
|
||||
continue;
|
||||
}
|
||||
ZipUtil.recursionZip(zipOut, fileSec, "");
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOGGER.error("zipMultiFile exception:{}", (Object) e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static void recursionZip(ZipOutputStream zipOut, File file, String baseDir)
|
||||
throws Exception {
|
||||
if (file.isDirectory()) {
|
||||
File[] files;
|
||||
File[] var7 = files = file.listFiles();
|
||||
int var6 = files.length;
|
||||
for (int len = 0; len < var6; ++len) {
|
||||
File fileSec = var7[len];
|
||||
ZipUtil.recursionZip(zipOut, fileSec, baseDir + file.getName() + File.separator);
|
||||
}
|
||||
} else {
|
||||
byte[] buf = new byte[1024];
|
||||
try (FileInputStream input = new FileInputStream(file); ) {
|
||||
int len;
|
||||
zipOut.putNextEntry(new ZipEntry(baseDir + file.getName()));
|
||||
while ((len = input.read(buf)) != -1) {
|
||||
zipOut.write(buf, 0, len);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOGGER.error("recursionZip exception:{}", (Object) e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
+48
@@ -0,0 +1,48 @@
|
||||
package cn.cloudwalk.service.organization.config;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
|
||||
/** 与 {@code cwos-component-organization-service-v2.9.2_xinghewan.jar} / {@code jar.src} 对齐(非 AutoCloseable)。 */
|
||||
public class ChannelFileReader {
|
||||
private FileInputStream fileIn;
|
||||
private ByteBuffer byteBuf;
|
||||
private long fileLength;
|
||||
private int arraySize;
|
||||
private byte[] array;
|
||||
|
||||
public ChannelFileReader(String fileName, int arraySize) throws IOException {
|
||||
this.fileIn = new FileInputStream(fileName);
|
||||
this.fileLength = this.fileIn.getChannel().size();
|
||||
this.arraySize = arraySize;
|
||||
this.byteBuf = ByteBuffer.allocate(arraySize);
|
||||
}
|
||||
|
||||
public int read() throws IOException {
|
||||
FileChannel fileChannel = this.fileIn.getChannel();
|
||||
int bytes = fileChannel.read(this.byteBuf);
|
||||
if (bytes != -1) {
|
||||
this.array = new byte[bytes];
|
||||
this.byteBuf.flip();
|
||||
this.byteBuf.get(this.array);
|
||||
this.byteBuf.clear();
|
||||
return bytes;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public void close() throws IOException {
|
||||
this.fileIn.close();
|
||||
this.array = null;
|
||||
}
|
||||
|
||||
public byte[] getArray() {
|
||||
return this.array;
|
||||
}
|
||||
|
||||
public long getFileLength() {
|
||||
return this.fileLength;
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package cn.cloudwalk.service.organization.config;
|
||||
|
||||
import java.util.concurrent.RejectedExecutionHandler;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
|
||||
@Configuration
|
||||
public class GroupPersonSynExecutorConfiguration {
|
||||
|
||||
@Autowired private GroupPersonSynPoolProperties poolProperties;
|
||||
|
||||
@Bean(name = "groupPersonSynExecutor")
|
||||
public ThreadPoolTaskExecutor groupPersonSynExecutor() {
|
||||
ThreadPoolTaskExecutor exec = new ThreadPoolTaskExecutor();
|
||||
exec.setCorePoolSize(poolProperties.getCorePoolSize());
|
||||
exec.setMaxPoolSize(poolProperties.getMaxPoolSize());
|
||||
exec.setQueueCapacity(poolProperties.getQueueCapacity());
|
||||
exec.setKeepAliveSeconds(poolProperties.getKeepAliveSeconds());
|
||||
exec.setAllowCoreThreadTimeOut(poolProperties.isAllowCoreThreadTimeOut());
|
||||
exec.setThreadNamePrefix("group-person-syn-");
|
||||
exec.setRejectedExecutionHandler((RejectedExecutionHandler) new ThreadPoolExecutor.AbortPolicy());
|
||||
exec.initialize();
|
||||
return exec;
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package cn.cloudwalk.service.organization.config;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "ninca.group.person.syn.pool")
|
||||
public class GroupPersonSynPoolProperties {
|
||||
|
||||
private int corePoolSize = 16;
|
||||
private int maxPoolSize = 32;
|
||||
private int keepAliveSeconds = 150;
|
||||
private int queueCapacity = 1000;
|
||||
private boolean allowCoreThreadTimeOut = true;
|
||||
|
||||
public int getCorePoolSize() {
|
||||
return corePoolSize;
|
||||
}
|
||||
|
||||
public void setCorePoolSize(int corePoolSize) {
|
||||
this.corePoolSize = corePoolSize;
|
||||
}
|
||||
|
||||
public int getMaxPoolSize() {
|
||||
return maxPoolSize;
|
||||
}
|
||||
|
||||
public void setMaxPoolSize(int maxPoolSize) {
|
||||
this.maxPoolSize = maxPoolSize;
|
||||
}
|
||||
|
||||
public int getKeepAliveSeconds() {
|
||||
return keepAliveSeconds;
|
||||
}
|
||||
|
||||
public void setKeepAliveSeconds(int keepAliveSeconds) {
|
||||
this.keepAliveSeconds = keepAliveSeconds;
|
||||
}
|
||||
|
||||
public int getQueueCapacity() {
|
||||
return queueCapacity;
|
||||
}
|
||||
|
||||
public void setQueueCapacity(int queueCapacity) {
|
||||
this.queueCapacity = queueCapacity;
|
||||
}
|
||||
|
||||
public boolean isAllowCoreThreadTimeOut() {
|
||||
return allowCoreThreadTimeOut;
|
||||
}
|
||||
|
||||
public void setAllowCoreThreadTimeOut(boolean allowCoreThreadTimeOut) {
|
||||
this.allowCoreThreadTimeOut = allowCoreThreadTimeOut;
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package cn.cloudwalk.service.organization.config;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.service.organization.service.common.RequestAttributeHystrixConcurrencyStrategy;
|
||||
import com.netflix.hystrix.Hystrix;
|
||||
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ConditionalOnClass(value = {Hystrix.class})
|
||||
public class HystrixStrategyAutoConfiguration {
|
||||
@Bean
|
||||
public HystrixConcurrencyStrategy hystrixConcurrencyStrategy() {
|
||||
return new RequestAttributeHystrixConcurrencyStrategy();
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package cn.cloudwalk.service.organization.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.data.redis.core.script.DefaultRedisScript;
|
||||
|
||||
/**
|
||||
* 为 CpImageStorePerson* 管理类提供 Redis Lua 脚本 Bean(字段名与 Bean 名一致,供 @Autowired 注入)。
|
||||
*/
|
||||
@Configuration
|
||||
public class OrganizationRedisLuaConfiguration {
|
||||
|
||||
@Bean
|
||||
public DefaultRedisScript<String> lockValidateJobRedisScript() {
|
||||
return script("lua/lockValidateJobRedisScript.lua");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DefaultRedisScript<String> unlockValidateJobRedisScript() {
|
||||
return script("lua/unlockValidateJobRedisScript.lua");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DefaultRedisScript<String> addWaitSynTaskRedisScript() {
|
||||
return script("lua/addWaitSynTaskRedisScript.lua");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DefaultRedisScript<String> lockHandleSynTaskRedisScript() {
|
||||
return script("lua/lockHandleSynTaskRedisScript.lua");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DefaultRedisScript<String> lockHeadSynTaskRedisScript() {
|
||||
return script("lua/lockHeadSynTaskRedisScript.lua");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DefaultRedisScript<String> handleSuccessSynTaskRedisScript() {
|
||||
return script("lua/handleSuccessSynTaskRedisScript.lua");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DefaultRedisScript<String> handleFailSynTaskRedisScript() {
|
||||
return script("lua/handleFailSynTaskRedisScript.lua");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DefaultRedisScript<String> refreshHandleSynTaskRedisScript() {
|
||||
return script("lua/refreshHandleSynTaskRedisScript.lua");
|
||||
}
|
||||
|
||||
private static DefaultRedisScript<String> script(String classPath) {
|
||||
DefaultRedisScript<String> s = new DefaultRedisScript<>();
|
||||
s.setLocation(new ClassPathResource(classPath));
|
||||
s.setResultType(String.class);
|
||||
return s;
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package cn.cloudwalk.service.organization.config;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.service.organization.config.PersonImportTaskExecutorProperties;
|
||||
import java.util.concurrent.RejectedExecutionHandler;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
|
||||
@Configuration
|
||||
public class PersonImportTaskExecutor {
|
||||
@Autowired private PersonImportTaskExecutorProperties personImportTaskExecutorProperties;
|
||||
|
||||
@Bean(name = {"personImportExecutor"})
|
||||
public ThreadPoolTaskExecutor fileSaveExecutor() {
|
||||
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
|
||||
threadPoolTaskExecutor.setCorePoolSize(
|
||||
this.personImportTaskExecutorProperties.getCorePoolSize());
|
||||
threadPoolTaskExecutor.setAllowCoreThreadTimeOut(
|
||||
this.personImportTaskExecutorProperties.isAllowCoreThreadTimeOut());
|
||||
threadPoolTaskExecutor.setMaxPoolSize(this.personImportTaskExecutorProperties.getMaxPoolSize());
|
||||
threadPoolTaskExecutor.setQueueCapacity(
|
||||
this.personImportTaskExecutorProperties.getQueueCapacity());
|
||||
threadPoolTaskExecutor.setThreadNamePrefix("guard-control-pool-");
|
||||
threadPoolTaskExecutor.setRejectedExecutionHandler(
|
||||
(RejectedExecutionHandler) new ThreadPoolExecutor.AbortPolicy());
|
||||
threadPoolTaskExecutor.initialize();
|
||||
return threadPoolTaskExecutor;
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package cn.cloudwalk.service.organization.config;
|
||||
|
||||
// 业务服务
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "cwos.person.import.pool")
|
||||
public class PersonImportTaskExecutorProperties {
|
||||
private int corePoolSize = 3;
|
||||
private int maxPoolSize = 3;
|
||||
private int keepAliveSeconds = 60;
|
||||
private int queueCapacity = 100;
|
||||
private boolean allowCoreThreadTimeOut = true;
|
||||
|
||||
public int getCorePoolSize() {
|
||||
return this.corePoolSize;
|
||||
}
|
||||
|
||||
public void setCorePoolSize(int corePoolSize) {
|
||||
this.corePoolSize = corePoolSize;
|
||||
}
|
||||
|
||||
public int getMaxPoolSize() {
|
||||
return this.maxPoolSize;
|
||||
}
|
||||
|
||||
public void setMaxPoolSize(int maxPoolSize) {
|
||||
this.maxPoolSize = maxPoolSize;
|
||||
}
|
||||
|
||||
public int getKeepAliveSeconds() {
|
||||
return this.keepAliveSeconds;
|
||||
}
|
||||
|
||||
public void setKeepAliveSeconds(int keepAliveSeconds) {
|
||||
this.keepAliveSeconds = keepAliveSeconds;
|
||||
}
|
||||
|
||||
public int getQueueCapacity() {
|
||||
return this.queueCapacity;
|
||||
}
|
||||
|
||||
public void setQueueCapacity(int queueCapacity) {
|
||||
this.queueCapacity = queueCapacity;
|
||||
}
|
||||
|
||||
public boolean isAllowCoreThreadTimeOut() {
|
||||
return this.allowCoreThreadTimeOut;
|
||||
}
|
||||
|
||||
public void setAllowCoreThreadTimeOut(boolean allowCoreThreadTimeOut) {
|
||||
this.allowCoreThreadTimeOut = allowCoreThreadTimeOut;
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package cn.cloudwalk.service.organization.config;
|
||||
|
||||
// 业务服务
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "ninca.picture.revision.pool")
|
||||
public class PictureRevisionPoolProperties {
|
||||
private int corePoolSize = 3;
|
||||
private int maxPoolSize = 5;
|
||||
private int keepAliveSeconds = 150;
|
||||
private int queueCapacity = 100;
|
||||
private boolean allowCoreThreadTimeOut = true;
|
||||
|
||||
public int getCorePoolSize() {
|
||||
return this.corePoolSize;
|
||||
}
|
||||
|
||||
public void setCorePoolSize(int corePoolSize) {
|
||||
this.corePoolSize = corePoolSize;
|
||||
}
|
||||
|
||||
public int getMaxPoolSize() {
|
||||
return this.maxPoolSize;
|
||||
}
|
||||
|
||||
public void setMaxPoolSize(int maxPoolSize) {
|
||||
this.maxPoolSize = maxPoolSize;
|
||||
}
|
||||
|
||||
public int getKeepAliveSeconds() {
|
||||
return this.keepAliveSeconds;
|
||||
}
|
||||
|
||||
public void setKeepAliveSeconds(int keepAliveSeconds) {
|
||||
this.keepAliveSeconds = keepAliveSeconds;
|
||||
}
|
||||
|
||||
public int getQueueCapacity() {
|
||||
return this.queueCapacity;
|
||||
}
|
||||
|
||||
public void setQueueCapacity(int queueCapacity) {
|
||||
this.queueCapacity = queueCapacity;
|
||||
}
|
||||
|
||||
public boolean isAllowCoreThreadTimeOut() {
|
||||
return this.allowCoreThreadTimeOut;
|
||||
}
|
||||
|
||||
public void setAllowCoreThreadTimeOut(boolean allowCoreThreadTimeOut) {
|
||||
this.allowCoreThreadTimeOut = allowCoreThreadTimeOut;
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package cn.cloudwalk.service.organization.config;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.service.organization.config.PictureRevisionPoolProperties;
|
||||
import java.util.concurrent.RejectedExecutionHandler;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
|
||||
@Configuration
|
||||
public class PictureRevisionTaskExecutor {
|
||||
@Autowired private PictureRevisionPoolProperties pictureRevisionPoolProperties;
|
||||
|
||||
@Bean(name = {"pictureRevisionExecutor"})
|
||||
public ThreadPoolTaskExecutor pictureRevisionTaskExecutor() {
|
||||
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
|
||||
threadPoolTaskExecutor.setCorePoolSize(this.pictureRevisionPoolProperties.getCorePoolSize());
|
||||
threadPoolTaskExecutor.setAllowCoreThreadTimeOut(
|
||||
this.pictureRevisionPoolProperties.isAllowCoreThreadTimeOut());
|
||||
threadPoolTaskExecutor.setMaxPoolSize(this.pictureRevisionPoolProperties.getMaxPoolSize());
|
||||
threadPoolTaskExecutor.setQueueCapacity(this.pictureRevisionPoolProperties.getQueueCapacity());
|
||||
threadPoolTaskExecutor.setThreadNamePrefix("picture-revision-pool-");
|
||||
threadPoolTaskExecutor.setRejectedExecutionHandler(
|
||||
(RejectedExecutionHandler) new ThreadPoolExecutor.AbortPolicy());
|
||||
threadPoolTaskExecutor.initialize();
|
||||
return threadPoolTaskExecutor;
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package cn.cloudwalk.service.organization.config;
|
||||
|
||||
// 业务服务
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "ninca.sync.log.pool")
|
||||
public class SaveSyncLogPoolProperties {
|
||||
private int corePoolSize = 3;
|
||||
private int maxPoolSize = 5;
|
||||
private int keepAliveSeconds = 150;
|
||||
private int queueCapacity = 100;
|
||||
private boolean allowCoreThreadTimeOut = true;
|
||||
|
||||
public int getCorePoolSize() {
|
||||
return this.corePoolSize;
|
||||
}
|
||||
|
||||
public void setCorePoolSize(int corePoolSize) {
|
||||
this.corePoolSize = corePoolSize;
|
||||
}
|
||||
|
||||
public int getMaxPoolSize() {
|
||||
return this.maxPoolSize;
|
||||
}
|
||||
|
||||
public void setMaxPoolSize(int maxPoolSize) {
|
||||
this.maxPoolSize = maxPoolSize;
|
||||
}
|
||||
|
||||
public int getKeepAliveSeconds() {
|
||||
return this.keepAliveSeconds;
|
||||
}
|
||||
|
||||
public void setKeepAliveSeconds(int keepAliveSeconds) {
|
||||
this.keepAliveSeconds = keepAliveSeconds;
|
||||
}
|
||||
|
||||
public int getQueueCapacity() {
|
||||
return this.queueCapacity;
|
||||
}
|
||||
|
||||
public void setQueueCapacity(int queueCapacity) {
|
||||
this.queueCapacity = queueCapacity;
|
||||
}
|
||||
|
||||
public boolean isAllowCoreThreadTimeOut() {
|
||||
return this.allowCoreThreadTimeOut;
|
||||
}
|
||||
|
||||
public void setAllowCoreThreadTimeOut(boolean allowCoreThreadTimeOut) {
|
||||
this.allowCoreThreadTimeOut = allowCoreThreadTimeOut;
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package cn.cloudwalk.service.organization.config;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.service.organization.config.SaveSyncLogPoolProperties;
|
||||
import java.util.concurrent.RejectedExecutionHandler;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
|
||||
@Configuration
|
||||
public class SaveSyncLogTaskExecutor {
|
||||
@Autowired private SaveSyncLogPoolProperties saveSyncLogPoolProperties;
|
||||
|
||||
@Bean(name = {"saveSyncLogExecutor"})
|
||||
public ThreadPoolTaskExecutor saveSyncLogTaskExecutor() {
|
||||
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
|
||||
threadPoolTaskExecutor.setCorePoolSize(this.saveSyncLogPoolProperties.getCorePoolSize());
|
||||
threadPoolTaskExecutor.setAllowCoreThreadTimeOut(
|
||||
this.saveSyncLogPoolProperties.isAllowCoreThreadTimeOut());
|
||||
threadPoolTaskExecutor.setMaxPoolSize(this.saveSyncLogPoolProperties.getMaxPoolSize());
|
||||
threadPoolTaskExecutor.setQueueCapacity(this.saveSyncLogPoolProperties.getQueueCapacity());
|
||||
threadPoolTaskExecutor.setThreadNamePrefix("sync-log-pool-");
|
||||
threadPoolTaskExecutor.setRejectedExecutionHandler(
|
||||
(RejectedExecutionHandler) new ThreadPoolExecutor.AbortPolicy());
|
||||
threadPoolTaskExecutor.initialize();
|
||||
return threadPoolTaskExecutor;
|
||||
}
|
||||
}
|
||||
+546
@@ -0,0 +1,546 @@
|
||||
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;
|
||||
import cn.cloudwalk.client.organization.param.ExportLabelTaskParam;
|
||||
import cn.cloudwalk.client.organization.param.ExportOrgTaskParam;
|
||||
import cn.cloudwalk.client.organization.param.ExportRecordTaskParam;
|
||||
import cn.cloudwalk.client.organization.param.PageLabelParam;
|
||||
import cn.cloudwalk.client.organization.param.organization.QueryOrganizationParam;
|
||||
import cn.cloudwalk.client.organization.personimg.param.QueryImgPersonParam;
|
||||
import cn.cloudwalk.client.organization.personimg.result.ImgPersonProGetResult;
|
||||
import cn.cloudwalk.client.organization.personimg.result.ImgStorePersonGetResult;
|
||||
import cn.cloudwalk.client.organization.personimg.service.ImgStorePersonPropertiesService;
|
||||
import cn.cloudwalk.client.organization.personimg.service.ImgStorePersonService;
|
||||
import cn.cloudwalk.client.organization.result.PageLabelResult;
|
||||
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;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
private void uploadFile(String businessId, String fileId, String zipPathStr) throws IOException {
|
||||
ChannelFileReader reader = new ChannelFileReader(zipPathStr, this.shardingSize);
|
||||
try {
|
||||
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);
|
||||
} finally {
|
||||
reader.close();
|
||||
}
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
package cn.cloudwalk.service.organization.export;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.result.PageLabelResult;
|
||||
import cn.cloudwalk.client.organization.result.PersonProListResult;
|
||||
import cn.cloudwalk.client.organization.service.ICommonAppDownloadCenterService;
|
||||
import cn.cloudwalk.intelligent.davinci.storage.manager.FileStorageManager;
|
||||
import cn.cloudwalk.service.organization.common.CommonDownloadDataConfig;
|
||||
import cn.cloudwalk.service.organization.common.FolderUtil;
|
||||
import cn.cloudwalk.service.organization.export.CommonRecordExcelByLabelCreater;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.attribute.FileAttribute;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.IntStream;
|
||||
import net.lingala.zip4j.ZipFile;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class CommonAppExportFileByLabelHandler {
|
||||
private static final Logger log =
|
||||
LoggerFactory.getLogger(CommonAppExportFileByLabelHandler.class);
|
||||
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
private static final DateTimeFormatter DIR_DATE_FORMAT =
|
||||
DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
|
||||
private String type;
|
||||
private String fileId;
|
||||
private Map<String, List<PageLabelResult>> dataMap;
|
||||
private CommonDownloadDataConfig commonDownloadDataConfig;
|
||||
private ICommonAppDownloadCenterService iCommonAppDownloadCenterService;
|
||||
private PersonProListResult personProListResult;
|
||||
private FileStorageManager fileStorageManager;
|
||||
private String businessId;
|
||||
|
||||
public CommonAppExportFileByLabelHandler(
|
||||
String businessId,
|
||||
String fileName,
|
||||
String fileId,
|
||||
Map<String, List<PageLabelResult>> dataList,
|
||||
CommonDownloadDataConfig commonDownloadDataConfig,
|
||||
FileStorageManager manager,
|
||||
ICommonAppDownloadCenterService service,
|
||||
PersonProListResult personProListResult) {
|
||||
this.type = fileName;
|
||||
this.fileId = fileId;
|
||||
this.dataMap = dataList;
|
||||
this.commonDownloadDataConfig = commonDownloadDataConfig;
|
||||
this.fileStorageManager = manager;
|
||||
this.iCommonAppDownloadCenterService = service;
|
||||
this.businessId = businessId;
|
||||
this.personProListResult = personProListResult;
|
||||
}
|
||||
|
||||
public Path process() throws IOException {
|
||||
String fileName = LocalDateTime.now().format(DIR_DATE_FORMAT);
|
||||
Path zipDir =
|
||||
Paths.get(
|
||||
this.commonDownloadDataConfig.getDownDir() + File.separator + fileName, new String[0]);
|
||||
Files.createDirectories(zipDir, new FileAttribute[0]);
|
||||
this.createExcelFromDataMap(zipDir);
|
||||
this.zipFile(fileName);
|
||||
FolderUtil.deleteFolder(zipDir.toString());
|
||||
return Paths.get(zipDir + this.commonDownloadDataConfig.getCompressionType(), new String[0]);
|
||||
}
|
||||
|
||||
private void createExcelFromDataMap(Path zipDir) {
|
||||
this.dataMap.forEach(
|
||||
(k, v) -> {
|
||||
int subCount =
|
||||
v.size() % this.commonDownloadDataConfig.getExcelMaxRows() == 0
|
||||
? v.size() / this.commonDownloadDataConfig.getExcelMaxRows()
|
||||
: v.size() / this.commonDownloadDataConfig.getExcelMaxRows() + 1;
|
||||
IntStream.range(0, subCount)
|
||||
.forEach(
|
||||
i -> {
|
||||
int status =
|
||||
this.iCommonAppDownloadCenterService.queryDownloadStatus(
|
||||
this.businessId, this.fileId);
|
||||
if (status > 1) {
|
||||
this.logger.info("下载中心已取消下载文件,fileId = {}", (Object) this.fileId);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
int endIndex =
|
||||
Math.min(
|
||||
(i + 1) * this.commonDownloadDataConfig.getExcelMaxRows(), v.size());
|
||||
String dirPath =
|
||||
zipDir.toString()
|
||||
+ File.separator
|
||||
+ k
|
||||
+ File.separator
|
||||
+ LocalDate.now().format(DATE_FORMAT);
|
||||
int index = i * this.commonDownloadDataConfig.getExcelMaxRows() + 1;
|
||||
CommonRecordExcelByLabelCreater.getCreater(
|
||||
v.subList(
|
||||
i * this.commonDownloadDataConfig.getExcelMaxRows(), endIndex),
|
||||
dirPath,
|
||||
index,
|
||||
this.personProListResult)
|
||||
.createFile();
|
||||
} catch (Exception e) {
|
||||
this.logger.error("创建Excel文件失败:{}", e);
|
||||
throw new RuntimeException("记录生成Excel文件异常");
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public void zipFile(String fileName) {
|
||||
String downloadPath = this.commonDownloadDataConfig.getDownDir();
|
||||
try {
|
||||
String filePath = downloadPath + File.separator + fileName;
|
||||
String zipFile = filePath + ".zip";
|
||||
new ZipFile(zipFile).addFolder(new File(filePath));
|
||||
} catch (Exception e) {
|
||||
this.logger.error(
|
||||
"压缩人员导出文件,执行报错 {}: {}", (Object) e.getClass().getName(), (Object) e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
package cn.cloudwalk.service.organization.export;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.result.PersonProListResult;
|
||||
import cn.cloudwalk.client.organization.service.ICommonAppDownloadCenterService;
|
||||
import cn.cloudwalk.client.organization.service.store.result.OrganizationResult;
|
||||
import cn.cloudwalk.intelligent.davinci.storage.manager.FileStorageManager;
|
||||
import cn.cloudwalk.service.organization.common.CommonDownloadDataConfig;
|
||||
import cn.cloudwalk.service.organization.common.FolderUtil;
|
||||
import cn.cloudwalk.service.organization.export.CommonRecordExcelByOrgCreater;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.attribute.FileAttribute;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.IntStream;
|
||||
import net.lingala.zip4j.ZipFile;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class CommonAppExportFileByOrgHandler {
|
||||
private static final Logger log = LoggerFactory.getLogger(CommonAppExportFileByOrgHandler.class);
|
||||
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
private static final DateTimeFormatter DIR_DATE_FORMAT =
|
||||
DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
|
||||
private String type;
|
||||
private String fileId;
|
||||
private Map<String, List<OrganizationResult>> dataMap;
|
||||
private CommonDownloadDataConfig commonDownloadDataConfig;
|
||||
private ICommonAppDownloadCenterService iCommonAppDownloadCenterService;
|
||||
private PersonProListResult personProListResult;
|
||||
private FileStorageManager fileStorageManager;
|
||||
private String businessId;
|
||||
|
||||
public CommonAppExportFileByOrgHandler(
|
||||
String businessId,
|
||||
String fileName,
|
||||
String fileId,
|
||||
Map<String, List<OrganizationResult>> dataList,
|
||||
CommonDownloadDataConfig commonDownloadDataConfig,
|
||||
FileStorageManager manager,
|
||||
ICommonAppDownloadCenterService service,
|
||||
PersonProListResult personProListResult) {
|
||||
this.type = fileName;
|
||||
this.fileId = fileId;
|
||||
this.dataMap = dataList;
|
||||
this.commonDownloadDataConfig = commonDownloadDataConfig;
|
||||
this.fileStorageManager = manager;
|
||||
this.iCommonAppDownloadCenterService = service;
|
||||
this.businessId = businessId;
|
||||
this.personProListResult = personProListResult;
|
||||
}
|
||||
|
||||
public Path process() throws IOException {
|
||||
String fileName = LocalDateTime.now().format(DIR_DATE_FORMAT);
|
||||
Path zipDir =
|
||||
Paths.get(
|
||||
this.commonDownloadDataConfig.getDownDir() + File.separator + fileName, new String[0]);
|
||||
Files.createDirectories(zipDir, new FileAttribute[0]);
|
||||
this.createExcelFromDataMap(zipDir);
|
||||
this.zipFile(fileName);
|
||||
FolderUtil.deleteFolder(zipDir.toString());
|
||||
return Paths.get(zipDir + this.commonDownloadDataConfig.getCompressionType(), new String[0]);
|
||||
}
|
||||
|
||||
private void createExcelFromDataMap(Path zipDir) {
|
||||
this.dataMap.forEach(
|
||||
(k, v) -> {
|
||||
int subCount =
|
||||
v.size() % this.commonDownloadDataConfig.getExcelMaxRows() == 0
|
||||
? v.size() / this.commonDownloadDataConfig.getExcelMaxRows()
|
||||
: v.size() / this.commonDownloadDataConfig.getExcelMaxRows() + 1;
|
||||
IntStream.range(0, subCount)
|
||||
.forEach(
|
||||
i -> {
|
||||
int status =
|
||||
this.iCommonAppDownloadCenterService.queryDownloadStatus(
|
||||
this.businessId, this.fileId);
|
||||
if (status > 1) {
|
||||
this.logger.info("下载中心已取消下载文件,fileId = {}", (Object) this.fileId);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
int endIndex =
|
||||
Math.min(
|
||||
(i + 1) * this.commonDownloadDataConfig.getExcelMaxRows(), v.size());
|
||||
String dirPath =
|
||||
zipDir.toString()
|
||||
+ File.separator
|
||||
+ k
|
||||
+ File.separator
|
||||
+ LocalDate.now().format(DATE_FORMAT);
|
||||
int index = i * this.commonDownloadDataConfig.getExcelMaxRows() + 1;
|
||||
CommonRecordExcelByOrgCreater.getCreater(
|
||||
v.subList(
|
||||
i * this.commonDownloadDataConfig.getExcelMaxRows(), endIndex),
|
||||
dirPath,
|
||||
index,
|
||||
this.personProListResult)
|
||||
.createFile();
|
||||
} catch (Exception e) {
|
||||
this.logger.error("创建Excel文件失败:{}", e);
|
||||
throw new RuntimeException("记录生成Excel文件异常");
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public void zipFile(String fileName) {
|
||||
String downloadPath = this.commonDownloadDataConfig.getDownDir();
|
||||
try {
|
||||
String filePath = downloadPath + File.separator + fileName;
|
||||
String zipFile = filePath + ".zip";
|
||||
new ZipFile(zipFile).addFolder(new File(filePath));
|
||||
} catch (Exception e) {
|
||||
this.logger.error(
|
||||
"压缩人员导出文件,执行报错 {}: {}", (Object) e.getClass().getName(), (Object) e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
package cn.cloudwalk.service.organization.export;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.personimg.result.ImgStorePersonGetResult;
|
||||
import cn.cloudwalk.client.organization.result.PersonProListResult;
|
||||
import cn.cloudwalk.client.organization.service.ICommonAppDownloadCenterService;
|
||||
import cn.cloudwalk.intelligent.davinci.storage.manager.FileStorageManager;
|
||||
import cn.cloudwalk.service.organization.common.CommonDownloadDataConfig;
|
||||
import cn.cloudwalk.service.organization.common.FolderUtil;
|
||||
import cn.cloudwalk.service.organization.export.CommonRecordExcelCreater;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.attribute.FileAttribute;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.IntStream;
|
||||
import net.lingala.zip4j.ZipFile;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class CommonAppExportFileHandler {
|
||||
private static final Logger log = LoggerFactory.getLogger(CommonAppExportFileHandler.class);
|
||||
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
private static final DateTimeFormatter DIR_DATE_FORMAT =
|
||||
DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
|
||||
private String type;
|
||||
private String fileId;
|
||||
private Map<String, List<ImgStorePersonGetResult>> dataMap;
|
||||
private CommonDownloadDataConfig commonDownloadDataConfig;
|
||||
private ICommonAppDownloadCenterService iCommonAppDownloadCenterService;
|
||||
private PersonProListResult personProListResult;
|
||||
private FileStorageManager fileStorageManager;
|
||||
private String businessId;
|
||||
|
||||
public CommonAppExportFileHandler(
|
||||
String businessId,
|
||||
String fileName,
|
||||
String fileId,
|
||||
Map<String, List<ImgStorePersonGetResult>> dataList,
|
||||
CommonDownloadDataConfig commonDownloadDataConfig,
|
||||
FileStorageManager manager,
|
||||
ICommonAppDownloadCenterService service,
|
||||
PersonProListResult personProListResult) {
|
||||
this.type = fileName;
|
||||
this.fileId = fileId;
|
||||
this.dataMap = dataList;
|
||||
this.commonDownloadDataConfig = commonDownloadDataConfig;
|
||||
this.fileStorageManager = manager;
|
||||
this.iCommonAppDownloadCenterService = service;
|
||||
this.businessId = businessId;
|
||||
this.personProListResult = personProListResult;
|
||||
}
|
||||
|
||||
public Path process() throws IOException {
|
||||
String fileName = LocalDateTime.now().format(DIR_DATE_FORMAT);
|
||||
Path zipDir =
|
||||
Paths.get(
|
||||
this.commonDownloadDataConfig.getDownDir() + File.separator + fileName, new String[0]);
|
||||
Files.createDirectories(zipDir, new FileAttribute[0]);
|
||||
this.createExcelFromDataMap(zipDir);
|
||||
this.zipFile(fileName);
|
||||
FolderUtil.deleteFolder(zipDir.toString());
|
||||
return Paths.get(zipDir + this.commonDownloadDataConfig.getCompressionType(), new String[0]);
|
||||
}
|
||||
|
||||
private void createExcelFromDataMap(Path zipDir) {
|
||||
this.dataMap.forEach(
|
||||
(k, v) -> {
|
||||
int subCount =
|
||||
v.size() % this.commonDownloadDataConfig.getExcelMaxRows() == 0
|
||||
? v.size() / this.commonDownloadDataConfig.getExcelMaxRows()
|
||||
: v.size() / this.commonDownloadDataConfig.getExcelMaxRows() + 1;
|
||||
IntStream.range(0, subCount)
|
||||
.forEach(
|
||||
i -> {
|
||||
int status =
|
||||
this.iCommonAppDownloadCenterService.queryDownloadStatus(
|
||||
this.businessId, this.fileId);
|
||||
if (status > 1) {
|
||||
this.logger.info("下载中心已取消下载文件,fileId = {}", (Object) this.fileId);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
int endIndex =
|
||||
Math.min(
|
||||
(i + 1) * this.commonDownloadDataConfig.getExcelMaxRows(), v.size());
|
||||
String dirPath =
|
||||
zipDir.toString()
|
||||
+ File.separator
|
||||
+ k
|
||||
+ File.separator
|
||||
+ LocalDate.now().format(DATE_FORMAT);
|
||||
int index = i * this.commonDownloadDataConfig.getExcelMaxRows() + 1;
|
||||
CommonRecordExcelCreater.getCreater(
|
||||
v.subList(
|
||||
i * this.commonDownloadDataConfig.getExcelMaxRows(), endIndex),
|
||||
dirPath,
|
||||
index,
|
||||
this.fileStorageManager,
|
||||
this.personProListResult,
|
||||
this.commonDownloadDataConfig.getHasContainImage())
|
||||
.createFile();
|
||||
} catch (Exception e) {
|
||||
this.logger.error("创建Excel文件失败:{}", (Object) e.getMessage());
|
||||
throw new RuntimeException("记录生成Excel文件异常");
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public void zipFile(String fileName) {
|
||||
String downloadPath = this.commonDownloadDataConfig.getDownDir();
|
||||
try {
|
||||
String filePath = downloadPath + File.separator + fileName;
|
||||
String zipFile = filePath + ".zip";
|
||||
new ZipFile(zipFile).addFolder(new File(filePath));
|
||||
} catch (Exception e) {
|
||||
this.logger.error(
|
||||
"压缩人员导出文件,执行报错 {}: {}", (Object) e.getClass().getName(), (Object) e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package cn.cloudwalk.service.organization.export;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.result.PageLabelResult;
|
||||
import cn.cloudwalk.client.organization.result.PersonProListResult;
|
||||
import cn.cloudwalk.service.organization.export.CommonRecordExcelByLabelCreater;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import org.apache.poi.ss.util.CellRangeAddress;
|
||||
import org.apache.poi.xssf.usermodel.XSSFRow;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
public class CommonExRecordExcelByLabelCreater extends CommonRecordExcelByLabelCreater {
|
||||
private static final Logger log =
|
||||
LoggerFactory.getLogger(CommonExRecordExcelByLabelCreater.class);
|
||||
|
||||
public CommonExRecordExcelByLabelCreater(
|
||||
List<PageLabelResult> records,
|
||||
String filePath,
|
||||
int index,
|
||||
PersonProListResult personProListResult) {
|
||||
super(records, filePath, index);
|
||||
this.personProListResult = personProListResult;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void createTitleRow() {
|
||||
XSSFRow titleRow = this.sheet.createRow(2);
|
||||
int columnNum = 0;
|
||||
this.createHeadCell(titleRow, columnNum, "标签名称");
|
||||
this.createHeadCell(titleRow, ++columnNum, "标签id");
|
||||
this.createHeadCell(titleRow, ++columnNum, "标签编号");
|
||||
this.createHeadCell(titleRow, ++columnNum, "人员数量");
|
||||
this.createHeadCell(titleRow, ++columnNum, "标签类型:0-手动创建,1-应用初始,2-应用创建");
|
||||
this.createHeadCell(titleRow, ++columnNum, "门禁设备(在线)");
|
||||
this.createHeadCell(titleRow, ++columnNum, "门禁设备(离线)");
|
||||
this.createHeadCell(titleRow, ++columnNum, "派梯楼层权限");
|
||||
this.sheet.setColumnWidth(1, 5000);
|
||||
this.sheet.setColumnWidth(3, 4000);
|
||||
this.createInfoRow(columnNum);
|
||||
}
|
||||
|
||||
private void createInfoRow(int columnNum) {
|
||||
XSSFRow row0 = this.sheet.createRow(0);
|
||||
this.createHeadCell(row0, 0, "default-标签批量导出模板");
|
||||
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;
|
||||
PageLabelResult commonRecord = (PageLabelResult) 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.getId());
|
||||
row.createCell(2).setCellValue(commonRecord.getCode());
|
||||
row.createCell(3).setCellValue((double) commonRecord.getPersonCount().intValue());
|
||||
row.createCell(4).setCellValue((double) commonRecord.getAddType().shortValue());
|
||||
row.createCell(5).setCellValue(commonRecord.getOnlineDevices());
|
||||
row.createCell(6).setCellValue(commonRecord.getOfflineDevices());
|
||||
row.createCell(7).setCellValue(commonRecord.getFloorNames());
|
||||
}
|
||||
long end = System.currentTimeMillis();
|
||||
this.logger.info("导出excel总耗时:{}", (Object) (end - start));
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package cn.cloudwalk.service.organization.export;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.result.PersonProListResult;
|
||||
import cn.cloudwalk.client.organization.service.store.result.OrganizationResult;
|
||||
import cn.cloudwalk.service.organization.export.CommonRecordExcelByOrgCreater;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import org.apache.poi.ss.util.CellRangeAddress;
|
||||
import org.apache.poi.xssf.usermodel.XSSFRow;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
public class CommonExRecordExcelByOrgCreater extends CommonRecordExcelByOrgCreater {
|
||||
private static final Logger log = LoggerFactory.getLogger(CommonExRecordExcelByOrgCreater.class);
|
||||
|
||||
public CommonExRecordExcelByOrgCreater(
|
||||
List<OrganizationResult> records,
|
||||
String filePath,
|
||||
int index,
|
||||
PersonProListResult personProListResult) {
|
||||
super(records, filePath, index);
|
||||
this.personProListResult = personProListResult;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void createTitleRow() {
|
||||
XSSFRow titleRow = this.sheet.createRow(2);
|
||||
int columnNum = 0;
|
||||
this.createHeadCell(titleRow, columnNum, "机构名称");
|
||||
this.createHeadCell(titleRow, ++columnNum, "机构id");
|
||||
this.createHeadCell(titleRow, ++columnNum, "机构类型");
|
||||
this.createHeadCell(titleRow, ++columnNum, "人员数量");
|
||||
this.createHeadCell(titleRow, ++columnNum, "状态:0-已启用");
|
||||
this.createHeadCell(titleRow, ++columnNum, "门禁设备(在线)");
|
||||
this.createHeadCell(titleRow, ++columnNum, "门禁设备(离线)");
|
||||
this.createHeadCell(titleRow, ++columnNum, "派梯楼层权限");
|
||||
this.sheet.setColumnWidth(1, 5000);
|
||||
this.sheet.setColumnWidth(3, 4000);
|
||||
this.createInfoRow(columnNum);
|
||||
}
|
||||
|
||||
private void createInfoRow(int columnNum) {
|
||||
XSSFRow row0 = this.sheet.createRow(0);
|
||||
this.createHeadCell(row0, 0, "default-机构批量导出模板");
|
||||
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;
|
||||
OrganizationResult commonRecord = (OrganizationResult) 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.getId());
|
||||
row.createCell(2).setCellValue(commonRecord.getType());
|
||||
row.createCell(3).setCellValue((double) commonRecord.getPersonCount().intValue());
|
||||
row.createCell(4).setCellValue((double) commonRecord.getIsDel().shortValue());
|
||||
row.createCell(5).setCellValue(commonRecord.getOnlineDevices());
|
||||
row.createCell(6).setCellValue(commonRecord.getOfflineDevices());
|
||||
row.createCell(7).setCellValue(commonRecord.getFloorNames());
|
||||
}
|
||||
long end = System.currentTimeMillis();
|
||||
this.logger.info("导出excel总耗时:{}", (Object) (end - start));
|
||||
}
|
||||
}
|
||||
+281
@@ -0,0 +1,281 @@
|
||||
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 java.io.File;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Instant;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.apache.poi.ss.util.CellRangeAddress;
|
||||
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<>();
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
package cn.cloudwalk.service.organization.export;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.result.PageLabelResult;
|
||||
import cn.cloudwalk.client.organization.result.PersonProListResult;
|
||||
import cn.cloudwalk.service.organization.common.FolderUtil;
|
||||
import cn.cloudwalk.service.organization.export.CommonExRecordExcelByLabelCreater;
|
||||
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.nio.file.attribute.FileAttribute;
|
||||
import java.util.List;
|
||||
import org.apache.poi.ss.usermodel.CellStyle;
|
||||
import org.apache.poi.ss.usermodel.FillPatternType;
|
||||
import org.apache.poi.ss.usermodel.Font;
|
||||
import org.apache.poi.ss.usermodel.HorizontalAlignment;
|
||||
import org.apache.poi.ss.usermodel.IndexedColors;
|
||||
import org.apache.poi.xssf.usermodel.XSSFCell;
|
||||
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
|
||||
import org.apache.poi.xssf.usermodel.XSSFDrawing;
|
||||
import org.apache.poi.xssf.usermodel.XSSFFont;
|
||||
import org.apache.poi.xssf.usermodel.XSSFRow;
|
||||
import org.apache.poi.xssf.usermodel.XSSFSheet;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public abstract class CommonRecordExcelByLabelCreater<T> {
|
||||
private static final Logger log = LoggerFactory.getLogger(CommonRecordExcelByLabelCreater.class);
|
||||
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
protected List<T> records;
|
||||
protected String dirPath;
|
||||
protected int index;
|
||||
protected XSSFSheet sheet;
|
||||
protected XSSFWorkbook wb;
|
||||
protected XSSFDrawing patriarch;
|
||||
protected CellStyle headStyle;
|
||||
protected PersonProListResult personProListResult;
|
||||
private int beginIndex;
|
||||
protected boolean hasContainImage;
|
||||
|
||||
protected CommonRecordExcelByLabelCreater(List<T> records, String dirPath, int index) {
|
||||
this.records = records;
|
||||
this.dirPath = dirPath;
|
||||
this.index = index;
|
||||
this.beginIndex = index;
|
||||
this.wb = new XSSFWorkbook();
|
||||
this.sheet = this.wb.createSheet();
|
||||
this.patriarch = this.sheet.createDrawingPatriarch();
|
||||
this.headStyle = this.headStyle();
|
||||
}
|
||||
|
||||
public static CommonRecordExcelByLabelCreater getCreater(
|
||||
List<PageLabelResult> records,
|
||||
String dirPath,
|
||||
int index,
|
||||
PersonProListResult personProListResult) {
|
||||
return new CommonExRecordExcelByLabelCreater(records, dirPath, index, personProListResult);
|
||||
}
|
||||
|
||||
private CellStyle headStyle() {
|
||||
XSSFCellStyle cellStyle = this.wb.createCellStyle();
|
||||
XSSFFont font = this.wb.createFont();
|
||||
font.setBold(true);
|
||||
cellStyle.setFont((Font) font);
|
||||
cellStyle.setAlignment(HorizontalAlignment.CENTER);
|
||||
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||
cellStyle.setFillBackgroundColor(IndexedColors.BLUE_GREY.index);
|
||||
cellStyle.setFillForegroundColor(IndexedColors.BLUE_GREY.index);
|
||||
return cellStyle;
|
||||
}
|
||||
|
||||
protected void createHeadCell(XSSFRow row, int columnNum, String value) {
|
||||
XSSFCell cell = row.createCell(columnNum);
|
||||
cell.setCellValue(value);
|
||||
cell.setCellStyle(this.headStyle);
|
||||
}
|
||||
|
||||
public void createFile() throws IOException {
|
||||
this.createDirectory();
|
||||
this.createTitleRow();
|
||||
this.createBodyRows();
|
||||
this.save();
|
||||
}
|
||||
|
||||
protected abstract void createTitleRow();
|
||||
|
||||
protected abstract void createBodyRows();
|
||||
|
||||
protected void createDirectory() throws IOException {
|
||||
if (!Paths.get(this.dirPath, new String[0]).toFile().exists()) {
|
||||
Files.createDirectories(Paths.get(this.dirPath, new String[0]), new FileAttribute[0]);
|
||||
}
|
||||
}
|
||||
|
||||
protected void save() throws IOException {
|
||||
try (OutputStream out =
|
||||
Files.newOutputStream(
|
||||
Paths.get(
|
||||
this.dirPath
|
||||
+ File.separator
|
||||
+ this.beginIndex
|
||||
+ "_"
|
||||
+ (this.index + this.records.size() - 1)
|
||||
+ ".xlsx",
|
||||
new String[0]),
|
||||
new OpenOption[0]); ) {
|
||||
this.wb.write(out);
|
||||
} catch (IOException e) {
|
||||
this.logger.error("生成文件失败", e);
|
||||
FolderUtil.deleteFolder(this.dirPath);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
package cn.cloudwalk.service.organization.export;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.result.PersonProListResult;
|
||||
import cn.cloudwalk.client.organization.service.store.result.OrganizationResult;
|
||||
import cn.cloudwalk.service.organization.common.FolderUtil;
|
||||
import cn.cloudwalk.service.organization.export.CommonExRecordExcelByOrgCreater;
|
||||
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.nio.file.attribute.FileAttribute;
|
||||
import java.util.List;
|
||||
import org.apache.poi.ss.usermodel.CellStyle;
|
||||
import org.apache.poi.ss.usermodel.FillPatternType;
|
||||
import org.apache.poi.ss.usermodel.Font;
|
||||
import org.apache.poi.ss.usermodel.HorizontalAlignment;
|
||||
import org.apache.poi.ss.usermodel.IndexedColors;
|
||||
import org.apache.poi.xssf.usermodel.XSSFCell;
|
||||
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
|
||||
import org.apache.poi.xssf.usermodel.XSSFDrawing;
|
||||
import org.apache.poi.xssf.usermodel.XSSFFont;
|
||||
import org.apache.poi.xssf.usermodel.XSSFRow;
|
||||
import org.apache.poi.xssf.usermodel.XSSFSheet;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public abstract class CommonRecordExcelByOrgCreater<T> {
|
||||
private static final Logger log = LoggerFactory.getLogger(CommonRecordExcelByOrgCreater.class);
|
||||
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
protected List<T> records;
|
||||
protected String dirPath;
|
||||
protected int index;
|
||||
protected XSSFSheet sheet;
|
||||
protected XSSFWorkbook wb;
|
||||
protected XSSFDrawing patriarch;
|
||||
protected CellStyle headStyle;
|
||||
protected PersonProListResult personProListResult;
|
||||
private int beginIndex;
|
||||
protected boolean hasContainImage;
|
||||
|
||||
protected CommonRecordExcelByOrgCreater(List<T> records, String dirPath, int index) {
|
||||
this.records = records;
|
||||
this.dirPath = dirPath;
|
||||
this.index = index;
|
||||
this.beginIndex = index;
|
||||
this.wb = new XSSFWorkbook();
|
||||
this.sheet = this.wb.createSheet();
|
||||
this.patriarch = this.sheet.createDrawingPatriarch();
|
||||
this.headStyle = this.headStyle();
|
||||
}
|
||||
|
||||
public static CommonRecordExcelByOrgCreater getCreater(
|
||||
List<OrganizationResult> records,
|
||||
String dirPath,
|
||||
int index,
|
||||
PersonProListResult personProListResult) {
|
||||
return new CommonExRecordExcelByOrgCreater(records, dirPath, index, personProListResult);
|
||||
}
|
||||
|
||||
private CellStyle headStyle() {
|
||||
XSSFCellStyle cellStyle = this.wb.createCellStyle();
|
||||
XSSFFont font = this.wb.createFont();
|
||||
font.setBold(true);
|
||||
cellStyle.setFont((Font) font);
|
||||
cellStyle.setAlignment(HorizontalAlignment.CENTER);
|
||||
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||
cellStyle.setFillBackgroundColor(IndexedColors.BLUE_GREY.index);
|
||||
cellStyle.setFillForegroundColor(IndexedColors.BLUE_GREY.index);
|
||||
return cellStyle;
|
||||
}
|
||||
|
||||
protected void createHeadCell(XSSFRow row, int columnNum, String value) {
|
||||
XSSFCell cell = row.createCell(columnNum);
|
||||
cell.setCellValue(value);
|
||||
cell.setCellStyle(this.headStyle);
|
||||
}
|
||||
|
||||
public void createFile() throws IOException {
|
||||
this.createDirectory();
|
||||
this.createTitleRow();
|
||||
this.createBodyRows();
|
||||
this.save();
|
||||
}
|
||||
|
||||
protected abstract void createTitleRow();
|
||||
|
||||
protected abstract void createBodyRows();
|
||||
|
||||
protected void createDirectory() throws IOException {
|
||||
if (!Paths.get(this.dirPath, new String[0]).toFile().exists()) {
|
||||
Files.createDirectories(Paths.get(this.dirPath, new String[0]), new FileAttribute[0]);
|
||||
}
|
||||
}
|
||||
|
||||
protected void save() throws IOException {
|
||||
try (OutputStream out =
|
||||
Files.newOutputStream(
|
||||
Paths.get(
|
||||
this.dirPath
|
||||
+ File.separator
|
||||
+ this.beginIndex
|
||||
+ "_"
|
||||
+ (this.index + this.records.size() - 1)
|
||||
+ ".xlsx",
|
||||
new String[0]),
|
||||
new OpenOption[0]); ) {
|
||||
this.wb.write(out);
|
||||
} catch (IOException e) {
|
||||
this.logger.error("生成文件失败", e);
|
||||
FolderUtil.deleteFolder(this.dirPath);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package cn.cloudwalk.service.organization.export;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.personimg.result.ImgStorePersonGetResult;
|
||||
import cn.cloudwalk.client.organization.result.PersonProListResult;
|
||||
import cn.cloudwalk.intelligent.davinci.storage.manager.FileStorageManager;
|
||||
import cn.cloudwalk.service.organization.common.FolderUtil;
|
||||
import cn.cloudwalk.service.organization.export.CommonExRecordExcelCreater;
|
||||
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.nio.file.attribute.FileAttribute;
|
||||
import java.util.List;
|
||||
import org.apache.poi.ss.usermodel.CellStyle;
|
||||
import org.apache.poi.ss.usermodel.FillPatternType;
|
||||
import org.apache.poi.ss.usermodel.Font;
|
||||
import org.apache.poi.ss.usermodel.HorizontalAlignment;
|
||||
import org.apache.poi.ss.usermodel.IndexedColors;
|
||||
import org.apache.poi.xssf.usermodel.XSSFCell;
|
||||
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
|
||||
import org.apache.poi.xssf.usermodel.XSSFDrawing;
|
||||
import org.apache.poi.xssf.usermodel.XSSFFont;
|
||||
import org.apache.poi.xssf.usermodel.XSSFRow;
|
||||
import org.apache.poi.xssf.usermodel.XSSFSheet;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public abstract class CommonRecordExcelCreater<T> {
|
||||
private static final Logger log = LoggerFactory.getLogger(CommonRecordExcelCreater.class);
|
||||
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
protected List<T> records;
|
||||
protected String dirPath;
|
||||
protected int index;
|
||||
protected XSSFSheet sheet;
|
||||
protected XSSFWorkbook wb;
|
||||
protected XSSFDrawing patriarch;
|
||||
protected CellStyle headStyle;
|
||||
protected PersonProListResult personProListResult;
|
||||
private int beginIndex;
|
||||
protected boolean hasContainImage;
|
||||
|
||||
protected CommonRecordExcelCreater(List<T> records, String dirPath, int index) {
|
||||
this.records = records;
|
||||
this.dirPath = dirPath;
|
||||
this.index = index;
|
||||
this.beginIndex = index;
|
||||
this.wb = new XSSFWorkbook();
|
||||
this.sheet = this.wb.createSheet();
|
||||
this.patriarch = this.sheet.createDrawingPatriarch();
|
||||
this.headStyle = this.headStyle();
|
||||
}
|
||||
|
||||
public static CommonRecordExcelCreater getCreater(
|
||||
List<ImgStorePersonGetResult> records,
|
||||
String dirPath,
|
||||
int index,
|
||||
FileStorageManager fileStorageManager,
|
||||
PersonProListResult personProListResult,
|
||||
boolean hasContainImage) {
|
||||
return new CommonExRecordExcelCreater(
|
||||
records, dirPath, index, fileStorageManager, personProListResult, hasContainImage);
|
||||
}
|
||||
|
||||
private CellStyle headStyle() {
|
||||
XSSFCellStyle cellStyle = this.wb.createCellStyle();
|
||||
XSSFFont font = this.wb.createFont();
|
||||
font.setBold(true);
|
||||
cellStyle.setFont((Font) font);
|
||||
cellStyle.setAlignment(HorizontalAlignment.CENTER);
|
||||
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||
cellStyle.setFillBackgroundColor(IndexedColors.BLUE_GREY.index);
|
||||
cellStyle.setFillForegroundColor(IndexedColors.BLUE_GREY.index);
|
||||
return cellStyle;
|
||||
}
|
||||
|
||||
protected void createHeadCell(XSSFRow row, int columnNum, String value) {
|
||||
XSSFCell cell = row.createCell(columnNum);
|
||||
cell.setCellValue(value);
|
||||
cell.setCellStyle(this.headStyle);
|
||||
}
|
||||
|
||||
public void createFile() throws IOException {
|
||||
this.createDirectory();
|
||||
this.createTitleRow();
|
||||
this.createBodyRows();
|
||||
this.save();
|
||||
}
|
||||
|
||||
protected abstract void createTitleRow();
|
||||
|
||||
protected abstract void createBodyRows();
|
||||
|
||||
protected void createDirectory() throws IOException {
|
||||
if (!Paths.get(this.dirPath, new String[0]).toFile().exists()) {
|
||||
Files.createDirectories(Paths.get(this.dirPath, new String[0]), new FileAttribute[0]);
|
||||
}
|
||||
}
|
||||
|
||||
protected void save() throws IOException {
|
||||
try (OutputStream out =
|
||||
Files.newOutputStream(
|
||||
Paths.get(
|
||||
this.dirPath
|
||||
+ File.separator
|
||||
+ this.beginIndex
|
||||
+ "_"
|
||||
+ (this.index + this.records.size() - 1)
|
||||
+ ".xlsx",
|
||||
new String[0]),
|
||||
new OpenOption[0]); ) {
|
||||
this.wb.write(out);
|
||||
} catch (IOException e) {
|
||||
this.logger.error("生成文件失败", e);
|
||||
FolderUtil.deleteFolder(this.dirPath);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
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;
|
||||
import cn.cloudwalk.cwos.client.event.event.PersonCardCompareEvent;
|
||||
import cn.cloudwalk.cwos.client.event.event.PictureResultEvent;
|
||||
import cn.cloudwalk.cwos.client.event.event.resource.EnterpriseChangeEvent;
|
||||
import cn.cloudwalk.cwos.client.event.handler.EventListener;
|
||||
import cn.cloudwalk.service.organization.service.DeviceGroupRefChangeEventHandler;
|
||||
import cn.cloudwalk.service.organization.service.PersonCardCompareEventHandler;
|
||||
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(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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
package cn.cloudwalk.service.organization.policy;
|
||||
|
||||
import cn.cloudwalk.data.organization.entity.TenantVisitorFloorPolicy;
|
||||
import cn.cloudwalk.data.organization.mapper.TenantVisitorFloorPolicyMapper;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
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;
|
||||
|
||||
/**
|
||||
* 租户访客楼层策略:启用时以 allow_zone_ids **替代** detail / 访客列表中的楼层集合(规范语义:非与 listByImageId
|
||||
* 求交)。策略数据仅在组织库 {@code component-organization}。
|
||||
*/
|
||||
@Service
|
||||
public class TenantVisitorFloorPolicyService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(TenantVisitorFloorPolicyService.class);
|
||||
|
||||
@Autowired private TenantVisitorFloorPolicyMapper tenantVisitorFloorPolicyMapper;
|
||||
|
||||
/** 按组织节点 ID 返回启用策略行;不存在或未启用时 empty。 */
|
||||
public Optional<TenantVisitorFloorPolicy> findEnabledPolicyByOrgId(String orgId) {
|
||||
if (StringUtils.isBlank(orgId)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
TenantVisitorFloorPolicy row = this.tenantVisitorFloorPolicyMapper.selectEnabledByOrgId(orgId);
|
||||
return Optional.ofNullable(row);
|
||||
}
|
||||
|
||||
/** 解析 allow_zone_ids JSON 数组;非法或空则返回 empty list。 */
|
||||
public List<String> parseAllowZoneIds(String allowZoneIdsJson) {
|
||||
if (StringUtils.isBlank(allowZoneIdsJson)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
try {
|
||||
List<String> parsed = JSON.parseArray(allowZoneIdsJson, String.class);
|
||||
if (parsed == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
return parsed.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.map(String::trim)
|
||||
.filter(s -> !s.isEmpty())
|
||||
.collect(Collectors.toList());
|
||||
} catch (Exception e) {
|
||||
log.warn("[POLICY-ERR] allow_zone_ids JSON invalid: {}", e.getMessage());
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按人员所属组织 ID 顺序依次尝试命中策略({@code tenant_visitor_floor_policy.org_id});任一命中则返回该行的
|
||||
* allow 列表。
|
||||
*/
|
||||
public Optional<List<String>> replacementZoneIdsIfPolicyActive(List<String> orgIds) {
|
||||
if (CollectionUtils.isEmpty(orgIds)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
log.info("[POLICY] entry orgIds={}", orgIds);
|
||||
for (String id : orgIds) {
|
||||
Optional<List<String>> zones = replacementZoneIdsIfPolicyActive(id);
|
||||
if (zones.isPresent()) {
|
||||
return zones;
|
||||
}
|
||||
}
|
||||
log.debug("[POLICY-MISS] no enabled policy for any org in {}", orgIds);
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* 若策略启用且 allow 列表非空,返回替代用的 zoneId 列表(新列表副本);否则 empty(调用方保留 listByImageId
|
||||
* 原始结果)。表未创建或查询异常时返回 empty,避免阻断 detail。
|
||||
*
|
||||
* @param orgId 组织节点 ID(与 cw_is_organization.ID、表中 org_id 一致),勿传 company/businessId
|
||||
*/
|
||||
public Optional<List<String>> replacementZoneIdsIfPolicyActive(String orgId) {
|
||||
try {
|
||||
Optional<TenantVisitorFloorPolicy> policy = findEnabledPolicyByOrgId(orgId);
|
||||
if (!policy.isPresent()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
List<String> allow = parseAllowZoneIds(policy.get().getAllowZoneIds());
|
||||
if (allow.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(new ArrayList<>(allow));
|
||||
} catch (Exception e) {
|
||||
log.warn(
|
||||
"tenant_visitor_floor_policy query failed, fallback to listByImageId floors: {}",
|
||||
e.toString());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
package cn.cloudwalk.service.organization.schedule;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.common.constant.ImageStoreConstants;
|
||||
import cn.cloudwalk.client.organization.result.ZoneResult;
|
||||
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.hutool.core.collection.ConcurrentHashSet;
|
||||
import java.io.File;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.stream.Collectors;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
public class BatchImportContext {
|
||||
private File unzipFolder;
|
||||
private long totalCount;
|
||||
private List<File> excelFiles;
|
||||
private BatchImport batchImport;
|
||||
private AtomicLong successCount;
|
||||
private AtomicLong failCount;
|
||||
private AtomicLong imageCopyTime = new AtomicLong(0L);
|
||||
private AtomicLong insertTime = new AtomicLong(0L);
|
||||
private Map<String, ImgStorePersonProperties> nameCodeMap =
|
||||
new HashMap<String, ImgStorePersonProperties>();
|
||||
private Map<Integer, String> nameIndexMap = new HashMap<Integer, String>();
|
||||
private Map<String, Organization> orgNameMap = new HashMap<String, Organization>();
|
||||
private Map<String, Label> labelNameMap = new HashMap<String, Label>();
|
||||
private Map<String, ZoneResult> zoneMap = new HashMap<String, ZoneResult>();
|
||||
private Set<String> cacheProperties = new ConcurrentHashSet();
|
||||
private String systemIdFiledName;
|
||||
|
||||
public BatchImportContext() {
|
||||
this.successCount = new AtomicLong(0L);
|
||||
this.failCount = new AtomicLong(0L);
|
||||
}
|
||||
|
||||
public File getUnzipFolder() {
|
||||
return this.unzipFolder;
|
||||
}
|
||||
|
||||
public void setUnzipFolder(File unzipFolder) {
|
||||
this.unzipFolder = unzipFolder;
|
||||
}
|
||||
|
||||
public long getTotalCount() {
|
||||
return this.totalCount;
|
||||
}
|
||||
|
||||
public void setTotalCount(long totalCount) {
|
||||
this.totalCount = totalCount;
|
||||
}
|
||||
|
||||
public List<File> getExcelFiles() {
|
||||
return this.excelFiles;
|
||||
}
|
||||
|
||||
public void setExcelFiles(List<File> excelFiles) {
|
||||
this.excelFiles = excelFiles;
|
||||
}
|
||||
|
||||
public BatchImport getBatchImport() {
|
||||
return this.batchImport;
|
||||
}
|
||||
|
||||
public void setBatchImport(BatchImport batchImport) {
|
||||
this.batchImport = batchImport;
|
||||
}
|
||||
|
||||
public AtomicLong getSuccessCount() {
|
||||
return this.successCount;
|
||||
}
|
||||
|
||||
public void setSuccessCount(AtomicLong successCount) {
|
||||
this.successCount = successCount;
|
||||
}
|
||||
|
||||
public AtomicLong getFailCount() {
|
||||
return this.failCount;
|
||||
}
|
||||
|
||||
public void setFailCount(AtomicLong failCount) {
|
||||
this.failCount = failCount;
|
||||
}
|
||||
|
||||
public AtomicLong getImageCopyTime() {
|
||||
return this.imageCopyTime;
|
||||
}
|
||||
|
||||
public void setImageCopyTime(AtomicLong imageCopyTime) {
|
||||
this.imageCopyTime = imageCopyTime;
|
||||
}
|
||||
|
||||
public AtomicLong getInsertTime() {
|
||||
return this.insertTime;
|
||||
}
|
||||
|
||||
public void setInsertTime(AtomicLong insertTime) {
|
||||
this.insertTime = insertTime;
|
||||
}
|
||||
|
||||
public Map<String, ImgStorePersonProperties> getNameCodeMap() {
|
||||
return this.nameCodeMap;
|
||||
}
|
||||
|
||||
public void setNameCodeMap(Map<String, ImgStorePersonProperties> nameCodeMap) {
|
||||
this.nameCodeMap = nameCodeMap;
|
||||
}
|
||||
|
||||
public void setNameCodeMap(List<ImgStorePersonProperties> personProperties) {
|
||||
HashMap<String, ImgStorePersonProperties> nameCodeMap =
|
||||
new HashMap<String, ImgStorePersonProperties>();
|
||||
for (ImgStorePersonProperties properties : personProperties) {
|
||||
nameCodeMap.put(properties.getName(), properties);
|
||||
if (properties.getHasSysAccount() == null || properties.getHasSysAccount() != 1) continue;
|
||||
this.setSystemIdFiledName(properties.getCode());
|
||||
}
|
||||
ImgStorePersonProperties imgStorePersonProperties = new ImgStorePersonProperties();
|
||||
imgStorePersonProperties.setBusinessId(this.getBatchImport().getBusinessId());
|
||||
imgStorePersonProperties.setCode("sysAccountId");
|
||||
imgStorePersonProperties.setName("同步创建账号系统ID");
|
||||
imgStorePersonProperties.setHasRequired(ImageStoreConstants.AGREE);
|
||||
imgStorePersonProperties.setType(Short.valueOf((short) 1));
|
||||
nameCodeMap.put("同步创建账号系统ID", imgStorePersonProperties);
|
||||
this.nameCodeMap = nameCodeMap;
|
||||
}
|
||||
|
||||
public Map<Integer, String> getNameIndexMap() {
|
||||
return this.nameIndexMap;
|
||||
}
|
||||
|
||||
public void setNameIndexMap(Map<Integer, String> nameIndexMap) {
|
||||
this.nameIndexMap = nameIndexMap;
|
||||
}
|
||||
|
||||
public void setOrgMap(List<Organization> organizationList) {
|
||||
if (CollectionUtils.isEmpty(organizationList)) {
|
||||
return;
|
||||
}
|
||||
for (Organization organization : organizationList) {
|
||||
this.orgNameMap.put(organization.getName(), organization);
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Organization> getOrgNameMap() {
|
||||
return this.orgNameMap;
|
||||
}
|
||||
|
||||
public void setLabelMap(List<Label> labelList) {
|
||||
if (CollectionUtils.isEmpty(labelList)) {
|
||||
return;
|
||||
}
|
||||
for (Label label : labelList) {
|
||||
this.labelNameMap.put(label.getName(), label);
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Label> getLabelNameMap() {
|
||||
return this.labelNameMap;
|
||||
}
|
||||
|
||||
public Set<String> getCacheProperties() {
|
||||
return this.cacheProperties;
|
||||
}
|
||||
|
||||
public void setCacheProperties(Set<String> cacheProperties) {
|
||||
this.cacheProperties = cacheProperties;
|
||||
}
|
||||
|
||||
public String getSystemIdFiledName() {
|
||||
return this.systemIdFiledName;
|
||||
}
|
||||
|
||||
public void setSystemIdFiledName(String systemIdFiledName) {
|
||||
this.systemIdFiledName = systemIdFiledName;
|
||||
}
|
||||
|
||||
public void setZoneMap(List<ZoneResult> zoneResultList) {
|
||||
if (CollectionUtils.isEmpty(zoneResultList)) {
|
||||
return;
|
||||
}
|
||||
for (ZoneResult zoneResult : zoneResultList) {
|
||||
String pName = "";
|
||||
if (zoneResult.getParentId() != null) {
|
||||
pName =
|
||||
((ZoneResult)
|
||||
zoneResultList.stream()
|
||||
.filter(zoneResult1 -> zoneResult1.getId().equals(zoneResult.getParentId()))
|
||||
.collect(Collectors.toList())
|
||||
.get(0))
|
||||
.getName();
|
||||
}
|
||||
this.zoneMap.put(pName + "%" + zoneResult.getName(), zoneResult);
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, ZoneResult> getZoneMap() {
|
||||
return this.zoneMap;
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package cn.cloudwalk.service.organization.schedule;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.service.organization.service.CpImageStorePersonValidateManager;
|
||||
import cn.cloudwalk.task.sdk.starter.job.AbstractJob;
|
||||
import org.quartz.DisallowConcurrentExecution;
|
||||
import org.quartz.JobExecutionContext;
|
||||
import org.quartz.JobExecutionException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
@DisallowConcurrentExecution
|
||||
public class DelayPersonValidateTask extends AbstractJob {
|
||||
private static final Logger log = LoggerFactory.getLogger(DelayPersonValidateTask.class);
|
||||
@Autowired private CpImageStorePersonValidateManager cpImageStorePersonValidateManager;
|
||||
|
||||
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
|
||||
log.info("DelayPersonValidateTask Start.");
|
||||
try {
|
||||
this.cpImageStorePersonValidateManager.delayAddValidateTrigger();
|
||||
} catch (Exception e) {
|
||||
log.error("DelayPersonValidateTask Exception:{}", (Object) e.getMessage());
|
||||
}
|
||||
log.info("DelayPersonValidateTask End.");
|
||||
}
|
||||
}
|
||||
+504
@@ -0,0 +1,504 @@
|
||||
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;
|
||||
import cn.cloudwalk.client.organization.result.ZoneResult;
|
||||
import cn.cloudwalk.client.organization.schedule.ImportStatus;
|
||||
import cn.cloudwalk.client.organization.service.PersonFileService;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkSessionContextHolder;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.cloud.utils.BeanCopyUtils;
|
||||
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;
|
||||
import cn.cloudwalk.data.organization.mapper.PersonBatchImportMapper;
|
||||
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.service.feign.ZoneFeignClient;
|
||||
import cn.cloudwalk.task.sdk.starter.job.AbstractJob;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.google.common.collect.Lists;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.ArrayList;
|
||||
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.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.apache.poi.ss.usermodel.WorkbookFactory;
|
||||
import org.quartz.DisallowConcurrentExecution;
|
||||
import org.quartz.JobExecutionContext;
|
||||
import org.quartz.JobExecutionException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
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("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(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
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;
|
||||
import org.quartz.JobExecutionContext;
|
||||
import org.quartz.JobExecutionException;
|
||||
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);
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
package cn.cloudwalk.service.organization.schedule;
|
||||
|
||||
// 调度服务
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.task.data.dto.param.TaskModifyParam;
|
||||
import cn.cloudwalk.task.sdk.client.TaskExecClient;
|
||||
import cn.cloudwalk.task.sdk.dto.JobDetailResult;
|
||||
import cn.cloudwalk.task.sdk.starter.config.init.properties.QuartzTaskProperties;
|
||||
import cn.cloudwalk.task.service.TaskService;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import org.quartz.JobBuilder;
|
||||
import org.quartz.JobDetail;
|
||||
import org.quartz.JobKey;
|
||||
import org.quartz.Scheduler;
|
||||
import org.quartz.SchedulerException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
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("${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);
|
||||
}
|
||||
}
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.service.AlarmDeviceManageService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class AlarmAlarmDeviceManageServiceImpl implements AlarmDeviceManageService {
|
||||
private static final Logger log =
|
||||
LoggerFactory.getLogger(AlarmAlarmDeviceManageServiceImpl.class);
|
||||
|
||||
public String getApplicationId(String businessId) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+695
@@ -0,0 +1,695 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.aggregate.common.enums.DelStatusEnum;
|
||||
import cn.cloudwalk.client.organization.param.AddAreaParam;
|
||||
import cn.cloudwalk.client.organization.param.AddUnitAreaParam;
|
||||
import cn.cloudwalk.client.organization.param.DelAreaParam;
|
||||
import cn.cloudwalk.client.organization.param.DelUnitAreaParam;
|
||||
import cn.cloudwalk.client.organization.param.EditAreaParam;
|
||||
import cn.cloudwalk.client.organization.param.NextTreeAreaParam;
|
||||
import cn.cloudwalk.client.organization.param.QueryAreaParam;
|
||||
import cn.cloudwalk.client.organization.result.NextTreeAreaResult;
|
||||
import cn.cloudwalk.client.organization.result.TreeAreaResult;
|
||||
import cn.cloudwalk.client.organization.service.AreaService;
|
||||
import cn.cloudwalk.client.organization.service.store.result.AreaResult;
|
||||
import cn.cloudwalk.cloud.annotation.CloudwalkParamsValidate;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkCallContext;
|
||||
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.AddUnitAreaDTO;
|
||||
import cn.cloudwalk.data.organization.dto.AreaTypeQueryDTO;
|
||||
import cn.cloudwalk.data.organization.dto.GetsAreaDTO;
|
||||
import cn.cloudwalk.data.organization.dto.GetsOrganizationDTO;
|
||||
import cn.cloudwalk.data.organization.dto.ImgStoreOrgBatchUpdateDTO;
|
||||
import cn.cloudwalk.data.organization.dto.UnitCountDTO;
|
||||
import cn.cloudwalk.data.organization.entity.Area;
|
||||
import cn.cloudwalk.data.organization.entity.AreaType;
|
||||
import cn.cloudwalk.data.organization.entity.ImgStoreUnitArea;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStoreAreaMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStoreAreaTypeMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStoreOrganizationMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStoreUnitAreaMapper;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import cn.cloudwalk.service.organization.common.ToolUtil;
|
||||
import com.github.pagehelper.Page;
|
||||
import com.github.pagehelper.PageHelper;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
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.context.annotation.Primary;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
@Primary
|
||||
@Service("coreAreaServiceImpl")
|
||||
public class AreaServiceImpl extends AbstractImagStoreService implements AreaService {
|
||||
@Resource private ImgStoreAreaMapper imgStoreAreaMapper;
|
||||
@Resource private ImgStoreOrganizationMapper organizationMapper;
|
||||
@Resource private ImgStoreAreaTypeMapper imgStoreAreaTypeMapper;
|
||||
@Resource private ImgStoreUnitAreaMapper imgStoreUnitAreaMapper;
|
||||
private static final short IS_DEL = 1;
|
||||
private static final short IS_NOT_DEL = 0;
|
||||
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<String> add(AddAreaParam param, CloudwalkCallContext context) {
|
||||
String businessId;
|
||||
if (StringUtils.isNotBlank(param.getBusinessId())) {
|
||||
businessId = param.getBusinessId();
|
||||
} else {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
GetsAreaDTO getsAreaDTO = new GetsAreaDTO();
|
||||
getsAreaDTO.setBusinessId(businessId);
|
||||
getsAreaDTO.setIsDel(Short.valueOf((short) 0));
|
||||
if (!StringUtils.isEmpty(param.getParentId())) {
|
||||
getsAreaDTO.setId(param.getParentId());
|
||||
List<Area> list = this.imgStoreAreaMapper.gets(getsAreaDTO);
|
||||
if (CollectionUtils.isEmpty(list)) {
|
||||
return CloudwalkResult.fail("53015100", getMessage("53015100"));
|
||||
}
|
||||
Area area1 = list.get(0);
|
||||
AreaType areaType = this.imgStoreAreaTypeMapper.selectByPrimaryKey(area1.getTypeId());
|
||||
if (areaType != null && areaType.getHasLowerLevel().intValue() != 1) {
|
||||
return CloudwalkResult.fail("53015101", getMessage("53015101"));
|
||||
}
|
||||
} else {
|
||||
List<Area> parent = this.imgStoreAreaMapper.getParentNode(businessId);
|
||||
if (!CollectionUtils.isEmpty(parent)) {
|
||||
return CloudwalkResult.fail("53015102", getMessage("53015102"));
|
||||
}
|
||||
}
|
||||
getsAreaDTO.setId(null);
|
||||
getsAreaDTO.setName(param.getName());
|
||||
List<Area> names = this.imgStoreAreaMapper.gets(getsAreaDTO);
|
||||
if (!CollectionUtils.isEmpty(names)) {
|
||||
return CloudwalkResult.fail("53015103", getMessage("53015103"));
|
||||
}
|
||||
long time = System.currentTimeMillis();
|
||||
Area area = (Area) BeanCopyUtils.copyProperties(param, Area.class);
|
||||
area.setId(getPrimaryId());
|
||||
area.setCreateTime(Long.valueOf(time));
|
||||
area.setCreateUserId(context.getUser().getCaller());
|
||||
area.setIsDel(Short.valueOf((short) 0));
|
||||
area.setLastUpdateTime(Long.valueOf(time));
|
||||
area.setLastUpdateUserId(context.getUser().getCaller());
|
||||
area.setName(param.getName());
|
||||
area.setParentId(param.getParentId());
|
||||
area.setBusinessId(businessId);
|
||||
this.imgStoreAreaMapper.insertSelective(area);
|
||||
return CloudwalkResult.success(area.getId());
|
||||
}
|
||||
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> edit(EditAreaParam param, CloudwalkCallContext context) {
|
||||
String businessId;
|
||||
if (StringUtils.isNotBlank(param.getBusinessId())) {
|
||||
businessId = param.getBusinessId();
|
||||
} else {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
GetsAreaDTO getsAreaDTO = new GetsAreaDTO();
|
||||
getsAreaDTO.setId(param.getId());
|
||||
getsAreaDTO.setBusinessId(businessId);
|
||||
getsAreaDTO.setIsDel(Short.valueOf((short) 0));
|
||||
List<Area> areaList = this.imgStoreAreaMapper.gets(getsAreaDTO);
|
||||
if (CollectionUtils.isEmpty(areaList)) {
|
||||
return CloudwalkResult.fail("53015104", getMessage("53015104"));
|
||||
}
|
||||
List<TreeAreaResult> res = null;
|
||||
Area old = areaList.get(0);
|
||||
Area edit = (Area) BeanCopyUtils.copyProperties(param, Area.class);
|
||||
edit.setId(old.getId());
|
||||
if (!StringUtils.isEmpty(param.getParentId())) {
|
||||
Area parent = this.imgStoreAreaMapper.selectByPrimaryKey(param.getParentId());
|
||||
if (parent == null
|
||||
|| parent.getIsDel().shortValue() == 1
|
||||
|| !businessId.equals(parent.getBusinessId())) {
|
||||
return CloudwalkResult.fail("53015100", getMessage("53015100"));
|
||||
}
|
||||
res =
|
||||
BeanCopyUtils.copy(this.imgStoreAreaMapper.getAllArea(businessId), TreeAreaResult.class);
|
||||
TreeAreaResult currentNode = null;
|
||||
for (TreeAreaResult org : res) {
|
||||
if (org.getId().equals(param.getId())) {
|
||||
currentNode = org;
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (TreeAreaResult nodeX : res) {
|
||||
label57:
|
||||
for (TreeAreaResult nodeY : res) {
|
||||
if (nodeX.getParentId() != null && nodeX.getParentId().equals(nodeY.getId())) {
|
||||
if (nodeY.getChildren() == null) {
|
||||
nodeY.setChildren(new ArrayList());
|
||||
break label57;
|
||||
}
|
||||
nodeY.getChildren().add(nodeX);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (currentNode != null && !CollectionUtils.isEmpty(currentNode.getChildren())) {
|
||||
List<String> values = new ArrayList<>();
|
||||
judgeTreeNode(currentNode.getChildren(), values);
|
||||
values.add(param.getId());
|
||||
if (values.contains(param.getParentId())) {
|
||||
return CloudwalkResult.fail("53015105", getMessage("53015105"));
|
||||
}
|
||||
}
|
||||
edit.setParentId(param.getParentId());
|
||||
}
|
||||
if (!StringUtils.isEmpty(param.getName())) {
|
||||
if (res == null) {
|
||||
res =
|
||||
BeanCopyUtils.copy(
|
||||
this.imgStoreAreaMapper.getAllArea(businessId), TreeAreaResult.class);
|
||||
}
|
||||
for (TreeAreaResult org : res) {
|
||||
if (org.getName().equals(param.getName()) && !org.getId().equals(param.getId())) {
|
||||
return CloudwalkResult.fail("53015103", getMessage("53015103"));
|
||||
}
|
||||
}
|
||||
edit.setName(param.getName());
|
||||
}
|
||||
edit.setLastUpdateUserId(context.getUser().getCaller());
|
||||
edit.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.imgStoreAreaMapper.updateByPrimaryKeySelective(edit);
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> delete(DelAreaParam param, CloudwalkCallContext context) {
|
||||
String businessId;
|
||||
if (StringUtils.isNotBlank(param.getBusinessId())) {
|
||||
businessId = param.getBusinessId();
|
||||
} else {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(param.getIds())) {
|
||||
if (this.imgStoreAreaMapper.getAreaByIds(param.getIds(), businessId).size()
|
||||
!= param.getIds().size()) {
|
||||
return CloudwalkResult.fail("53060411", getMessage("53060411"));
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(this.imgStoreAreaMapper.getParentIdIsNull(param.getIds()))) {
|
||||
return CloudwalkResult.fail("53015106", getMessage("53015106"));
|
||||
}
|
||||
this.imgStoreAreaMapper.batchDel(
|
||||
param.getIds(), System.currentTimeMillis(), context.getUser().getCaller(), businessId);
|
||||
this.imgStoreUnitAreaMapper.deleteByAreaIds(param.getIds());
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
|
||||
public CloudwalkResult<List<TreeAreaResult>> tree(
|
||||
NextTreeAreaParam param, CloudwalkCallContext context) {
|
||||
List<TreeAreaResult> res;
|
||||
String businessId = context.getCompany().getCompanyId();
|
||||
List<String> orgIds = new ArrayList<>();
|
||||
List<TreeAreaResult> tree = new ArrayList<>();
|
||||
if (StringUtils.isBlank(param.getParentId())) {
|
||||
if (CollectionUtils.isEmpty(orgIds)) {
|
||||
List<Area> allOrg = this.imgStoreAreaMapper.getAllArea(businessId);
|
||||
res = BeanCopyUtils.copy(allOrg, TreeAreaResult.class);
|
||||
} else {
|
||||
List<Area> areaByIds = this.imgStoreAreaMapper.getAreaByIds(orgIds, businessId);
|
||||
res = BeanCopyUtils.copy(areaByIds, TreeAreaResult.class);
|
||||
}
|
||||
if (CollectionUtils.isEmpty(res)) {
|
||||
AreaType areaType;
|
||||
Area area = new Area();
|
||||
AreaTypeQueryDTO areaTypeQueryDto = new AreaTypeQueryDTO();
|
||||
areaTypeQueryDto.setBusinessId(businessId);
|
||||
areaTypeQueryDto.setStatus(Integer.valueOf(0));
|
||||
areaTypeQueryDto.setHasDefault(Integer.valueOf(1));
|
||||
List<AreaType> areaTypes = this.imgStoreAreaTypeMapper.select(areaTypeQueryDto);
|
||||
if (!CollectionUtils.isEmpty(areaTypes)) {
|
||||
areaType = areaTypes.get(0);
|
||||
synchronized (this) {
|
||||
List<Area> resList = this.imgStoreAreaMapper.getAllArea(businessId);
|
||||
if (CollectionUtils.isEmpty(resList)) {
|
||||
area.setBusinessId(businessId);
|
||||
area.setTypeId(areaType.getId());
|
||||
area.setIsDel(Short.valueOf((short) 0));
|
||||
area.setName("默认根节点");
|
||||
area.setId(CloudwalkDateUtils.getUUID());
|
||||
area.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
area.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.imgStoreAreaMapper.insertSelective(area);
|
||||
} else {
|
||||
area = resList.get(0);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return CloudwalkResult.fail("53015107", getMessage("53015107"));
|
||||
}
|
||||
TreeAreaResult result =
|
||||
(TreeAreaResult) BeanCopyUtils.copyProperties(area, TreeAreaResult.class);
|
||||
result.setChildren(null);
|
||||
result.setLevel(Integer.valueOf(1));
|
||||
result.setUnitCount(Integer.valueOf(0));
|
||||
result.setType(areaType.getName());
|
||||
result.setHasLowerLevel(areaType.getHasLowerLevel());
|
||||
tree.add(result);
|
||||
return CloudwalkResult.success(tree);
|
||||
}
|
||||
res =
|
||||
(List<TreeAreaResult>)
|
||||
res.stream()
|
||||
.filter(ToolUtil.distinctByKey(TreeAreaResult::getId))
|
||||
.collect(Collectors.toList());
|
||||
} else {
|
||||
res = getTreeByParentId(param.getParentId(), businessId);
|
||||
}
|
||||
addPersonCount(res);
|
||||
addTypeName(res);
|
||||
for (TreeAreaResult nodeX : res) {
|
||||
boolean mark = false;
|
||||
for (TreeAreaResult nodeY : res) {
|
||||
if (nodeX.getParentId() != null && nodeX.getParentId().equals(nodeY.getId())) {
|
||||
mark = true;
|
||||
if (nodeY.getChildren() == null) {
|
||||
nodeY.setChildren(new ArrayList());
|
||||
}
|
||||
nodeY.getChildren().add(nodeX);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!mark) {
|
||||
tree.add(nodeX);
|
||||
}
|
||||
}
|
||||
addLevel(tree, 1);
|
||||
return CloudwalkResult.success(tree);
|
||||
}
|
||||
|
||||
private List<TreeAreaResult> getTreeByParentId(String parentId, String businessId) {
|
||||
List<String> parentIdList = new ArrayList<>();
|
||||
parentIdList.add(parentId);
|
||||
List<Area> resultAll = new ArrayList<>();
|
||||
while (!CollectionUtils.isEmpty(parentIdList)) {
|
||||
List<Area> resultOnce = this.imgStoreAreaMapper.getAreaByParentIds(parentIdList, businessId);
|
||||
if (!CollectionUtils.isEmpty(resultOnce)) {
|
||||
resultAll.addAll(resultOnce);
|
||||
parentIdList.clear();
|
||||
for (Area area : resultOnce) parentIdList.add(area.getId());
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return BeanCopyUtils.copy(resultAll, TreeAreaResult.class);
|
||||
}
|
||||
|
||||
private List<Area> getListByParentId(GetsAreaDTO dto, Integer retainParent) {
|
||||
List<String> parentIdList = new ArrayList<>();
|
||||
String parentId = dto.getParentId();
|
||||
parentIdList.add(parentId);
|
||||
dto.setParentId(null);
|
||||
List<Area> resultAll = new ArrayList<>();
|
||||
while (!CollectionUtils.isEmpty(parentIdList)) {
|
||||
dto.setParentIds(parentIdList);
|
||||
List<Area> resultOnce = this.imgStoreAreaMapper.gets(dto);
|
||||
if (!CollectionUtils.isEmpty(resultOnce)) {
|
||||
resultAll.addAll(resultOnce);
|
||||
parentIdList.clear();
|
||||
for (Area area : resultOnce) parentIdList.add(area.getId());
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (retainParent != null && retainParent.intValue() == 1) {
|
||||
Area area = this.imgStoreAreaMapper.selectByPrimaryKey(parentId);
|
||||
resultAll.add(area);
|
||||
}
|
||||
return resultAll;
|
||||
}
|
||||
|
||||
public CloudwalkResult<List<NextTreeAreaResult>> getNextTree(
|
||||
NextTreeAreaParam param, CloudwalkCallContext context) {
|
||||
String businessId;
|
||||
if (StringUtils.isNotBlank(param.getBusinessId())) {
|
||||
businessId = param.getBusinessId();
|
||||
} else {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
List<NextTreeAreaResult> res =
|
||||
BeanCopyUtils.copy(
|
||||
this.imgStoreAreaMapper.getNextArea(param.getParentId(), businessId),
|
||||
NextTreeAreaResult.class);
|
||||
List<String> ids = new ArrayList<>();
|
||||
Set<String> typeIds = new HashSet<>();
|
||||
for (NextTreeAreaResult nextTreeAreaResult : res) {
|
||||
ids.add(nextTreeAreaResult.getId());
|
||||
typeIds.add(nextTreeAreaResult.getTypeId());
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(ids)) {
|
||||
Map<String, Integer> map = new HashMap<>();
|
||||
Map<String, AreaType> typeMap = new HashMap<>();
|
||||
List<UnitCountDTO> unitCountDTOS = this.imgStoreAreaMapper.getUnitCount(ids);
|
||||
for (UnitCountDTO dto : unitCountDTOS) {
|
||||
map.put(dto.getId(), dto.getCount());
|
||||
}
|
||||
AreaTypeQueryDTO typeQueryDto = new AreaTypeQueryDTO();
|
||||
typeQueryDto.setIds(new ArrayList<>(typeIds));
|
||||
List<AreaType> areaTypeList = this.imgStoreAreaTypeMapper.select(typeQueryDto);
|
||||
if (!CollectionUtils.isEmpty(areaTypeList)) {
|
||||
for (AreaType areaType : areaTypeList) {
|
||||
typeMap.put(areaType.getId(), areaType);
|
||||
}
|
||||
}
|
||||
for (NextTreeAreaResult nextTreeAreaResult : res) {
|
||||
Integer count = map.get(nextTreeAreaResult.getId());
|
||||
if (count != null) {
|
||||
nextTreeAreaResult.setUnitCount(count);
|
||||
} else {
|
||||
nextTreeAreaResult.setUnitCount(Integer.valueOf(0));
|
||||
}
|
||||
AreaType areaType = typeMap.get(nextTreeAreaResult.getTypeId());
|
||||
if (areaType != null) {
|
||||
String typeName = areaType.getName();
|
||||
nextTreeAreaResult.setType((typeName == null) ? "" : typeName);
|
||||
nextTreeAreaResult.setHasLowerLevel(areaType.getHasLowerLevel());
|
||||
continue;
|
||||
}
|
||||
nextTreeAreaResult.setType("");
|
||||
nextTreeAreaResult.setHasLowerLevel(null);
|
||||
}
|
||||
}
|
||||
return CloudwalkResult.success(res);
|
||||
}
|
||||
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> addUnit(
|
||||
AddUnitAreaParam unitAreaParam, CloudwalkCallContext context) {
|
||||
if (CollectionUtils.isEmpty(unitAreaParam.getUnitIds())) {
|
||||
return CloudwalkResult.fail("53060411", getMessage("53060411"));
|
||||
}
|
||||
Area unitArea = this.imgStoreAreaMapper.selectByPrimaryKey(unitAreaParam.getAreaId());
|
||||
if (unitArea == null
|
||||
|| unitArea.getIsDel().shortValue() == 1
|
||||
|| !context.getCompany().getCompanyId().equals(unitArea.getBusinessId())) {
|
||||
return CloudwalkResult.fail("53015104", getMessage("53015104"));
|
||||
}
|
||||
List<String> unitIds =
|
||||
this.imgStoreAreaMapper.getUnitIdInRef(
|
||||
(AddUnitAreaDTO) BeanCopyUtils.copyProperties(unitAreaParam, AddUnitAreaDTO.class));
|
||||
if (!CollectionUtils.isEmpty(unitIds)) {
|
||||
unitAreaParam.getUnitIds().removeAll(unitIds);
|
||||
}
|
||||
if (CollectionUtils.isEmpty(unitAreaParam.getUnitIds())) {
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
GetsOrganizationDTO dto = new GetsOrganizationDTO();
|
||||
dto.setIds(unitAreaParam.getUnitIds());
|
||||
dto.setBusinessId(
|
||||
StringUtils.isEmpty(unitAreaParam.getBusinessId())
|
||||
? context.getCompany().getCompanyId()
|
||||
: unitAreaParam.getBusinessId());
|
||||
dto.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
if (this.organizationMapper.gets(dto).size() != unitAreaParam.getUnitIds().size()) {
|
||||
return CloudwalkResult.fail("53015108", getMessage("53015108"));
|
||||
}
|
||||
List<ImgStoreUnitArea> list = new ArrayList<>();
|
||||
long time = System.currentTimeMillis();
|
||||
for (String id : unitAreaParam.getUnitIds()) {
|
||||
ImgStoreUnitArea storeUnitArea = new ImgStoreUnitArea();
|
||||
storeUnitArea.setCreateTime(Long.valueOf(time));
|
||||
storeUnitArea.setCreateUserId(context.getUser().getCaller());
|
||||
storeUnitArea.setId(getPrimaryId());
|
||||
storeUnitArea.setLastUpdateTime(Long.valueOf(time));
|
||||
storeUnitArea.setLastUpdateUserId(context.getUser().getCaller());
|
||||
storeUnitArea.setAreaId(unitAreaParam.getAreaId());
|
||||
storeUnitArea.setUnitId(id);
|
||||
list.add(storeUnitArea);
|
||||
}
|
||||
this.imgStoreAreaMapper.batchInsert(list);
|
||||
ImgStoreOrgBatchUpdateDTO batchUpdateDTO = new ImgStoreOrgBatchUpdateDTO();
|
||||
batchUpdateDTO.setIds(unitAreaParam.getUnitIds());
|
||||
batchUpdateDTO.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.organizationMapper.updateBatchByIds(batchUpdateDTO);
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> delUnit(
|
||||
DelUnitAreaParam delUnitAreaParam, CloudwalkCallContext context) {
|
||||
String businessId;
|
||||
if (StringUtils.isNotBlank(delUnitAreaParam.getBusinessId())) {
|
||||
businessId = delUnitAreaParam.getBusinessId();
|
||||
} else {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
GetsAreaDTO getsAreaDTO = new GetsAreaDTO();
|
||||
getsAreaDTO.setId(delUnitAreaParam.getAreaId());
|
||||
getsAreaDTO.setBusinessId(businessId);
|
||||
List<Area> areaList = this.imgStoreAreaMapper.gets(getsAreaDTO);
|
||||
if (CollectionUtils.isEmpty(areaList)) {
|
||||
return CloudwalkResult.fail("53015104", getMessage("53015104"));
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(delUnitAreaParam.getUnitIds())) {
|
||||
this.organizationMapper.batchDel(
|
||||
delUnitAreaParam.getUnitIds(),
|
||||
System.currentTimeMillis(),
|
||||
context.getUser().getCaller(),
|
||||
businessId);
|
||||
ImgStoreOrgBatchUpdateDTO batchUpdateDTO = new ImgStoreOrgBatchUpdateDTO();
|
||||
batchUpdateDTO.setIds(delUnitAreaParam.getUnitIds());
|
||||
batchUpdateDTO.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.organizationMapper.updateBatchByIds(batchUpdateDTO);
|
||||
}
|
||||
return CloudwalkResult.success(Boolean.TRUE);
|
||||
}
|
||||
|
||||
public CloudwalkResult<List<AreaResult>> getList(
|
||||
QueryAreaParam param, CloudwalkCallContext context) {
|
||||
String businessId;
|
||||
List<Area> resultData;
|
||||
if (StringUtils.isNotBlank(param.getBusinessId())) {
|
||||
businessId = param.getBusinessId();
|
||||
} else {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
GetsAreaDTO getsAreaDTO = (GetsAreaDTO) BeanCopyUtils.copyProperties(param, GetsAreaDTO.class);
|
||||
getsAreaDTO.setBusinessId(businessId);
|
||||
getsAreaDTO.setIsDel(Short.valueOf((short) 0));
|
||||
if (StringUtils.isNotBlank(param.getParentId())
|
||||
&& param.getHasCascade() != null
|
||||
&& param.getHasCascade().intValue() == 1) {
|
||||
resultData = getListByParentId(getsAreaDTO, param.getRetainParent());
|
||||
} else {
|
||||
resultData = this.imgStoreAreaMapper.gets(getsAreaDTO);
|
||||
}
|
||||
List<String> ids = new ArrayList<>();
|
||||
Set<String> typeIds = new HashSet<>();
|
||||
for (Area area : resultData) {
|
||||
ids.add(area.getId());
|
||||
typeIds.add(area.getTypeId());
|
||||
}
|
||||
List<AreaResult> resultList = BeanCopyUtils.copy(resultData, AreaResult.class);
|
||||
if (!CollectionUtils.isEmpty(ids)) {
|
||||
Map<String, Integer> map = new HashMap<>();
|
||||
Map<String, AreaType> typeMap = new HashMap<>();
|
||||
List<UnitCountDTO> unitCount = this.imgStoreAreaMapper.getUnitCount(ids);
|
||||
AreaTypeQueryDTO typeQueryDto = new AreaTypeQueryDTO();
|
||||
typeQueryDto.setIds(new ArrayList<>(typeIds));
|
||||
List<AreaType> areaTypeList = this.imgStoreAreaTypeMapper.select(typeQueryDto);
|
||||
if (!CollectionUtils.isEmpty(unitCount)) {
|
||||
for (UnitCountDTO dto : unitCount) {
|
||||
map.put(dto.getId(), dto.getCount());
|
||||
}
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(areaTypeList)) {
|
||||
for (AreaType areaType : areaTypeList) {
|
||||
typeMap.put(areaType.getId(), areaType);
|
||||
}
|
||||
}
|
||||
for (AreaResult result : resultList) {
|
||||
Integer count = map.get(result.getId());
|
||||
if (count != null) {
|
||||
result.setUnitCount(count);
|
||||
} else {
|
||||
result.setUnitCount(Integer.valueOf(0));
|
||||
}
|
||||
AreaType areaType = typeMap.get(result.getTypeId());
|
||||
if (areaType != null) {
|
||||
String typeName = areaType.getName();
|
||||
result.setType((typeName == null) ? "" : typeName);
|
||||
result.setHasLowerLevel(areaType.getHasLowerLevel());
|
||||
continue;
|
||||
}
|
||||
result.setType("");
|
||||
result.setHasLowerLevel(null);
|
||||
}
|
||||
}
|
||||
return CloudwalkResult.success(resultList);
|
||||
}
|
||||
|
||||
public CloudwalkResult<CloudwalkPageAble<AreaResult>> getPage(
|
||||
QueryAreaParam param, CloudwalkPageInfo page, CloudwalkCallContext context) {
|
||||
String businessId;
|
||||
if (StringUtils.isNotBlank(param.getBusinessId())) {
|
||||
businessId = param.getBusinessId();
|
||||
} else {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
PageHelper.startPage(page.getCurrentPage(), page.getPageSize());
|
||||
GetsAreaDTO getsAreaDTO = (GetsAreaDTO) BeanCopyUtils.copyProperties(param, GetsAreaDTO.class);
|
||||
getsAreaDTO.setBusinessId(businessId);
|
||||
getsAreaDTO.setIsDel(Short.valueOf((short) 0));
|
||||
Page<Area> pageData = (Page<Area>) this.imgStoreAreaMapper.gets(getsAreaDTO);
|
||||
List<Area> resultData = pageData.getResult();
|
||||
List<String> ids = new ArrayList<>();
|
||||
Set<String> typeIds = new HashSet<>();
|
||||
for (Area area : resultData) {
|
||||
ids.add(area.getId());
|
||||
typeIds.add(area.getTypeId());
|
||||
}
|
||||
List<AreaResult> resultList = BeanCopyUtils.copy(resultData, AreaResult.class);
|
||||
if (!CollectionUtils.isEmpty(ids)) {
|
||||
Map<String, Integer> map = new HashMap<>();
|
||||
Map<String, AreaType> typeMap = new HashMap<>();
|
||||
List<UnitCountDTO> unitCount = this.imgStoreAreaMapper.getUnitCount(ids);
|
||||
AreaTypeQueryDTO typeQueryDto = new AreaTypeQueryDTO();
|
||||
typeQueryDto.setIds(new ArrayList<>(typeIds));
|
||||
List<AreaType> areaTypeList = this.imgStoreAreaTypeMapper.select(typeQueryDto);
|
||||
if (!CollectionUtils.isEmpty(unitCount)) {
|
||||
for (UnitCountDTO dto : unitCount) {
|
||||
map.put(dto.getId(), dto.getCount());
|
||||
}
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(areaTypeList)) {
|
||||
areaTypeList.forEach(o -> typeMap.put(o.getId(), o));
|
||||
}
|
||||
for (AreaResult result : resultList) {
|
||||
Integer count = map.get(result.getId());
|
||||
if (count != null) {
|
||||
result.setUnitCount(count);
|
||||
} else {
|
||||
result.setUnitCount(Integer.valueOf(0));
|
||||
}
|
||||
AreaType areaType = typeMap.get(result.getTypeId());
|
||||
if (areaType != null) {
|
||||
String typeName = areaType.getName();
|
||||
result.setType((typeName == null) ? "" : typeName);
|
||||
result.setHasLowerLevel(areaType.getHasLowerLevel());
|
||||
continue;
|
||||
}
|
||||
result.setType("");
|
||||
result.setHasLowerLevel(null);
|
||||
}
|
||||
}
|
||||
CloudwalkPageAble<AreaResult> pageAble =
|
||||
new CloudwalkPageAble(resultList, page, pageData.getTotal());
|
||||
return CloudwalkResult.success(pageAble);
|
||||
}
|
||||
|
||||
public CloudwalkResult<AreaResult> detail(QueryAreaParam param, CloudwalkCallContext context) {
|
||||
Area area;
|
||||
GetsAreaDTO getsAreaDTO = (GetsAreaDTO) BeanCopyUtils.copyProperties(param, GetsAreaDTO.class);
|
||||
getsAreaDTO.setIsDel(Short.valueOf((short) 0));
|
||||
List<Area> resultData = this.imgStoreAreaMapper.gets(getsAreaDTO);
|
||||
if (!CollectionUtils.isEmpty(resultData)) {
|
||||
area = resultData.get(0);
|
||||
} else {
|
||||
return CloudwalkResult.success(null);
|
||||
}
|
||||
String areaId = area.getId();
|
||||
String typeId = area.getTypeId();
|
||||
List<UnitCountDTO> unitCountDTOList =
|
||||
this.imgStoreAreaMapper.getUnitCount(Collections.singletonList(areaId));
|
||||
AreaType areaType = this.imgStoreAreaTypeMapper.selectByPrimaryKey(typeId);
|
||||
AreaResult result = (AreaResult) BeanCopyUtils.copyProperties(area, AreaResult.class);
|
||||
if (!CollectionUtils.isEmpty(unitCountDTOList)) {
|
||||
result.setUnitCount(((UnitCountDTO) unitCountDTOList.get(0)).getCount());
|
||||
} else {
|
||||
result.setUnitCount(Integer.valueOf(0));
|
||||
}
|
||||
if (areaType != null) {
|
||||
result.setType(areaType.getName());
|
||||
result.setHasLowerLevel(areaType.getHasLowerLevel());
|
||||
} else {
|
||||
result.setType("");
|
||||
result.setHasLowerLevel(null);
|
||||
}
|
||||
if (result.getParentId() == null) {
|
||||
result.setLevel(Integer.valueOf(1));
|
||||
}
|
||||
return CloudwalkResult.success(result);
|
||||
}
|
||||
|
||||
private void addLevel(List<TreeAreaResult> tree, int level) {
|
||||
if (!CollectionUtils.isEmpty(tree)) {
|
||||
for (TreeAreaResult result : tree) {
|
||||
result.setLevel(Integer.valueOf(level));
|
||||
addLevel(result.getChildren(), level + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void addPersonCount(List<TreeAreaResult> res) {
|
||||
List<String> ids = new ArrayList<>();
|
||||
for (TreeAreaResult areaResult : res) {
|
||||
ids.add(areaResult.getId());
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(ids)) {
|
||||
Map<String, Integer> map = new HashMap<>();
|
||||
List<UnitCountDTO> unitCountDTOList = this.imgStoreAreaMapper.getUnitCount(ids);
|
||||
for (UnitCountDTO dto : unitCountDTOList) {
|
||||
map.put(dto.getId(), dto.getCount());
|
||||
}
|
||||
for (TreeAreaResult organizationResult : res) {
|
||||
Integer count = map.get(organizationResult.getId());
|
||||
if (count != null) {
|
||||
organizationResult.setUnitCount(count);
|
||||
continue;
|
||||
}
|
||||
organizationResult.setUnitCount(Integer.valueOf(0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void addTypeName(List<TreeAreaResult> res) {
|
||||
Set<String> typeIds = new HashSet<>();
|
||||
Map<String, AreaType> typeMap = new HashMap<>();
|
||||
for (TreeAreaResult result : res) {
|
||||
typeIds.add(result.getTypeId());
|
||||
}
|
||||
AreaTypeQueryDTO typeQueryDto = new AreaTypeQueryDTO();
|
||||
typeQueryDto.setIds(new ArrayList<>(typeIds));
|
||||
List<AreaType> areaTypeList = this.imgStoreAreaTypeMapper.select(typeQueryDto);
|
||||
if (!CollectionUtils.isEmpty(areaTypeList)) {
|
||||
for (AreaType areaType : areaTypeList) {
|
||||
typeMap.put(areaType.getId(), areaType);
|
||||
}
|
||||
}
|
||||
for (TreeAreaResult result : res) {
|
||||
AreaType areaType = typeMap.get(result.getTypeId());
|
||||
if (areaType == null) {
|
||||
result.setType("");
|
||||
result.setHasLowerLevel(Integer.valueOf(0));
|
||||
continue;
|
||||
}
|
||||
String typeName = areaType.getName();
|
||||
result.setType((typeName == null) ? "" : typeName);
|
||||
result.setHasLowerLevel(areaType.getHasLowerLevel());
|
||||
}
|
||||
}
|
||||
|
||||
private void judgeTreeNode(List<TreeAreaResult> children, List<String> values) {
|
||||
if (!CollectionUtils.isEmpty(children))
|
||||
for (TreeAreaResult result : children) {
|
||||
values.add(result.getId());
|
||||
judgeTreeNode(result.getChildren(), values);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+420
@@ -0,0 +1,420 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
+404
@@ -0,0 +1,404 @@
|
||||
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;
|
||||
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.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.serial.UUIDSerial;
|
||||
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 com.alibaba.fastjson.JSON;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Sets;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Collection;
|
||||
import java.util.Comparator;
|
||||
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;
|
||||
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.springframework.util.ReflectionUtils;
|
||||
import org.springside.modules.utils.Collections3;
|
||||
|
||||
@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 = 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(deviceGetResult.getData())) {
|
||||
List<AtomicDeviceGetResult> deviceData = deviceGetResult.getData();
|
||||
List<DeviceResult> deviceResultList = Lists.newArrayListWithCapacity(deviceData.size());
|
||||
deviceData.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(
|
||||
r ->
|
||||
Objects.equals(
|
||||
r.getBindPropertyCode(), property.getBindProp()))
|
||||
.findFirst();
|
||||
if (registryPropertyOptional.isPresent()) {
|
||||
Optional<ImgStorePersonProperties> propertyOptional =
|
||||
personPropertyList.stream()
|
||||
.filter(
|
||||
p ->
|
||||
Objects.equals(
|
||||
p.getId(),
|
||||
registryPropertyOptional.get().getPersonPropertyId()))
|
||||
.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());
|
||||
}
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.ninca.messagecenter.file.param.FileFinishParam;
|
||||
import cn.cloudwalk.client.ninca.messagecenter.file.param.FileGetParam;
|
||||
import cn.cloudwalk.client.ninca.messagecenter.file.param.FileInitParam;
|
||||
import cn.cloudwalk.client.ninca.messagecenter.file.result.FileResult;
|
||||
import cn.cloudwalk.client.organization.service.ICommonAppDownloadCenterService;
|
||||
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.context.CloudwalkCallContext;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.cloud.utils.CloudwalkDateUtils;
|
||||
import cn.cloudwalk.service.organization.common.ComponentInnerKafkaConfig;
|
||||
import cn.cloudwalk.service.organization.common.JsonUtils;
|
||||
import cn.cloudwalk.service.organization.service.feign.MessageCenterFeignClient;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import javax.annotation.Resource;
|
||||
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 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<>();
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.param.ExportLabelTaskParam;
|
||||
import cn.cloudwalk.client.organization.param.ExportOrgTaskParam;
|
||||
import cn.cloudwalk.client.organization.param.ExportRecordTaskParam;
|
||||
import cn.cloudwalk.client.organization.personimg.service.ImgStorePersonService;
|
||||
import cn.cloudwalk.client.organization.service.ICommonAppDownloadCenterService;
|
||||
import cn.cloudwalk.client.organization.service.ICommonAppExportTaskService;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkCallContext;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
import cn.cloudwalk.cloud.session.company.CompanyContext;
|
||||
import cn.cloudwalk.cloud.session.user.UserContext;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import cn.cloudwalk.service.organization.common.CommonDownloadDataConfig;
|
||||
import cn.cloudwalk.service.organization.common.ComponentInnerKafkaConfig;
|
||||
import cn.cloudwalk.service.organization.export.CommonAppExportExecuteTask;
|
||||
import java.time.LocalDateTime;
|
||||
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();
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.batch.param.download.FilePartAppendPara;
|
||||
import cn.cloudwalk.client.organization.batch.param.download.FilePartFinishPara;
|
||||
import cn.cloudwalk.client.organization.batch.param.download.FilePartInitResult;
|
||||
import cn.cloudwalk.client.organization.service.ICommonAppFileManageService;
|
||||
import cn.cloudwalk.intelligent.davinci.common.exception.DavinciServiceException;
|
||||
import cn.cloudwalk.intelligent.davinci.storage.bean.part.dto.PartFinishDTO;
|
||||
import cn.cloudwalk.intelligent.davinci.storage.bean.part.dto.PartInitDTO;
|
||||
import cn.cloudwalk.intelligent.davinci.storage.bean.part.dto.PartInitResultDTO;
|
||||
import cn.cloudwalk.intelligent.davinci.storage.manager.FilePartManager;
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.batch.param.download.FilePartFinishPara;
|
||||
import cn.cloudwalk.client.organization.batch.param.download.FilePartInitResult;
|
||||
import cn.cloudwalk.client.organization.service.ICommonAppFileManageService;
|
||||
import cn.cloudwalk.client.organization.service.ICommonStorageService;
|
||||
import cn.cloudwalk.client.organization.service.store.utils.TimeUtils;
|
||||
import cn.cloudwalk.cloud.serial.UUIDSerial;
|
||||
import cn.cloudwalk.intelligent.davinci.common.exception.DavinciServiceException;
|
||||
import cn.cloudwalk.intelligent.davinci.storage.bean.file.dto.FileRemoveDTO;
|
||||
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.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;
|
||||
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(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());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+409
@@ -0,0 +1,409 @@
|
||||
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;
|
||||
import cn.cloudwalk.client.organization.service.store.result.PersonRegistryResult;
|
||||
import cn.cloudwalk.client.resource.application.param.ApplicationQueryParam;
|
||||
import cn.cloudwalk.client.resource.application.result.ApplicationResult;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkCallContext;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
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;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStoreLabelMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStoreOrganizationMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.PersonRegistryDeviceMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.PersonRegistryMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.PersonRegistryPropertiesMapper;
|
||||
import cn.cloudwalk.rest.resource.application.feign.ApplicationFeignClient;
|
||||
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.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import javax.annotation.Resource;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
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("${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);
|
||||
}
|
||||
}
|
||||
|
||||
+695
@@ -0,0 +1,695 @@
|
||||
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.PassRuleResult;
|
||||
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.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 -> {
|
||||
String orgIdsCsv = personOrgMap.get(personId);
|
||||
List<String> orgIds =
|
||||
(orgIdsCsv == null || orgIdsCsv.isEmpty())
|
||||
? new ArrayList<String>()
|
||||
: new ArrayList<String>(Arrays.asList(orgIdsCsv.split(",")));
|
||||
String labelIdsCsv = personLabelMap.get(personId);
|
||||
List<String> labelIds =
|
||||
(labelIdsCsv == null || labelIdsCsv.isEmpty())
|
||||
? new ArrayList<String>()
|
||||
: new ArrayList<String>(Arrays.asList(labelIdsCsv.split(",")));
|
||||
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(result.getData())) {
|
||||
for (BatchPassRuleResult passRule : result.getData()) {
|
||||
List<String> zoneNameList =
|
||||
Optional.ofNullable(passRule.getZoneList())
|
||||
.orElse(Collections.<PassRuleResult>emptyList())
|
||||
.stream()
|
||||
.map(PassRuleResult::getZoneName)
|
||||
.collect(Collectors.toList());
|
||||
Collections.sort(
|
||||
zoneNameList, (Comparator<? super String>) new NaturalOrderComparator(true));
|
||||
String zoneNameStr = String.join(",", 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;
|
||||
}
|
||||
}
|
||||
+637
@@ -0,0 +1,637 @@
|
||||
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;
|
||||
import cn.cloudwalk.client.aggregate.group.param.AgImageStoreImageSyncParam;
|
||||
import cn.cloudwalk.client.aggregate.group.result.AgImageStoreImageResult;
|
||||
import cn.cloudwalk.client.aggregate.group.service.AgImageStoreImageService;
|
||||
import cn.cloudwalk.client.aggregate.group.service.AgImageStoreService;
|
||||
import cn.cloudwalk.client.organization.common.enums.CpImageStoreMatchPatternEnum;
|
||||
import cn.cloudwalk.client.organization.result.BatchSearchFaceResult;
|
||||
import cn.cloudwalk.client.organization.result.SearchFaceResult;
|
||||
import cn.cloudwalk.client.organization.service.store.param.CpSearchFaceParam;
|
||||
import cn.cloudwalk.client.organization.service.store.result.AssociatedResult;
|
||||
import cn.cloudwalk.client.organization.service.store.service.CpImageStoreToolService;
|
||||
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.dto.GetsImageStoreAssociatedDTO;
|
||||
import cn.cloudwalk.data.organization.dto.GroupPersonRefDTO;
|
||||
import cn.cloudwalk.data.organization.dto.ImgStorePersonQueryDto;
|
||||
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;
|
||||
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.data.organization.mapper.IsImageStoreAssociatedMapper;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.Resource;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Isolation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
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 = 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 -> 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"));
|
||||
}
|
||||
}
|
||||
}
|
||||
+1028
File diff suppressed because it is too large
Load Diff
+724
@@ -0,0 +1,724 @@
|
||||
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;
|
||||
import cn.cloudwalk.client.aggregate.group.param.AgImageStoreEditParam;
|
||||
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.cloud.context.CloudwalkCallContext;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.data.organization.dto.GroupPersonSynData;
|
||||
import cn.cloudwalk.data.organization.dto.SyncPersonDTO;
|
||||
import cn.cloudwalk.data.organization.entity.GroupPersonRef;
|
||||
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.hutool.core.collection.CollectionUtil;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Sets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
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 org.springframework.data.redis.core.RedisCallback;
|
||||
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("${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(personId));
|
||||
} else {
|
||||
groupPersonSynData.setDelPersonIds(Lists.newArrayList(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(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(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(synData.getPersonId()));
|
||||
Map<String, GroupPersonRef> associatedPersonResultsBeforeUpdate =
|
||||
this.cpImageStorePersonManager.getOldAssociatedPersonIds(
|
||||
waitSyncImageStore.getId(), Lists.newArrayList(synData.getPersonId()));
|
||||
GroupPersonRef refAfterUpdate = associatedPersonResultsAfterUpdate.get(synData.getPersonId());
|
||||
if (refAfterUpdate != null) {
|
||||
List<ImgStorePerson> associatedPersonExpiryDateAfterUpdate =
|
||||
this.imgStorePersonMapper.selectExpiryDateByIds(
|
||||
Lists.newArrayList(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(
|
||||
(RedisCallback)
|
||||
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(
|
||||
(RedisCallback)
|
||||
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(
|
||||
(RedisCallback)
|
||||
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(
|
||||
(RedisCallback)
|
||||
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(
|
||||
(RedisCallback)
|
||||
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(
|
||||
(RedisCallback)
|
||||
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);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+575
@@ -0,0 +1,575 @@
|
||||
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;
|
||||
import cn.cloudwalk.client.aggregate.group.result.AgFeatureExtractResult;
|
||||
import cn.cloudwalk.client.aggregate.group.result.AgImageStoreResult;
|
||||
import cn.cloudwalk.client.organization.common.enums.SyncStatusEnum;
|
||||
import cn.cloudwalk.client.organization.result.HandleFaceResult;
|
||||
import cn.cloudwalk.client.organization.service.store.param.CpHandleFaceParam;
|
||||
import cn.cloudwalk.client.organization.service.store.service.CpImageStoreToolService;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkCallContext;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.cloud.utils.CloudwalkDateUtils;
|
||||
import cn.cloudwalk.data.organization.dto.DelGroupPersonDTO;
|
||||
import cn.cloudwalk.data.organization.dto.DevicePersonSyncLogDTO;
|
||||
import cn.cloudwalk.data.organization.dto.GroupPersonRefDTO;
|
||||
import cn.cloudwalk.data.organization.dto.ImgStorePersonQueryDto;
|
||||
import cn.cloudwalk.data.organization.dto.SyncPersonDTO;
|
||||
import cn.cloudwalk.data.organization.entity.GroupPersonRef;
|
||||
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.service.organization.common.AbstractImagStoreService;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Sets;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.Resource;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
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("${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(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());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+925
@@ -0,0 +1,925 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
|
||||
import cn.cloudwalk.client.organization.service.store.utils.SnowFlake;
|
||||
import cn.cloudwalk.data.organization.dto.QueryGroupPersonDTO;
|
||||
import cn.cloudwalk.data.organization.dto.SyncPersonDTO;
|
||||
import cn.cloudwalk.data.organization.entity.GroupPersonRef;
|
||||
import cn.cloudwalk.data.organization.mapper.GroupPersonRefMapper;
|
||||
import cn.cloudwalk.service.organization.common.JsonUtils;
|
||||
import cn.cloudwalk.service.organization.service.CpImageStorePersonTxHandler;
|
||||
import cn.cloudwalk.service.organization.service.CpImageStoreSyncManager;
|
||||
import cn.cloudwalk.service.organization.utils.BeanCopyUtils;
|
||||
import cn.cloudwalk.task.sdk.client.TaskExecClient;
|
||||
import cn.cloudwalk.task.sdk.starter.config.init.properties.QuartzTaskProperties;
|
||||
import cn.hutool.core.collection.ConcurrentHashSet;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Sets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Comparator;
|
||||
import java.util.Date;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
import org.springframework.data.redis.core.RedisCallback;
|
||||
import javax.annotation.Resource;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.quartz.Scheduler;
|
||||
import org.quartz.SchedulerException;
|
||||
import org.quartz.Trigger;
|
||||
import org.quartz.TriggerBuilder;
|
||||
import org.quartz.TriggerKey;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
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.stereotype.Service;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
@Service
|
||||
public class CpImageStorePersonValidateManager {
|
||||
private static final Logger log =
|
||||
LoggerFactory.getLogger(CpImageStorePersonValidateManager.class);
|
||||
private final String VALIDATE_JOB_GROUP_LOCK = "validate_job_group_lock:";
|
||||
|
||||
@Value(value = "${group-person.syn.config.lock-validate-job-group-second:30}")
|
||||
private String lockValidateJobGroupSecond;
|
||||
|
||||
@Value(value = "${group-person.syn.config.lock-validate-job-group-time-out:120}")
|
||||
private String lockValidateJobGroupTimeOut;
|
||||
|
||||
@Value(value = "${group-person.syn.config.delay-add-validate-data:false}")
|
||||
private Boolean delayAddValidateData;
|
||||
|
||||
@Value(value = "${group-person.syn.config.delay-add-validate-hour:48}")
|
||||
private Long delayAddValidateHour;
|
||||
|
||||
@Autowired private QuartzTaskProperties quartzTaskProperties;
|
||||
@Autowired private TaskExecClient taskExecClient;
|
||||
@Autowired private CpImageStorePersonTxHandler cpImageStorePersonTxHandler;
|
||||
@Autowired private CpImageStoreSyncManager cpImageStoreSyncManager;
|
||||
@Autowired private StringRedisTemplate redisTemplate;
|
||||
@Autowired private DefaultRedisScript<String> lockValidateJobRedisScript;
|
||||
@Autowired private DefaultRedisScript<String> unlockValidateJobRedisScript;
|
||||
@Resource private GroupPersonRefMapper groupPersonRefMapper;
|
||||
|
||||
/*
|
||||
* WARNING - Removed try catching itself - possible behaviour change.
|
||||
*/
|
||||
public void addValidateData(List<SyncPersonDTO> syncPersonList) {
|
||||
Long lockValue;
|
||||
log.info("bind接口service 查询syncPersonList:{}", (Object) JSONObject.toJSONString(syncPersonList));
|
||||
ConcurrentHashSet deleteSet = new ConcurrentHashSet();
|
||||
ConcurrentHashMap addMap = new ConcurrentHashMap();
|
||||
ConcurrentHashMap removeMap = new ConcurrentHashMap();
|
||||
ConcurrentHashSet addSet = new ConcurrentHashSet();
|
||||
HashSet changeGroupIdSet = Sets.newHashSet();
|
||||
long currentTime = System.currentTimeMillis();
|
||||
syncPersonList.parallelStream()
|
||||
.forEach(
|
||||
arg_0 ->
|
||||
this.lambda$addValidateData$4(
|
||||
changeGroupIdSet,
|
||||
currentTime,
|
||||
(Set) deleteSet,
|
||||
removeMap,
|
||||
addMap,
|
||||
(Set) addSet,
|
||||
arg_0));
|
||||
Iterator iterator = addSet.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
SyncPersonDTO syncPersonDTO = (SyncPersonDTO) iterator.next();
|
||||
if (deleteSet.contains(syncPersonDTO)) {
|
||||
deleteSet.remove(syncPersonDTO);
|
||||
iterator.remove();
|
||||
continue;
|
||||
}
|
||||
if (!StringUtils.isBlank((CharSequence) syncPersonDTO.getImageId())) continue;
|
||||
iterator.remove();
|
||||
}
|
||||
Scheduler scheduler =
|
||||
this.taskExecClient.getScheduler(this.quartzTaskProperties.getSchedulerName());
|
||||
for (Map.Entry<Long, Set<SyncPersonLocal>> entry :
|
||||
((Map<Long, Set<SyncPersonLocal>>) (Map) removeMap).entrySet()) {
|
||||
Long l = (Long) entry.getKey();
|
||||
lockValue = SnowFlake.nextId();
|
||||
try {
|
||||
if (this.validateJobGroupLock(l, lockValue)) {
|
||||
String dataSet;
|
||||
TriggerKey triggerKey =
|
||||
TriggerKey.triggerKey((String) l.toString(), (String) "QZ_PERSON_VALIDATE_JOB");
|
||||
Trigger trigger = scheduler.getTrigger(triggerKey);
|
||||
if (trigger == null
|
||||
|| !StringUtils.isNotBlank(
|
||||
(CharSequence)
|
||||
(dataSet = trigger.getJobDataMap().getString("VALIDATE_TRIGGER_KEY"))))
|
||||
continue;
|
||||
List<SyncPersonLocal> syncPersonDTOS =
|
||||
JsonUtils.toObjList(dataSet, SyncPersonLocal.class);
|
||||
syncPersonDTOS =
|
||||
CpImageStorePersonValidateManager.removeAll(syncPersonDTOS, entry.getValue());
|
||||
if (addMap.containsKey(l)) {
|
||||
Set keyAddSet = (Set) addMap.get(l);
|
||||
syncPersonDTOS = CpImageStorePersonValidateManager.addAll(syncPersonDTOS, keyAddSet);
|
||||
addMap.remove(l);
|
||||
}
|
||||
trigger.getJobDataMap().put("VALIDATE_TRIGGER_KEY", JsonUtils.toJson(syncPersonDTOS));
|
||||
scheduler.rescheduleJob(triggerKey, trigger);
|
||||
continue;
|
||||
}
|
||||
log.error("CpImageStorePersonValidateManager addValidateData removeJob time out");
|
||||
} catch (SchedulerException e) {
|
||||
log.error("获取trigger异常:{}", (Object) e.getLocalizedMessage());
|
||||
} catch (Exception e) {
|
||||
log.error("移除trigger未知异常:{}", (Object) e.getMessage());
|
||||
} finally {
|
||||
this.validateJobGroupUnLock(l, lockValue);
|
||||
}
|
||||
}
|
||||
for (Map.Entry<Long, Set<SyncPersonLocal>> entry :
|
||||
((Map<Long, Set<SyncPersonLocal>>) (Map) addMap).entrySet()) {
|
||||
if (((Set) entry.getValue()).isEmpty()) continue;
|
||||
Long l = (Long) entry.getKey();
|
||||
lockValue = SnowFlake.nextId();
|
||||
Long addValidateTime = currentTime + this.delayAddValidateHour * 60L * 60L * 1000L;
|
||||
if (this.delayAddValidateData.booleanValue() && l > addValidateTime) continue;
|
||||
try {
|
||||
if (this.validateJobGroupLock(l, lockValue)) {
|
||||
TriggerKey triggerKey =
|
||||
TriggerKey.triggerKey((String) l.toString(), (String) "QZ_PERSON_VALIDATE_JOB");
|
||||
Trigger trigger = scheduler.getTrigger(triggerKey);
|
||||
if (trigger == null) {
|
||||
trigger =
|
||||
TriggerBuilder.newTrigger()
|
||||
.withIdentity(l.toString(), "QZ_PERSON_VALIDATE_JOB")
|
||||
.withDescription("trigger at:" + l)
|
||||
.forJob("PERSON_VALIDATE_JOB_NAME", "QZ_PERSON_VALIDATE_JOB")
|
||||
.startAt(new Date(l))
|
||||
.usingJobData("VALIDATE_TRIGGER_KEY", JsonUtils.toJson(entry.getValue()))
|
||||
.build();
|
||||
scheduler.scheduleJob(trigger);
|
||||
continue;
|
||||
}
|
||||
String dataSet = trigger.getJobDataMap().getString("VALIDATE_TRIGGER_KEY");
|
||||
List<SyncPersonLocal> syncPersonDtoList =
|
||||
StringUtils.isNotBlank((CharSequence) dataSet)
|
||||
? JsonUtils.toObjList(dataSet, SyncPersonLocal.class)
|
||||
: new ArrayList<>();
|
||||
syncPersonDtoList =
|
||||
CpImageStorePersonValidateManager.addAll(syncPersonDtoList, entry.getValue());
|
||||
trigger.getJobDataMap().put("VALIDATE_TRIGGER_KEY", JsonUtils.toJson(syncPersonDtoList));
|
||||
scheduler.rescheduleJob(triggerKey, trigger);
|
||||
continue;
|
||||
}
|
||||
log.error("CpImageStorePersonValidateManager addValidateData addOrModJob time out");
|
||||
} catch (SchedulerException e) {
|
||||
log.error("添加trigger异常:{}", (Object) e.getLocalizedMessage());
|
||||
} catch (Exception e) {
|
||||
log.error("添加trigger未知异常:{}", (Object) e.getMessage());
|
||||
} finally {
|
||||
this.validateJobGroupUnLock(l, lockValue);
|
||||
}
|
||||
}
|
||||
this.updateExpiryDateStatus(currentTime, syncPersonList);
|
||||
Map<String, List<SyncPersonDTO>> deleteImageMap =
|
||||
(Map<String, List<SyncPersonDTO>>)
|
||||
(Map)
|
||||
deleteSet.parallelStream()
|
||||
.collect(Collectors.groupingBy(SyncPersonDTO::getImageStoreId));
|
||||
for (Map.Entry<String, List<SyncPersonDTO>> entry : deleteImageMap.entrySet()) {
|
||||
Set<String> keySet =
|
||||
entry.getValue().parallelStream().map(s -> s.getImageId()).collect(Collectors.toSet());
|
||||
this.cpImageStorePersonTxHandler.handleImageStoreImageChange(
|
||||
(String) entry.getKey(), keySet, false);
|
||||
}
|
||||
Map<String, List<SyncPersonDTO>> addImageMap =
|
||||
(java.util.Map<
|
||||
java.lang.String, java.util.List<cn.cloudwalk.data.organization.dto.SyncPersonDTO>>)
|
||||
addSet.parallelStream().collect(Collectors.groupingBy(SyncPersonDTO::getImageStoreId));
|
||||
for (Map.Entry<String, List<SyncPersonDTO>> entry : addImageMap.entrySet()) {
|
||||
Set<String> keySet =
|
||||
entry.getValue().parallelStream()
|
||||
.map(SyncPersonDTO::getImageId)
|
||||
.collect(Collectors.toSet());
|
||||
this.cpImageStorePersonTxHandler.handleImageStoreImageChange(entry.getKey(), keySet, true);
|
||||
}
|
||||
this.cpImageStoreSyncManager.sendChangeToDevice(changeGroupIdSet, false);
|
||||
}
|
||||
|
||||
private void updateExpiryDateStatus(Long currentTime, List<SyncPersonDTO> syncPersonList) {
|
||||
GroupPersonRef groupPersonRef = new GroupPersonRef();
|
||||
syncPersonList.stream()
|
||||
.forEach(
|
||||
syncPerson -> {
|
||||
Long addValidateTime = currentTime + this.delayAddValidateHour * 60L * 60L * 1000L;
|
||||
groupPersonRef.setId(syncPerson.getGroupPersonRefId());
|
||||
groupPersonRef.setExpiryBeginDateStatus(Integer.valueOf(1));
|
||||
if (this.delayAddValidateData.booleanValue()
|
||||
&& null != syncPerson.getNewExpiryBeginDate()
|
||||
&& syncPerson.getNewExpiryBeginDate() > addValidateTime) {
|
||||
groupPersonRef.setExpiryBeginDateStatus(Integer.valueOf(0));
|
||||
}
|
||||
groupPersonRef.setExpiryEndDateStatus(Integer.valueOf(1));
|
||||
if (this.delayAddValidateData.booleanValue()
|
||||
&& null != syncPerson.getNewExpiryEndDate()
|
||||
&& syncPerson.getNewExpiryEndDate() > addValidateTime) {
|
||||
groupPersonRef.setExpiryEndDateStatus(Integer.valueOf(0));
|
||||
}
|
||||
HashSet<String> ids = new HashSet<String>();
|
||||
ids.add(groupPersonRef.getId());
|
||||
this.groupPersonRefMapper.updateStatusByIds(groupPersonRef, ids);
|
||||
});
|
||||
}
|
||||
|
||||
private boolean validateJobGroupLock(Long key, Long lockValue) {
|
||||
Long start = System.currentTimeMillis();
|
||||
log.info(
|
||||
"CpImageStorePersonValidateManager validateJobGroupLock:{},{},{}",
|
||||
new Object[] {key, lockValue, start});
|
||||
String lockKey = "validate_job_group_lock:" + key;
|
||||
while (true) {
|
||||
Long lockResult;
|
||||
if (0L
|
||||
== (lockResult =
|
||||
(Long)
|
||||
this.redisTemplate.execute(
|
||||
(RedisCallback)
|
||||
connection ->
|
||||
(Long)
|
||||
connection.eval(
|
||||
this.lockValidateJobRedisScript
|
||||
.getScriptAsString()
|
||||
.getBytes(),
|
||||
ReturnType.INTEGER,
|
||||
0,
|
||||
(byte[][])
|
||||
new byte[][] {
|
||||
lockKey.getBytes(),
|
||||
String.valueOf(lockValue).getBytes(),
|
||||
this.lockValidateJobGroupSecond.getBytes()
|
||||
})))) {
|
||||
log.info("CpImageStorePersonValidateManager validateJobGroupLock success:{}", (Object) key);
|
||||
return true;
|
||||
}
|
||||
long waitTime = System.currentTimeMillis() - start;
|
||||
log.info(
|
||||
"CpImageStorePersonValidateManager validateJobGroupLock wait:{},{}",
|
||||
(Object) key,
|
||||
(Object) waitTime);
|
||||
if (waitTime >= Long.valueOf(this.lockValidateJobGroupTimeOut)) {
|
||||
log.info(
|
||||
"CpImageStorePersonValidateManager validateJobGroupLock wait out:{}", (Object) key);
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(100L);
|
||||
continue;
|
||||
} catch (InterruptedException e) {
|
||||
log.error("CpImageStorePersonValidateManager validateJobGroupLock sleep error:", e);
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean validateJobGroupUnLock(Long key, Long lockValue) {
|
||||
log.info(
|
||||
"CpImageStorePersonValidateManager validateJobGroupUnLock:{},{}",
|
||||
(Object) key,
|
||||
(Object) lockValue);
|
||||
String lockKey = "validate_job_group_lock:" + key;
|
||||
Long lockResult =
|
||||
(Long)
|
||||
this.redisTemplate.execute(
|
||||
(RedisCallback)
|
||||
connection ->
|
||||
(Long)
|
||||
connection.eval(
|
||||
this.unlockValidateJobRedisScript.getScriptAsString().getBytes(),
|
||||
ReturnType.INTEGER,
|
||||
0,
|
||||
(byte[][])
|
||||
new byte[][] {
|
||||
lockKey.getBytes(), String.valueOf(lockValue).getBytes()
|
||||
}));
|
||||
if (0L == lockResult) {
|
||||
log.info(
|
||||
"CpImageStorePersonValidateManager validateJobGroupUnLock success:{},{}",
|
||||
(Object) key,
|
||||
(Object) lockValue);
|
||||
return true;
|
||||
}
|
||||
log.error(
|
||||
"CpImageStorePersonValidateManager validateJobGroupUnLock fail:{},{}",
|
||||
(Object) key,
|
||||
(Object) lockValue);
|
||||
return false;
|
||||
}
|
||||
|
||||
private void delDataManager(
|
||||
long currentTime,
|
||||
SyncPersonDTO syncPersonDTO,
|
||||
Set<SyncPersonDTO> deleteSet,
|
||||
Map<Long, Set<SyncPersonLocal>> removeMap,
|
||||
Map<Long, Set<SyncPersonLocal>> addMap) {
|
||||
Set timeSet;
|
||||
Long oldExpiryBeginDate = syncPersonDTO.getOldExpiryBeginDate();
|
||||
Long oldExpiryEndDate = syncPersonDTO.getOldExpiryEndDate();
|
||||
Long newExpiryBeginDate = syncPersonDTO.getNewExpiryBeginDate();
|
||||
Long newExpiryEndDate = syncPersonDTO.getNewExpiryEndDate();
|
||||
deleteSet.add(syncPersonDTO);
|
||||
if (oldExpiryBeginDate != null) {
|
||||
Set removeAddSet =
|
||||
removeMap.computeIfAbsent(oldExpiryBeginDate, k -> new ConcurrentHashSet());
|
||||
removeAddSet.add(
|
||||
new SyncPersonLocal(
|
||||
syncPersonDTO.getGroupPersonRefId(),
|
||||
syncPersonDTO.getImageStoreId(),
|
||||
syncPersonDTO.getImageId(),
|
||||
0));
|
||||
}
|
||||
if (oldExpiryEndDate != null) {
|
||||
Set removeEndSet = removeMap.computeIfAbsent(oldExpiryEndDate, k -> new ConcurrentHashSet());
|
||||
removeEndSet.add(
|
||||
new SyncPersonLocal(
|
||||
syncPersonDTO.getGroupPersonRefId(),
|
||||
syncPersonDTO.getImageStoreId(),
|
||||
syncPersonDTO.getImageId(),
|
||||
-1));
|
||||
}
|
||||
if (newExpiryBeginDate != null && newExpiryBeginDate > currentTime) {
|
||||
timeSet = addMap.computeIfAbsent(newExpiryBeginDate, k -> new ConcurrentHashSet());
|
||||
timeSet.add(
|
||||
new SyncPersonLocal(
|
||||
syncPersonDTO.getGroupPersonRefId(),
|
||||
syncPersonDTO.getImageStoreId(),
|
||||
syncPersonDTO.getImageId(),
|
||||
0));
|
||||
}
|
||||
if (newExpiryEndDate != null && newExpiryEndDate > currentTime) {
|
||||
timeSet = addMap.computeIfAbsent(newExpiryEndDate, k -> new ConcurrentHashSet());
|
||||
timeSet.add(
|
||||
new SyncPersonLocal(
|
||||
syncPersonDTO.getGroupPersonRefId(),
|
||||
syncPersonDTO.getImageStoreId(),
|
||||
syncPersonDTO.getImageId(),
|
||||
-1));
|
||||
}
|
||||
}
|
||||
|
||||
private void addDataManager(
|
||||
long currentTime,
|
||||
SyncPersonDTO syncPersonDTO,
|
||||
Set<SyncPersonDTO> addSet,
|
||||
Map<Long, Set<SyncPersonLocal>> removeMap,
|
||||
Map<Long, Set<SyncPersonLocal>> addMap) {
|
||||
Set timeSet;
|
||||
Long oldExpiryBeginDate = syncPersonDTO.getOldExpiryBeginDate();
|
||||
Long oldExpiryEndDate = syncPersonDTO.getOldExpiryEndDate();
|
||||
Long newExpiryBeginDate = syncPersonDTO.getNewExpiryBeginDate();
|
||||
Long newExpiryEndDate = syncPersonDTO.getNewExpiryEndDate();
|
||||
if (newExpiryBeginDate == null || newExpiryBeginDate <= currentTime) {
|
||||
addSet.add(syncPersonDTO);
|
||||
} else {
|
||||
timeSet = addMap.computeIfAbsent(newExpiryBeginDate, k -> new ConcurrentHashSet());
|
||||
timeSet.add(
|
||||
new SyncPersonLocal(
|
||||
syncPersonDTO.getGroupPersonRefId(),
|
||||
syncPersonDTO.getImageStoreId(),
|
||||
syncPersonDTO.getImageId(),
|
||||
0));
|
||||
}
|
||||
if (newExpiryEndDate != null && newExpiryEndDate <= currentTime) {
|
||||
addSet.remove(syncPersonDTO);
|
||||
} else if (newExpiryEndDate != null) {
|
||||
timeSet = addMap.computeIfAbsent(newExpiryEndDate, k -> new ConcurrentHashSet());
|
||||
timeSet.add(
|
||||
new SyncPersonLocal(
|
||||
syncPersonDTO.getGroupPersonRefId(),
|
||||
syncPersonDTO.getImageStoreId(),
|
||||
syncPersonDTO.getImageId(),
|
||||
-1));
|
||||
}
|
||||
if (oldExpiryBeginDate != null) {
|
||||
Set removeAddSet =
|
||||
removeMap.computeIfAbsent(oldExpiryBeginDate, k -> new ConcurrentHashSet());
|
||||
removeAddSet.add(
|
||||
new SyncPersonLocal(
|
||||
syncPersonDTO.getGroupPersonRefId(),
|
||||
syncPersonDTO.getImageStoreId(),
|
||||
syncPersonDTO.getImageId(),
|
||||
0));
|
||||
}
|
||||
if (oldExpiryEndDate != null) {
|
||||
Set removeEndSet = removeMap.computeIfAbsent(oldExpiryEndDate, k -> new ConcurrentHashSet());
|
||||
removeEndSet.add(
|
||||
new SyncPersonLocal(
|
||||
syncPersonDTO.getGroupPersonRefId(),
|
||||
syncPersonDTO.getImageStoreId(),
|
||||
syncPersonDTO.getImageId(),
|
||||
-1));
|
||||
}
|
||||
}
|
||||
|
||||
private void updateDataManage(
|
||||
long currentTime,
|
||||
SyncPersonDTO syncPersonDTO,
|
||||
Set<SyncPersonDTO> deleteSet,
|
||||
Set<SyncPersonDTO> addSet,
|
||||
Map<Long, Set<SyncPersonLocal>> removeMap,
|
||||
Map<Long, Set<SyncPersonLocal>> addMap) {
|
||||
Set timeSet;
|
||||
boolean addFlag;
|
||||
String oldImageId = syncPersonDTO.getOldImageId();
|
||||
Long oldExpiryBeginDate = syncPersonDTO.getOldExpiryBeginDate();
|
||||
Long oldExpiryEndDate = syncPersonDTO.getOldExpiryEndDate();
|
||||
Long newExpiryBeginDate = syncPersonDTO.getNewExpiryBeginDate();
|
||||
Long newExpiryEndDate = syncPersonDTO.getNewExpiryEndDate();
|
||||
boolean bl =
|
||||
addFlag =
|
||||
!(newExpiryBeginDate != null && newExpiryBeginDate > currentTime
|
||||
|| newExpiryEndDate != null && newExpiryEndDate <= currentTime);
|
||||
if (addFlag) {
|
||||
addSet.add(syncPersonDTO);
|
||||
}
|
||||
if (StringUtils.isNotBlank((CharSequence) oldImageId)) {
|
||||
SyncPersonDTO delDto = new SyncPersonDTO();
|
||||
BeanCopyUtils.copyProperties((Object) syncPersonDTO, (Object) delDto);
|
||||
delDto.setImageId(oldImageId);
|
||||
deleteSet.add(delDto);
|
||||
} else {
|
||||
boolean delFlag;
|
||||
boolean bl2 =
|
||||
delFlag =
|
||||
!(!StringUtils.isBlank((CharSequence) oldImageId)
|
||||
|| oldExpiryBeginDate != null && oldExpiryBeginDate > currentTime
|
||||
|| oldExpiryEndDate != null && oldExpiryEndDate <= currentTime);
|
||||
if (delFlag) {
|
||||
deleteSet.add(syncPersonDTO);
|
||||
}
|
||||
}
|
||||
if (oldExpiryBeginDate != null) {
|
||||
Set removeAddSet =
|
||||
removeMap.computeIfAbsent(oldExpiryBeginDate, k -> new ConcurrentHashSet());
|
||||
if (StringUtils.isNotBlank((CharSequence) oldImageId)) {
|
||||
removeAddSet.add(
|
||||
new SyncPersonLocal(
|
||||
syncPersonDTO.getGroupPersonRefId(),
|
||||
syncPersonDTO.getImageStoreId(),
|
||||
oldImageId,
|
||||
0));
|
||||
} else {
|
||||
removeAddSet.add(
|
||||
new SyncPersonLocal(
|
||||
syncPersonDTO.getGroupPersonRefId(),
|
||||
syncPersonDTO.getImageStoreId(),
|
||||
syncPersonDTO.getImageId(),
|
||||
0));
|
||||
}
|
||||
}
|
||||
if (oldExpiryEndDate != null) {
|
||||
Set removeEndSet = removeMap.computeIfAbsent(oldExpiryEndDate, k -> new ConcurrentHashSet());
|
||||
if (StringUtils.isNotBlank((CharSequence) oldImageId)) {
|
||||
removeEndSet.add(
|
||||
new SyncPersonLocal(
|
||||
syncPersonDTO.getGroupPersonRefId(),
|
||||
syncPersonDTO.getImageStoreId(),
|
||||
oldImageId,
|
||||
-1));
|
||||
} else {
|
||||
removeEndSet.add(
|
||||
new SyncPersonLocal(
|
||||
syncPersonDTO.getGroupPersonRefId(),
|
||||
syncPersonDTO.getImageStoreId(),
|
||||
syncPersonDTO.getImageId(),
|
||||
-1));
|
||||
}
|
||||
}
|
||||
if (newExpiryBeginDate != null && newExpiryBeginDate > currentTime) {
|
||||
timeSet = addMap.computeIfAbsent(newExpiryBeginDate, k -> new ConcurrentHashSet());
|
||||
timeSet.add(
|
||||
new SyncPersonLocal(
|
||||
syncPersonDTO.getGroupPersonRefId(),
|
||||
syncPersonDTO.getImageStoreId(),
|
||||
syncPersonDTO.getImageId(),
|
||||
0));
|
||||
}
|
||||
if (newExpiryEndDate != null && newExpiryEndDate > currentTime) {
|
||||
timeSet = addMap.computeIfAbsent(newExpiryEndDate, k -> new ConcurrentHashSet());
|
||||
timeSet.add(
|
||||
new SyncPersonLocal(
|
||||
syncPersonDTO.getGroupPersonRefId(),
|
||||
syncPersonDTO.getImageStoreId(),
|
||||
syncPersonDTO.getImageId(),
|
||||
-1));
|
||||
}
|
||||
}
|
||||
|
||||
public void syncDataToGroup(String dataJson) {
|
||||
Set<String> keySet;
|
||||
log.info(
|
||||
"CpImageStorePersonValidateManager syncDataToGroup start dataJson:{}", (Object) dataJson);
|
||||
List<SyncPersonLocal> syncPersonDTOS = JsonUtils.toObjList(dataJson, SyncPersonLocal.class);
|
||||
Map<Integer, List<SyncPersonLocal>> map =
|
||||
syncPersonDTOS.parallelStream().collect(Collectors.groupingBy(SyncPersonLocal::getAction));
|
||||
List<SyncPersonLocal> addList = map.get(0);
|
||||
List<SyncPersonLocal> deleteList = map.get(-1);
|
||||
if (!CollectionUtils.isEmpty(deleteList)) {
|
||||
Map<String, List<SyncPersonLocal>> deleteMap =
|
||||
deleteList.parallelStream()
|
||||
.collect(Collectors.groupingBy(SyncPersonLocal::getImageStoreId));
|
||||
for (Map.Entry<String, List<SyncPersonLocal>> entry : deleteMap.entrySet()) {
|
||||
keySet =
|
||||
entry.getValue().parallelStream()
|
||||
.map(SyncPersonLocal::getImageId)
|
||||
.collect(Collectors.toSet());
|
||||
this.cpImageStorePersonTxHandler.handleImageStoreImageChange(entry.getKey(), keySet, false);
|
||||
}
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(addList)) {
|
||||
Map<String, List<SyncPersonLocal>> addMap =
|
||||
addList.parallelStream().collect(Collectors.groupingBy(SyncPersonLocal::getImageStoreId));
|
||||
for (Map.Entry<String, List<SyncPersonLocal>> entry : addMap.entrySet()) {
|
||||
keySet =
|
||||
entry.getValue().parallelStream()
|
||||
.map(SyncPersonLocal::getImageId)
|
||||
.collect(Collectors.toSet());
|
||||
this.cpImageStorePersonTxHandler.handleImageStoreImageChange(entry.getKey(), keySet, true);
|
||||
}
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(addList)) {
|
||||
Set<String> addRefIds =
|
||||
addList.parallelStream()
|
||||
.map(SyncPersonLocal::getGroupPersonRefId)
|
||||
.collect(Collectors.toSet());
|
||||
this.cpImageStorePersonTxHandler.updateGroupPersonRefStatus((short) 0, addRefIds);
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(deleteList)) {
|
||||
Set<String> deleteRefIds =
|
||||
deleteList.parallelStream()
|
||||
.map(SyncPersonLocal::getGroupPersonRefId)
|
||||
.collect(Collectors.toSet());
|
||||
this.cpImageStorePersonTxHandler.updateGroupPersonRefStatus((short) 1, deleteRefIds);
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(syncPersonDTOS)) {
|
||||
Set<String> changeGroupIdSet =
|
||||
syncPersonDTOS.parallelStream()
|
||||
.map(SyncPersonLocal::getImageStoreId)
|
||||
.collect(Collectors.toSet());
|
||||
this.cpImageStoreSyncManager.sendChangeToDevice(changeGroupIdSet, true);
|
||||
}
|
||||
log.info("CpImageStorePersonValidateManager syncDataToGroup end");
|
||||
}
|
||||
|
||||
private static List<SyncPersonLocal> removeAll(
|
||||
List<SyncPersonLocal> list, Set<SyncPersonLocal> set) {
|
||||
if (set != null && !set.isEmpty()) {
|
||||
Iterator<SyncPersonLocal> it = set.iterator();
|
||||
while (it.hasNext()) {
|
||||
list.remove(it.next());
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private static List<SyncPersonLocal> addAll(
|
||||
List<SyncPersonLocal> list, Set<SyncPersonLocal> set) {
|
||||
if (!CollectionUtils.isEmpty(set)) {
|
||||
Iterator<SyncPersonLocal> it = set.iterator();
|
||||
while (it.hasNext()) {
|
||||
list.add(it.next());
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/*
|
||||
* WARNING - Removed try catching itself - possible behaviour change.
|
||||
*/
|
||||
public void delayAddValidateTrigger() {
|
||||
if (!this.delayAddValidateData.booleanValue()) {
|
||||
log.debug("DelayPersonValidateTask 未开启延迟添加定时任务开关");
|
||||
return;
|
||||
}
|
||||
Long currentTime = System.currentTimeMillis();
|
||||
Long delayTime = currentTime + this.delayAddValidateHour * 60L * 60L * 1000L;
|
||||
QueryGroupPersonDTO queryGroupPersonDTO = new QueryGroupPersonDTO();
|
||||
queryGroupPersonDTO.setStartTime(currentTime);
|
||||
queryGroupPersonDTO.setEndTime(delayTime);
|
||||
queryGroupPersonDTO.setExpiryBeginDateStatus(Integer.valueOf(0));
|
||||
queryGroupPersonDTO.setExpiryEndDateStatus(Integer.valueOf(0));
|
||||
List<GroupPersonRef> waitAddValidateList =
|
||||
this.groupPersonRefMapper.queryByExpiryDateStatus(queryGroupPersonDTO);
|
||||
if (CollectionUtils.isEmpty((Collection) waitAddValidateList)) {
|
||||
log.debug(
|
||||
"[{}-{}]时间范围内没有需要添加的trigger",
|
||||
(Object) queryGroupPersonDTO.getStartTime(),
|
||||
(Object) queryGroupPersonDTO.getEndTime());
|
||||
}
|
||||
ConcurrentHashMap addMap = new ConcurrentHashMap();
|
||||
ConcurrentHashSet addSet = new ConcurrentHashSet();
|
||||
ConcurrentHashSet deleteSet = new ConcurrentHashSet();
|
||||
HashSet changeGroupIdSet = Sets.newHashSet();
|
||||
ArrayList syncPersonList = Lists.newArrayListWithCapacity((int) waitAddValidateList.size());
|
||||
waitAddValidateList =
|
||||
(List)
|
||||
waitAddValidateList.stream()
|
||||
.sorted(Comparator.comparing(GroupPersonRef::getExpiryBeginDate))
|
||||
.collect(Collectors.toList());
|
||||
waitAddValidateList.stream()
|
||||
.forEach(
|
||||
arg_0 ->
|
||||
this.lambda$delayAddValidateTrigger$24(
|
||||
changeGroupIdSet,
|
||||
syncPersonList,
|
||||
currentTime,
|
||||
(Set) addSet,
|
||||
delayTime,
|
||||
addMap,
|
||||
(Set) deleteSet,
|
||||
arg_0));
|
||||
Iterator iterator = addSet.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
SyncPersonDTO syncPersonDTO = (SyncPersonDTO) iterator.next();
|
||||
if (deleteSet.contains(syncPersonDTO)) {
|
||||
deleteSet.remove(syncPersonDTO);
|
||||
iterator.remove();
|
||||
continue;
|
||||
}
|
||||
if (!StringUtils.isBlank((CharSequence) syncPersonDTO.getImageId())) continue;
|
||||
iterator.remove();
|
||||
}
|
||||
Scheduler scheduler =
|
||||
this.taskExecClient.getScheduler(this.quartzTaskProperties.getSchedulerName());
|
||||
for (Map.Entry<Long, Set<SyncPersonLocal>> entry :
|
||||
((Map<Long, Set<SyncPersonLocal>>) (Map) addMap).entrySet()) {
|
||||
if (((Set) entry.getValue()).isEmpty()) continue;
|
||||
Long l = (Long) entry.getKey();
|
||||
Long lockValue = SnowFlake.nextId();
|
||||
try {
|
||||
if (this.validateJobGroupLock(l, lockValue)) {
|
||||
TriggerKey triggerKey =
|
||||
TriggerKey.triggerKey((String) l.toString(), (String) "QZ_PERSON_VALIDATE_JOB");
|
||||
Trigger trigger = scheduler.getTrigger(triggerKey);
|
||||
if (trigger == null) {
|
||||
trigger =
|
||||
TriggerBuilder.newTrigger()
|
||||
.withIdentity(l.toString(), "QZ_PERSON_VALIDATE_JOB")
|
||||
.withDescription("trigger at:" + l)
|
||||
.forJob("PERSON_VALIDATE_JOB_NAME", "QZ_PERSON_VALIDATE_JOB")
|
||||
.startAt(new Date(l))
|
||||
.usingJobData("VALIDATE_TRIGGER_KEY", JsonUtils.toJson(entry.getValue()))
|
||||
.build();
|
||||
scheduler.scheduleJob(trigger);
|
||||
continue;
|
||||
}
|
||||
String dataSet = trigger.getJobDataMap().getString("VALIDATE_TRIGGER_KEY");
|
||||
List<SyncPersonLocal> syncPersonDtoList =
|
||||
StringUtils.isNotBlank((CharSequence) dataSet)
|
||||
? JsonUtils.toObjList(dataSet, SyncPersonLocal.class)
|
||||
: new ArrayList<>();
|
||||
syncPersonDtoList =
|
||||
CpImageStorePersonValidateManager.addAll(syncPersonDtoList, entry.getValue());
|
||||
trigger.getJobDataMap().put("VALIDATE_TRIGGER_KEY", JsonUtils.toJson(syncPersonDtoList));
|
||||
scheduler.rescheduleJob(triggerKey, trigger);
|
||||
continue;
|
||||
}
|
||||
log.error("CpImageStorePersonValidateManager addValidateData addOrModJob time out");
|
||||
} catch (SchedulerException e) {
|
||||
log.error("添加trigger异常:{}", (Object) e.getLocalizedMessage());
|
||||
} catch (Exception e) {
|
||||
log.error("添加trigger未知异常:{}", (Object) e.getMessage());
|
||||
} finally {
|
||||
this.validateJobGroupUnLock(l, lockValue);
|
||||
}
|
||||
}
|
||||
this.updateExpiryDateStatus(currentTime, syncPersonList);
|
||||
Map<String, List<SyncPersonDTO>> deleteImageMap =
|
||||
(Map<String, List<SyncPersonDTO>>)
|
||||
(Map)
|
||||
deleteSet.parallelStream()
|
||||
.collect(Collectors.groupingBy(SyncPersonDTO::getImageStoreId));
|
||||
for (Map.Entry<String, List<SyncPersonDTO>> entry : deleteImageMap.entrySet()) {
|
||||
Set<String> keySet =
|
||||
entry.getValue().parallelStream().map(s -> s.getImageId()).collect(Collectors.toSet());
|
||||
this.cpImageStorePersonTxHandler.handleImageStoreImageChange(
|
||||
(String) entry.getKey(), keySet, false);
|
||||
}
|
||||
Map<String, List<SyncPersonDTO>> addImageMap =
|
||||
(java.util.Map<
|
||||
java.lang.String, java.util.List<cn.cloudwalk.data.organization.dto.SyncPersonDTO>>)
|
||||
addSet.parallelStream().collect(Collectors.groupingBy(SyncPersonDTO::getImageStoreId));
|
||||
for (Map.Entry<String, List<SyncPersonDTO>> entry : addImageMap.entrySet()) {
|
||||
Set<String> keySet =
|
||||
entry.getValue().parallelStream()
|
||||
.map(SyncPersonDTO::getImageId)
|
||||
.collect(Collectors.toSet());
|
||||
this.cpImageStorePersonTxHandler.handleImageStoreImageChange(entry.getKey(), keySet, true);
|
||||
}
|
||||
this.cpImageStoreSyncManager.sendChangeToDevice(changeGroupIdSet, false);
|
||||
}
|
||||
|
||||
private /* synthetic */ void lambda$delayAddValidateTrigger$24(
|
||||
Set changeGroupIdSet,
|
||||
List syncPersonList,
|
||||
Long currentTime,
|
||||
Set addSet,
|
||||
Long delayTime,
|
||||
Map addMap,
|
||||
Set deleteSet,
|
||||
GroupPersonRef waitAddValidate) {
|
||||
Set timeSet;
|
||||
waitAddValidate.setExpiryBeginDate(
|
||||
(Long)
|
||||
Optional.ofNullable(waitAddValidate.getExpiryBeginDate())
|
||||
.map(date -> date / 1000L * 1000L)
|
||||
.orElse(null));
|
||||
waitAddValidate.setExpiryEndDate(
|
||||
(Long)
|
||||
Optional.ofNullable(waitAddValidate.getExpiryEndDate())
|
||||
.map(date -> date / 1000L * 1000L)
|
||||
.orElse(null));
|
||||
changeGroupIdSet.add(waitAddValidate.getImageStoreId());
|
||||
if (waitAddValidate.getExpiryBeginDateStatus() == 0) {
|
||||
SyncPersonDTO addSyncPersonDTO =
|
||||
this.cpImageStorePersonTxHandler.generateSyncPersonDTO(waitAddValidate, 0, null, null);
|
||||
syncPersonList.add(addSyncPersonDTO);
|
||||
if (waitAddValidate.getExpiryBeginDate() <= currentTime) {
|
||||
addSet.add(addSyncPersonDTO);
|
||||
} else if (waitAddValidate.getExpiryBeginDate() <= delayTime) {
|
||||
timeSet =
|
||||
(java.util.Set)
|
||||
addMap.computeIfAbsent(
|
||||
waitAddValidate.getExpiryBeginDate(), k -> new ConcurrentHashSet());
|
||||
timeSet.add(
|
||||
new SyncPersonLocal(
|
||||
addSyncPersonDTO.getGroupPersonRefId(),
|
||||
addSyncPersonDTO.getImageStoreId(),
|
||||
addSyncPersonDTO.getImageId(),
|
||||
0));
|
||||
}
|
||||
}
|
||||
if (waitAddValidate.getExpiryEndDateStatus() == 0) {
|
||||
SyncPersonDTO deleteSyncPersonDTO =
|
||||
this.cpImageStorePersonTxHandler.generateSyncPersonDTO(waitAddValidate, -1, null, null);
|
||||
syncPersonList.add(deleteSyncPersonDTO);
|
||||
if (waitAddValidate.getExpiryEndDate() <= currentTime) {
|
||||
deleteSet.add(deleteSyncPersonDTO);
|
||||
} else if (waitAddValidate.getExpiryEndDate() <= delayTime) {
|
||||
timeSet =
|
||||
(java.util.Set)
|
||||
addMap.computeIfAbsent(
|
||||
waitAddValidate.getExpiryEndDate(), k -> new ConcurrentHashSet());
|
||||
timeSet.add(
|
||||
new SyncPersonLocal(
|
||||
deleteSyncPersonDTO.getGroupPersonRefId(),
|
||||
deleteSyncPersonDTO.getImageStoreId(),
|
||||
deleteSyncPersonDTO.getImageId(),
|
||||
-1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private /* synthetic */ void lambda$addValidateData$4(
|
||||
Set changeGroupIdSet,
|
||||
long currentTime,
|
||||
Set deleteSet,
|
||||
Map removeMap,
|
||||
Map addMap,
|
||||
Set addSet,
|
||||
SyncPersonDTO syncPersonDTO) {
|
||||
syncPersonDTO.setOldExpiryBeginDate(
|
||||
(Long)
|
||||
Optional.ofNullable(syncPersonDTO.getOldExpiryBeginDate())
|
||||
.map(date -> date / 1000L * 1000L)
|
||||
.orElse(null));
|
||||
syncPersonDTO.setOldExpiryEndDate(
|
||||
(Long)
|
||||
Optional.ofNullable(syncPersonDTO.getOldExpiryEndDate())
|
||||
.map(date -> date / 1000L * 1000L)
|
||||
.orElse(null));
|
||||
syncPersonDTO.setNewExpiryBeginDate(
|
||||
(Long)
|
||||
Optional.ofNullable(syncPersonDTO.getNewExpiryBeginDate())
|
||||
.map(date -> date / 1000L * 1000L)
|
||||
.orElse(null));
|
||||
syncPersonDTO.setNewExpiryEndDate(
|
||||
(Long)
|
||||
Optional.ofNullable(syncPersonDTO.getNewExpiryEndDate())
|
||||
.map(date -> date / 1000L * 1000L)
|
||||
.orElse(null));
|
||||
changeGroupIdSet.add(syncPersonDTO.getImageStoreId());
|
||||
int action = syncPersonDTO.getAction();
|
||||
switch (action) {
|
||||
case -1:
|
||||
{
|
||||
this.delDataManager(currentTime, syncPersonDTO, deleteSet, removeMap, addMap);
|
||||
break;
|
||||
}
|
||||
case 0:
|
||||
{
|
||||
this.addDataManager(currentTime, syncPersonDTO, addSet, removeMap, addMap);
|
||||
break;
|
||||
}
|
||||
case 1:
|
||||
{
|
||||
this.updateDataManage(currentTime, syncPersonDTO, deleteSet, addSet, removeMap, addMap);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class SyncPersonLocal {
|
||||
private String groupPersonRefId;
|
||||
private String imageStoreId;
|
||||
private String imageId;
|
||||
private int action;
|
||||
|
||||
public SyncPersonLocal() {}
|
||||
|
||||
public SyncPersonLocal(
|
||||
String groupPersonRefId, String imageStoreId, String imageId, int action) {
|
||||
this.groupPersonRefId = groupPersonRefId;
|
||||
this.imageStoreId = imageStoreId;
|
||||
this.imageId = imageId;
|
||||
this.action = action;
|
||||
}
|
||||
|
||||
public boolean equals(Object o) {
|
||||
if (o == this) {
|
||||
return true;
|
||||
}
|
||||
if (!(o instanceof SyncPersonLocal)) {
|
||||
return false;
|
||||
}
|
||||
SyncPersonLocal other = (SyncPersonLocal) o;
|
||||
return this.getAction() == other.getAction()
|
||||
&& (this.getGroupPersonRefId() == null && other.getGroupPersonRefId() == null
|
||||
|| this.getGroupPersonRefId() != null
|
||||
&& this.getGroupPersonRefId().equals(other.getGroupPersonRefId()))
|
||||
&& (this.getImageId() == null && other.getImageId() == null
|
||||
|| this.getImageId() != null && this.getImageId().equals(other.getImageId()))
|
||||
&& (this.getImageStoreId() == null && other.getImageStoreId() == null
|
||||
|| this.getImageStoreId() != null
|
||||
&& this.getImageStoreId().equals(other.getImageStoreId()));
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return super.hashCode();
|
||||
}
|
||||
|
||||
public String getGroupPersonRefId() {
|
||||
return this.groupPersonRefId;
|
||||
}
|
||||
|
||||
public String getImageStoreId() {
|
||||
return this.imageStoreId;
|
||||
}
|
||||
|
||||
public String getImageId() {
|
||||
return this.imageId;
|
||||
}
|
||||
|
||||
public int getAction() {
|
||||
return this.action;
|
||||
}
|
||||
|
||||
public void setGroupPersonRefId(String groupPersonRefId) {
|
||||
this.groupPersonRefId = groupPersonRefId;
|
||||
}
|
||||
|
||||
public void setImageStoreId(String imageStoreId) {
|
||||
this.imageStoreId = imageStoreId;
|
||||
}
|
||||
|
||||
public void setImageId(String imageId) {
|
||||
this.imageId = imageId;
|
||||
}
|
||||
|
||||
public void setAction(int action) {
|
||||
this.action = action;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "CpImageStorePersonValidateManager.SyncPersonLocal(groupPersonRefId="
|
||||
+ this.getGroupPersonRefId()
|
||||
+ ", imageStoreId="
|
||||
+ this.getImageStoreId()
|
||||
+ ", imageId="
|
||||
+ this.getImageId()
|
||||
+ ", action="
|
||||
+ this.getAction()
|
||||
+ ")";
|
||||
}
|
||||
}
|
||||
}
|
||||
+827
@@ -0,0 +1,827 @@
|
||||
/*
|
||||
* 自 vendor cwos-component-organization-service-v2.9.2_xinghewan 反编译恢复;与现场逻辑一致。
|
||||
* 原因为 reactor 曾排除 vendor jar 导致该 @Service 未打入 classpath。
|
||||
*/
|
||||
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.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.ImgStorePerson;
|
||||
import cn.cloudwalk.data.organization.entity.IsImageStoreAssociated;
|
||||
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 cn.cloudwalk.service.organization.service.CpImageStorePersonManager;
|
||||
import cn.cloudwalk.service.organization.service.CpImageStorePersonSynManager;
|
||||
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.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
|
||||
@SuppressWarnings({"rawtypes", "unchecked"})
|
||||
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(value="${cloudwalk.imagestore.person.searchSize:2}")
|
||||
private int searchSize;
|
||||
|
||||
@Transactional(rollbackFor={Exception.class})
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<String> add(AddImageStoreParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
CloudwalkResult addResult;
|
||||
List<IsImageStoreAssociated> imageStoreAssociatedList;
|
||||
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((CharSequence)param.getBusinessId())) {
|
||||
addParam.setBusinessId(context.getCompany().getCompanyId());
|
||||
}
|
||||
if ((imageStoreAssociatedList = this.addBaseImageStore((BaseImageStoreParam)param, context, imageStoreId, addParam.getBusinessId())).size() > 0) {
|
||||
this.isImageStoreAssociatedMapper.batchInsert(imageStoreAssociatedList);
|
||||
}
|
||||
if (!(addResult = this.agImageStoreService.add(addParam, context)).isSuccess()) {
|
||||
throw new ServiceException(addResult.getCode(), addResult.getMessage());
|
||||
}
|
||||
this.cpImageStorePersonSynManager.addGroupPersonSynTask(Lists.newArrayList(imageStoreId), "isAll");
|
||||
return CloudwalkResult.<String>success(imageStoreId);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor={Exception.class})
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<Boolean> edit(EditImageStoreParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
CloudwalkResult editResult;
|
||||
this.checkExistAndStatus(param.getImageStoreId());
|
||||
AgImageStoreEditParam editParam = new AgImageStoreEditParam();
|
||||
editParam.setId(param.getImageStoreId());
|
||||
editParam.setName(param.getName());
|
||||
String businessId = param.getBusinessId();
|
||||
if (StringUtils.isBlank((CharSequence)businessId)) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
List<IsImageStoreAssociated> imageStoreAssociatedList = this.addBaseImageStore((BaseImageStoreParam)param, context, param.getImageStoreId(), businessId);
|
||||
if (this.checkAssociatedIsChange(param.getImageStoreId(), imageStoreAssociatedList)) {
|
||||
this.isImageStoreAssociatedMapper.deleteAllByImageId(param.getImageStoreId());
|
||||
if (imageStoreAssociatedList.size() > 0) {
|
||||
this.isImageStoreAssociatedMapper.batchInsert(imageStoreAssociatedList);
|
||||
}
|
||||
editParam.setStatus(SyncStatusEnum.SYNC_WAIT.getCode());
|
||||
}
|
||||
if (!(editResult = this.agImageStoreService.edit(editParam, context)).isSuccess()) {
|
||||
throw new ServiceException(editResult.getCode(), editResult.getMessage());
|
||||
}
|
||||
this.cpImageStorePersonSynManager.addGroupPersonSynTask(Lists.newArrayList(param.getImageStoreId()), "isAll");
|
||||
return CloudwalkResult.<Boolean>success(Boolean.TRUE);
|
||||
}
|
||||
|
||||
private boolean checkAssociatedIsChange(String imageStoreId, List<IsImageStoreAssociated> associatedListAfterUpdate) {
|
||||
GetsImageStoreAssociatedDTO queryDTO = new GetsImageStoreAssociatedDTO();
|
||||
queryDTO.setImageStoreId(imageStoreId);
|
||||
List<IsImageStoreAssociated> associatedListBeforeUpdate =
|
||||
(List<IsImageStoreAssociated>) (List) this.isImageStoreAssociatedMapper.gets(queryDTO);
|
||||
if (CollectionUtils.isEmpty((Collection)associatedListBeforeUpdate) && CollectionUtils.isEmpty(associatedListAfterUpdate)) {
|
||||
return false;
|
||||
}
|
||||
if (associatedListBeforeUpdate.size() != associatedListAfterUpdate.size()) {
|
||||
return true;
|
||||
}
|
||||
HashSet<String> associatedStrBeforeUpdate = new HashSet<String>(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());
|
||||
}
|
||||
HashSet<String> associatedStrAfterUpdate = new HashSet<String>(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 {
|
||||
this.checkAppRefByImageStoreIdForDelete(param.getId(), context);
|
||||
this.checkExistAndStatus(param.getId());
|
||||
QueryGroupPersonDTO queryDTO = new QueryGroupPersonDTO();
|
||||
queryDTO.setImageStoreId(param.getId());
|
||||
queryDTO.setIsDel(Short.valueOf(DelStatusEnum.NORAML.getCode()));
|
||||
List 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 delete = this.agImageStoreService.delete((AgImageStoreKeyParam)BeanCopyUtils.copyProperties((Object)param, AgImageStoreKeyParam.class), context);
|
||||
if (!delete.isSuccess()) {
|
||||
throw new ServiceException(delete.getCode(), delete.getMessage());
|
||||
}
|
||||
return CloudwalkResult.<Boolean>success(Boolean.TRUE);
|
||||
}
|
||||
|
||||
private void checkAppRefByImageStoreIdForDelete(String imageStoreId, CloudwalkCallContext context) throws ServiceException {
|
||||
ApplicationImageStoreQueryParam queryParam = new ApplicationImageStoreQueryParam();
|
||||
queryParam.setImageStoreId(imageStoreId);
|
||||
CloudwalkResult queryResult = this.applicationImageStoreService.query(queryParam, context);
|
||||
if (!queryResult.isSuccess()) {
|
||||
throw new ServiceException(queryResult.getCode(), queryResult.getMessage());
|
||||
}
|
||||
if (!CollectionUtils.isEmpty((Collection)((Collection)queryResult.getData()))) {
|
||||
throw new ServiceException("53013545", this.getMessage("53013545"));
|
||||
}
|
||||
}
|
||||
|
||||
public CloudwalkResult<CloudwalkPageAble<PageImageStoreResult>> page(QueryImageStoreParam queryImageStoreParam, CloudwalkCallContext context) throws ServiceException {
|
||||
CloudwalkResult agPageResult;
|
||||
boolean isEnd = this.handleQueryParam(queryImageStoreParam);
|
||||
if (isEnd) {
|
||||
return CloudwalkResult.success(
|
||||
new CloudwalkPageAble<PageImageStoreResult>(
|
||||
new ArrayList<PageImageStoreResult>(),
|
||||
new CloudwalkPageInfo(
|
||||
queryImageStoreParam.getCurrentPage(), queryImageStoreParam.getRowsOfPage()),
|
||||
0L));
|
||||
}
|
||||
AgImageStoreQueryParam queryParam = (AgImageStoreQueryParam)BeanCopyUtils.copyProperties((Object)queryImageStoreParam, AgImageStoreQueryParam.class);
|
||||
if (StringUtils.isBlank((CharSequence)queryParam.getBusinessId())) {
|
||||
queryParam.setBusinessId(context.getCompany().getCompanyId());
|
||||
}
|
||||
if (!(agPageResult = this.agImageStoreService.page(queryParam)).isSuccess()) {
|
||||
return CloudwalkResult.fail((String)agPageResult.getCode(), (String)agPageResult.getMessage());
|
||||
}
|
||||
if (agPageResult.getData() == null) {
|
||||
return CloudwalkResult.success(
|
||||
new CloudwalkPageAble<PageImageStoreResult>(
|
||||
new ArrayList<PageImageStoreResult>(),
|
||||
new CloudwalkPageInfo(queryParam.getCurrentPage(), queryParam.getRowsOfPage()),
|
||||
0L));
|
||||
}
|
||||
List<PageImageStoreResult> resultList = this.packageCpResult(((CloudwalkPageAble)agPageResult.getData()).getDatas(), queryParam.getBusinessId());
|
||||
CloudwalkPageAble<?> pageData = (CloudwalkPageAble<?>) agPageResult.getData();
|
||||
return CloudwalkResult.success(
|
||||
new CloudwalkPageAble<PageImageStoreResult>(
|
||||
resultList,
|
||||
new CloudwalkPageInfo((int) pageData.getCurrentPage(), (int) pageData.getPageSize()),
|
||||
pageData.getTotalRows()));
|
||||
}
|
||||
|
||||
public CloudwalkResult<List<ImageStoreResult>> list(QueryImageStoreParam queryImageStoreParam, CloudwalkCallContext cloudwalkContext) throws ServiceException {
|
||||
CloudwalkResult agQueryResult;
|
||||
List<ImageStoreResult> resultList = new ArrayList<ImageStoreResult>();
|
||||
boolean isEnd = this.handleQueryParam(queryImageStoreParam);
|
||||
if (isEnd) {
|
||||
return CloudwalkResult.success(resultList);
|
||||
}
|
||||
AgImageStoreQueryParam queryParam = (AgImageStoreQueryParam)BeanCopyUtils.copyProperties((Object)queryImageStoreParam, AgImageStoreQueryParam.class);
|
||||
if (StringUtils.isBlank((CharSequence)queryParam.getBusinessId())) {
|
||||
queryParam.setBusinessId(cloudwalkContext.getCompany().getCompanyId());
|
||||
}
|
||||
if (!(agQueryResult = this.agImageStoreService.query(queryParam)).isSuccess()) {
|
||||
return CloudwalkResult.fail((String)agQueryResult.getCode(), (String)agQueryResult.getMessage());
|
||||
}
|
||||
if (!CollectionUtils.isEmpty((Collection)queryImageStoreParam.getLabelIds())) {
|
||||
GetsImageStoreAssociatedDTO get = new GetsImageStoreAssociatedDTO();
|
||||
get.setAssociatedObjectIds((Collection)queryImageStoreParam.getLabelIds());
|
||||
get.setAssociatedObjectIdType(Integer.valueOf(2));
|
||||
List<IsImageStoreAssociated> associateds =
|
||||
(List<IsImageStoreAssociated>) (List) this.isImageStoreAssociatedMapper.gets(get);
|
||||
if (CollectionUtils.isEmpty((Collection) associateds)) {
|
||||
return CloudwalkResult.success(resultList);
|
||||
}
|
||||
List<String> imageStoreIds = Collections3.extractToList(associateds, "imageStoreId");
|
||||
List<AgImageStoreResult> agList = (List<AgImageStoreResult>) agQueryResult.getData();
|
||||
List<AgImageStoreResult> collect =
|
||||
agList.stream().filter(a -> imageStoreIds.contains(a.getId())).collect(Collectors.toList());
|
||||
agQueryResult.setData(collect);
|
||||
}
|
||||
resultList =
|
||||
this.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 queryResult = this.agImageStoreService.query(queryParam);
|
||||
if (!queryResult.isSuccess()) {
|
||||
return CloudwalkResult.fail((String)queryResult.getCode(), (String)queryResult.getMessage());
|
||||
}
|
||||
if (CollectionUtils.isEmpty((Collection)((Collection)queryResult.getData()))) {
|
||||
return CloudwalkResult.fail((String)"53013502", (String)this.getMessage("53013502"));
|
||||
}
|
||||
AgImageStoreResult agImageStoreResult = (AgImageStoreResult)((List)queryResult.getData()).get(0);
|
||||
ImageStoreDetailResult result = (ImageStoreDetailResult)BeanCopyUtils.copyProperties((Object)agImageStoreResult, ImageStoreDetailResult.class);
|
||||
result.setPersonNum(this.getPersonNum(agImageStoreResult.getId()));
|
||||
try {
|
||||
result.setBusinessName(this.getBusinessName(result.getBusinessId()));
|
||||
}
|
||||
catch (ServiceException e) {
|
||||
this.logger.error("\u67e5\u8be2\u4f01\u4e1a\u540d\u79f0\u9519\u8befe:{}", (Object)e.getMessage());
|
||||
return CloudwalkResult.fail((String)e.getCode(), (String)e.getMessage());
|
||||
}
|
||||
try {
|
||||
result.setSourceApplicationName(this.getSourceApplicationName(result.getSourceApplicationId()));
|
||||
}
|
||||
catch (ServiceException e) {
|
||||
this.logger.error("\u67e5\u8be2\u6765\u6e90\u5e94\u7528\u540d\u79f0\u9519\u8befe:{}", (Object)e.getMessage());
|
||||
return CloudwalkResult.fail((String)e.getCode(), (String)e.getMessage());
|
||||
}
|
||||
this.getAssociated(result);
|
||||
DeviceImageStoreQueryParam deviceParam = new DeviceImageStoreQueryParam();
|
||||
deviceParam.setImageStoreId(param.getId());
|
||||
CloudwalkResult deviceResult = this.deviceImageStoreService.query(deviceParam, context);
|
||||
if (deviceResult.isSuccess()) {
|
||||
result.setDevices(this.getDeviceList((List)deviceResult.getData(), context));
|
||||
} else {
|
||||
this.logger.error("\u56fe\u5e93\u8be6\u60c5\u5173\u8054\u8bbe\u5907\u540d\u79f0\u83b7\u53d6\u5931\u8d25\uff0cresult:[{}]", (Object)JSONObject.toJSONString((Object)deviceResult));
|
||||
}
|
||||
ApplicationImageStoreQueryParam appParam = new ApplicationImageStoreQueryParam();
|
||||
appParam.setImageStoreId(param.getId());
|
||||
CloudwalkResult appResult = this.applicationImageStoreService.query(appParam, context);
|
||||
if (appResult.isSuccess()) {
|
||||
result.setApplicationNames(Collections3.extractToList((Collection)((Collection)appResult.getData()), (String)"applicationName"));
|
||||
} else {
|
||||
this.logger.error("\u56fe\u5e93\u8be6\u60c5\u5173\u8054\u5e94\u7528\u540d\u79f0\u83b7\u53d6\u5931\u8d25\uff0cresult:[{}]", (Object)JSONObject.toJSONString((Object)appResult));
|
||||
}
|
||||
return CloudwalkResult.success(result);
|
||||
}
|
||||
|
||||
private List<DeviceInfoResult> getDeviceList(List<DeviceImageStoreQueryResult> resultList, CloudwalkCallContext context) {
|
||||
ArrayList<DeviceInfoResult> list = Lists.newArrayListWithCapacity(resultList.size());
|
||||
try {
|
||||
List<String> deviceIds =
|
||||
resultList.stream().map(DeviceImageStoreQueryResult::getDeviceId).collect(Collectors.toList());
|
||||
CoreDeviceQueryParam param = new CoreDeviceQueryParam();
|
||||
param.setIds(deviceIds);
|
||||
param.setBusinessId(context.getCompany().getCompanyId());
|
||||
CloudwalkResult deviceResult = this.atomicDeviceService.list(param, context);
|
||||
Map<String, String> deviceMap = new HashMap<String, String>();
|
||||
if (deviceResult.isSuccess() && deviceResult.getData() != null) {
|
||||
for (AtomicDeviceGetResult device :
|
||||
(List<AtomicDeviceGetResult>) (List) deviceResult.getData()) {
|
||||
deviceMap.put(device.getId(), device.getDeviceCode());
|
||||
}
|
||||
}
|
||||
for (DeviceImageStoreQueryResult result : resultList) {
|
||||
DeviceInfoResult dr = new DeviceInfoResult();
|
||||
dr.setDeviceId(result.getDeviceId());
|
||||
dr.setDeviceCode((String)deviceMap.get(result.getDeviceId()));
|
||||
dr.setDeviceName(result.getDeviceName());
|
||||
dr.setIdentifyType(result.getIdentifyType());
|
||||
list.add(dr);
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
this.logger.error("exception:{}", (Object)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(this.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 = this.getAssociated(associatedParam.getObjectId(), time, userId, imageStoreId, action, objectType);
|
||||
associated.setExpiryBeginDate(associatedParam.getExpiryBeginDate());
|
||||
associated.setExpiryEndDate(associatedParam.getExpiryEndDate());
|
||||
associated.setValidDateCron(null);
|
||||
if (!CollectionUtils.isEmpty((Collection)associatedParam.getValidDateCron())) {
|
||||
associated.setValidDateCron(JSON.toJSONString((Object)associatedParam.getValidDateCron()));
|
||||
}
|
||||
return associated;
|
||||
}
|
||||
|
||||
private List<IsImageStoreAssociated> addBaseImageStore(BaseImageStoreParam param, CloudwalkCallContext context, String imageStoreId, String businessId) throws ServiceException {
|
||||
long time = System.currentTimeMillis();
|
||||
List<String> includePersonIds =
|
||||
CollectionUtils.isEmpty((Collection) param.getIncludePersons())
|
||||
? new ArrayList<String>()
|
||||
: param.getIncludePersons().stream()
|
||||
.map(AssociatedParam::getObjectId)
|
||||
.collect(Collectors.toList());
|
||||
if (CollectionUtils.isEmpty((Collection)param.getIncludeOrganizations()) && CollectionUtils.isEmpty((Collection)param.getIncludeLabels()) && CollectionUtils.isEmpty(includePersonIds)) {
|
||||
return new ArrayList<IsImageStoreAssociated>();
|
||||
}
|
||||
ArrayList<IsImageStoreAssociated> imageStoreAssociatedList = new ArrayList<IsImageStoreAssociated>();
|
||||
if (CpImageStoreMatchPatternEnum.getByCode((String)param.getMatchPattern()) != null) {
|
||||
imageStoreAssociatedList.add(this.getAssociated(param.getMatchPattern(), time, context.getUser().getCaller(), imageStoreId, null, (Integer)4));
|
||||
} else {
|
||||
imageStoreAssociatedList.add(this.getAssociated(CpImageStoreMatchPatternEnum.MERGE.getCode(), time, context.getUser().getCaller(), imageStoreId, null, (Integer)4));
|
||||
}
|
||||
AssociatedParam imageStoreAssociatedParam = new AssociatedParam();
|
||||
imageStoreAssociatedParam.setObjectId(imageStoreId);
|
||||
imageStoreAssociatedParam.setExpiryBeginDate(param.getExpiryBeginDate());
|
||||
imageStoreAssociatedParam.setExpiryEndDate(param.getExpiryEndDate());
|
||||
imageStoreAssociatedParam.setValidDateCron(param.getValidDateCron());
|
||||
imageStoreAssociatedList.add(this.getAssociated(imageStoreAssociatedParam, time, context.getUser().getCaller(), imageStoreId, (Integer)0, (Integer)5));
|
||||
if (!CollectionUtils.isEmpty((Collection)param.getIncludeOrganizations())) {
|
||||
if (this.imgStoreOrganizationMapper.getOrgByIds(param.getIncludeOrganizations(), businessId).size() != param.getIncludeOrganizations().size()) {
|
||||
throw new ServiceException("53013513", this.getMessage("53013513"));
|
||||
}
|
||||
for (Object objectId : param.getIncludeOrganizations()) {
|
||||
imageStoreAssociatedList.add(this.getAssociated((String)objectId, time, context.getUser().getCaller(), imageStoreId, (Integer)0, (Integer)1));
|
||||
}
|
||||
}
|
||||
if (!CollectionUtils.isEmpty((Collection)param.getIncludeLabels())) {
|
||||
if (this.imgStoreLabelMapper.getLabelByIds(param.getIncludeLabels(), businessId).size() != param.getIncludeLabels().size()) {
|
||||
throw new ServiceException("53013514", this.getMessage("53013514"));
|
||||
}
|
||||
for (Object objectId : param.getIncludeLabels()) {
|
||||
imageStoreAssociatedList.add(this.getAssociated((String)objectId, time, context.getUser().getCaller(), imageStoreId, (Integer)0, (Integer)2));
|
||||
}
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(includePersonIds)) {
|
||||
ImgStorePersonQueryDto personQuery = new ImgStorePersonQueryDto();
|
||||
personQuery.setIds(includePersonIds);
|
||||
personQuery.setBusinessId(businessId);
|
||||
personQuery.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
if (this.personMapper.gets(personQuery).size() != includePersonIds.size()) {
|
||||
throw new ServiceException("53013515", this.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(this.getAssociated(associatedParam, time, context.getUser().getCaller(), imageStoreId, (Integer)0, (Integer)3));
|
||||
}
|
||||
}
|
||||
if (!CollectionUtils.isEmpty((Collection)param.getExcludeLabels())) {
|
||||
if (this.imgStoreLabelMapper.getLabelByIds(param.getExcludeLabels(), businessId).size() != param.getExcludeLabels().size()) {
|
||||
throw new ServiceException("53013516", this.getMessage("53013516"));
|
||||
}
|
||||
for (Object objectId : param.getExcludeLabels()) {
|
||||
imageStoreAssociatedList.add(this.getAssociated((String)objectId, time, context.getUser().getCaller(), imageStoreId, (Integer)1, (Integer)2));
|
||||
}
|
||||
}
|
||||
if (!CollectionUtils.isEmpty((Collection) param.getExcludePersons())) {
|
||||
ImgStorePersonQueryDto excludePersonQuery = new ImgStorePersonQueryDto();
|
||||
excludePersonQuery.setIds((Collection) param.getExcludePersons());
|
||||
excludePersonQuery.setBusinessId(businessId);
|
||||
excludePersonQuery.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
if (this.personMapper.gets(excludePersonQuery).size() != param.getExcludePersons().size()) {
|
||||
throw new ServiceException("53013517", this.getMessage("53013517"));
|
||||
}
|
||||
for (String objectId : param.getExcludePersons()) {
|
||||
imageStoreAssociatedList.add(this.getAssociated(objectId, time, context.getUser().getCaller(), imageStoreId, (Integer)1, (Integer)3));
|
||||
}
|
||||
}
|
||||
return imageStoreAssociatedList;
|
||||
}
|
||||
|
||||
private String getBusinessName(String businessId) throws ServiceException {
|
||||
GeneralQueryBusinessParam generalQueryBusinessParam = new GeneralQueryBusinessParam();
|
||||
generalQueryBusinessParam.setId(businessId);
|
||||
CloudwalkResult cloudwalkResult = this.acBusinessService.generalQuery(generalQueryBusinessParam);
|
||||
if (cloudwalkResult == null) {
|
||||
throw new ServiceException("53013535", this.getMessage("53013535"));
|
||||
}
|
||||
if (!cloudwalkResult.isSuccess()) {
|
||||
throw new ServiceException(cloudwalkResult.getCode(), cloudwalkResult.getMessage());
|
||||
}
|
||||
if (cloudwalkResult.getData() != null && ((List)cloudwalkResult.getData()).size() > 0) {
|
||||
return ((AcBusinessDTO)((List)cloudwalkResult.getData()).get(0)).getName();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String getSourceApplicationName(String sourceApplicationId) throws ServiceException {
|
||||
if (StringUtils.isEmpty((CharSequence)sourceApplicationId)) {
|
||||
return null;
|
||||
}
|
||||
ApplicationBasicParam applicationBasicParam = new ApplicationBasicParam();
|
||||
applicationBasicParam.setIds(Arrays.asList(sourceApplicationId));
|
||||
CloudwalkResult cloudwalkResult = this.applicationService.gets(applicationBasicParam);
|
||||
if (cloudwalkResult == null) {
|
||||
throw new ServiceException("53013547", this.getMessage("53013547"));
|
||||
}
|
||||
if (!cloudwalkResult.isSuccess()) {
|
||||
throw new ServiceException(cloudwalkResult.getCode(), cloudwalkResult.getMessage());
|
||||
}
|
||||
if (cloudwalkResult.getData() != null && ((List)cloudwalkResult.getData()).size() > 0) {
|
||||
return ((ApplicationResult)((List)cloudwalkResult.getData()).get(0)).getName();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void checkExistAndStatus(String iamgeStoreId) throws ServiceException {
|
||||
AgImageStoreQueryParam queryParam = new AgImageStoreQueryParam();
|
||||
queryParam.setId(iamgeStoreId);
|
||||
CloudwalkResult query = this.agImageStoreService.query(queryParam);
|
||||
if (!query.isSuccess()) {
|
||||
throw new ServiceException(query.getCode(), query.getMessage());
|
||||
}
|
||||
if (CollectionUtils.isEmpty((Collection)((Collection)query.getData()))) {
|
||||
throw new ServiceException("53013502", this.getMessage("53013502"));
|
||||
}
|
||||
if (SyncStatusEnum.SYNC_ING.getCode().equals(((AgImageStoreResult)((List)query.getData()).get(0)).getStatus())) {
|
||||
throw new ServiceException("53013512", this.getMessage("53013512"));
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, String> getBusinessNameMap() throws ServiceException {
|
||||
CloudwalkResult listCloudwalkResult = this.acBusinessService.generalQuery(new GeneralQueryBusinessParam());
|
||||
if (!listCloudwalkResult.isSuccess()) {
|
||||
throw new ServiceException(listCloudwalkResult.getCode(), listCloudwalkResult.getMessage());
|
||||
}
|
||||
if (CollectionUtils.isEmpty((Collection)((Collection)listCloudwalkResult.getData()))) {
|
||||
return new HashMap<String, String>();
|
||||
}
|
||||
return Collections3.extractToMap((Collection)((Collection)listCloudwalkResult.getData()), (String)"id", (String)"name");
|
||||
}
|
||||
|
||||
private Map<String, String> getSourceApplicationNameMap(String businessId) throws ServiceException {
|
||||
ApplicationQueryParam param = new ApplicationQueryParam();
|
||||
param.setBusinessId(businessId);
|
||||
param.setStatus(CommonStatusEnum.ENABLE.getCode());
|
||||
CloudwalkResult listCloudwalkResult = this.applicationService.query(param);
|
||||
if (!listCloudwalkResult.isSuccess()) {
|
||||
throw new ServiceException(listCloudwalkResult.getCode(), listCloudwalkResult.getMessage());
|
||||
}
|
||||
if (CollectionUtils.isEmpty((Collection)((Collection)listCloudwalkResult.getData()))) {
|
||||
return new HashMap<String, String>();
|
||||
}
|
||||
return Collections3.extractToMap((Collection)((Collection)listCloudwalkResult.getData()), (String)"id", (String)"name");
|
||||
}
|
||||
|
||||
private void getAssociated(ImageStoreDetailResult result) {
|
||||
GetsImageStoreAssociatedDTO get = new GetsImageStoreAssociatedDTO();
|
||||
get.setImageStoreId(result.getId());
|
||||
List<IsImageStoreAssociated> associateds =
|
||||
(List<IsImageStoreAssociated>) (List) this.isImageStoreAssociatedMapper.gets(get);
|
||||
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>();
|
||||
String businessId = result.getBusinessId();
|
||||
for (IsImageStoreAssociated associated : associateds) {
|
||||
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;
|
||||
result.setExpiryBeginDate(associated.getExpiryBeginDate());
|
||||
result.setExpiryEndDate(associated.getExpiryEndDate());
|
||||
result.setValidDateCron(JsonUtils.toStrList((String)associated.getValidDateCron()));
|
||||
continue;
|
||||
}
|
||||
if (1 != associated.getAssociatedAction()) continue;
|
||||
if (2 == associated.getAssociatedObjectIdType()) {
|
||||
excludeLabelIds.add(associated.getAssociatedObjectId());
|
||||
continue;
|
||||
}
|
||||
if (3 != associated.getAssociatedObjectIdType()) continue;
|
||||
excludePersonIds.add(associated.getAssociatedObjectId());
|
||||
}
|
||||
result.setMatchPattern(matchPattern);
|
||||
if (!CollectionUtils.isEmpty(includeLabelIds)) {
|
||||
result.setIncludeLabels(BeanCopyUtils.copy((Collection)this.imgStoreLabelMapper.getLabelByIds(includeLabelIds, businessId), LabelResult.class));
|
||||
} else {
|
||||
result.setIncludeLabels(new ArrayList());
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(includeOrganizationIds)) {
|
||||
result.setIncludeOrganizations(BeanCopyUtils.copy((Collection)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);
|
||||
ArrayList<ImgStorePersonResult> includePersons = new ArrayList<ImgStorePersonResult>();
|
||||
personList.forEach(imgStorePerson -> {
|
||||
ImgStorePersonResult imgStorePersonResult = new ImgStorePersonResult();
|
||||
BeanCopyUtils.copyProperties((Object)imgStorePerson, (Object)imgStorePersonResult);
|
||||
AssociatedResult associatedResult = (AssociatedResult)includePersonMap.get(imgStorePerson.getId());
|
||||
BeanCopyUtils.copyProperties((Object)associatedResult, (Object)imgStorePersonResult);
|
||||
imgStorePersonResult.setValidDateCron(JsonUtils.toStrList((String)associatedResult.getValidDateCron()));
|
||||
includePersons.add(imgStorePersonResult);
|
||||
});
|
||||
result.setIncludePersons(includePersons);
|
||||
} else {
|
||||
result.setIncludePersons(new ArrayList());
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(excludeLabelIds)) {
|
||||
result.setExcludeLabels(BeanCopyUtils.copy((Collection)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((Collection)this.personMapper.gets(getDTO), ImgStorePersonResult.class));
|
||||
} else {
|
||||
result.setExcludePersons(new ArrayList());
|
||||
}
|
||||
}
|
||||
|
||||
private boolean handleQueryParam(QueryImageStoreParam queryParam) {
|
||||
List imageStoreIds;
|
||||
if (StringUtils.isNotBlank((CharSequence)queryParam.getOrgId()) || !CollectionUtils.isEmpty((Collection)queryParam.getOrgIds())) {
|
||||
List orgImageStoreList = this.organizationImageStoreMapper.query((OrganizationImageStoreQueryDTO)BeanCopyUtils.copyProperties((Object)queryParam, OrganizationImageStoreQueryDTO.class));
|
||||
GetsImageStoreAssociatedDTO orgParam = new GetsImageStoreAssociatedDTO();
|
||||
orgParam.setAssociatedObjectIdType(Integer.valueOf(1));
|
||||
ArrayList<String> orgIds = new ArrayList<String>(500);
|
||||
if (StringUtils.isNotBlank((CharSequence)queryParam.getOrgId())) {
|
||||
orgIds.add(queryParam.getOrgId());
|
||||
}
|
||||
if (!CollectionUtils.isEmpty((Collection)queryParam.getOrgIds())) {
|
||||
orgIds.addAll(queryParam.getOrgIds());
|
||||
}
|
||||
orgParam.setAssociatedObjectIds(orgIds);
|
||||
List orgResultList = this.isImageStoreAssociatedMapper.gets(orgParam);
|
||||
if (CollectionUtils.isEmpty((Collection)orgImageStoreList) && CollectionUtils.isEmpty((Collection)orgResultList)) {
|
||||
return true;
|
||||
}
|
||||
List imageStoreIds2 = Collections3.extractToList((Collection)orgImageStoreList, (String)"imageStoreId");
|
||||
imageStoreIds2.addAll(Collections3.extractToList((Collection)orgResultList, (String)"imageStoreId"));
|
||||
if (StringUtils.isNotBlank((CharSequence)queryParam.getId())) {
|
||||
if (!imageStoreIds2.contains(queryParam.getId())) {
|
||||
return true;
|
||||
}
|
||||
} else if (!CollectionUtils.isEmpty((Collection)queryParam.getIds())) {
|
||||
imageStoreIds2.retainAll(queryParam.getIds());
|
||||
}
|
||||
if (CollectionUtils.isEmpty((Collection)imageStoreIds2)) {
|
||||
return true;
|
||||
}
|
||||
queryParam.setIds(imageStoreIds2);
|
||||
}
|
||||
if (!CollectionUtils.isEmpty((Collection)queryParam.getPersonIds())) {
|
||||
QueryGroupPersonDTO queryGroupPersonDTO = (QueryGroupPersonDTO)BeanCopyUtils.copyProperties((Object)queryParam, QueryGroupPersonDTO.class);
|
||||
queryGroupPersonDTO.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
List queryResult = this.groupPersonRefMapper.query(queryGroupPersonDTO);
|
||||
if (CollectionUtils.isEmpty((Collection)queryResult)) {
|
||||
return true;
|
||||
}
|
||||
imageStoreIds = Collections3.extractToList((Collection)queryResult, (String)"imageStoreId");
|
||||
if (StringUtils.isNotBlank((CharSequence)queryParam.getId())) {
|
||||
if (!imageStoreIds.contains(queryParam.getId())) {
|
||||
return true;
|
||||
}
|
||||
} else if (!CollectionUtils.isEmpty((Collection)queryParam.getIds())) {
|
||||
imageStoreIds.retainAll(queryParam.getIds());
|
||||
}
|
||||
if (CollectionUtils.isEmpty((Collection)imageStoreIds)) {
|
||||
return true;
|
||||
}
|
||||
queryParam.setIds(imageStoreIds);
|
||||
}
|
||||
if (!CollectionUtils.isEmpty((Collection)queryParam.getLabelIds())) {
|
||||
GetsImageStoreAssociatedDTO labelParam = new GetsImageStoreAssociatedDTO();
|
||||
labelParam.setAssociatedObjectIdType(Integer.valueOf(2));
|
||||
labelParam.setAssociatedObjectIds((Collection)queryParam.getLabelIds());
|
||||
List labelResultList = this.isImageStoreAssociatedMapper.gets(labelParam);
|
||||
if (CollectionUtils.isEmpty((Collection)labelResultList)) {
|
||||
return true;
|
||||
}
|
||||
imageStoreIds = Collections3.extractToList((Collection)labelResultList, (String)"imageStoreId");
|
||||
if (StringUtils.isNotBlank((CharSequence)queryParam.getId())) {
|
||||
if (!imageStoreIds.contains(queryParam.getId())) {
|
||||
return true;
|
||||
}
|
||||
} else if (!CollectionUtils.isEmpty((Collection)queryParam.getIds())) {
|
||||
imageStoreIds.retainAll(queryParam.getIds());
|
||||
}
|
||||
if (CollectionUtils.isEmpty((Collection)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<ImageStoreResult>();
|
||||
}
|
||||
List<String> imageIds = agDatas.stream().map(AgImageStoreResult::getId).collect(Collectors.toList());
|
||||
long startTime = System.currentTimeMillis();
|
||||
ArrayList<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("\u56fe\u5e93\u5206\u9875\u67e5\u8be2\u8017\u65f6:[{}],searchSize:[{}]", (Object)(endTime - startTime), (Object)this.searchSize);
|
||||
Map<String, Integer> countMap =
|
||||
countByImageStoreIds.stream()
|
||||
.filter(imageStoreCountDTO -> null != imageStoreCountDTO)
|
||||
.collect(
|
||||
Collectors.toMap(
|
||||
ImageStoreCountDTO::getId,
|
||||
ImageStoreCountDTO::getCount,
|
||||
(k1, k2) -> k1));
|
||||
Map<String, String> businessNameMap = this.getBusinessNameMap();
|
||||
Map<String, String> sourceApplicationNameMap = this.getSourceApplicationNameMap(businessId);
|
||||
ArrayList<ImageStoreResult> resultList = new ArrayList<ImageStoreResult>(agDatas.size());
|
||||
for (AgImageStoreResult agData : agDatas) {
|
||||
ImageStoreResult temp = (ImageStoreResult)BeanCopyUtils.copyProperties((Object)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));
|
||||
this.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<PageImageStoreResult>();
|
||||
}
|
||||
List<String> imageIds = agDatas.stream().map(AgImageStoreResult::getId).collect(Collectors.toList());
|
||||
long startTime = System.currentTimeMillis();
|
||||
ArrayList<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("\u56fe\u5e93\u5206\u9875\u67e5\u8be2\u8017\u65f6:[{}],searchSize:[{}]", (Object)(endTime - startTime), (Object)this.searchSize);
|
||||
Map<String, Integer> countMap =
|
||||
countByImageStoreIds.stream()
|
||||
.filter(imageStoreCountDTO -> null != imageStoreCountDTO)
|
||||
.collect(
|
||||
Collectors.toMap(
|
||||
ImageStoreCountDTO::getId,
|
||||
ImageStoreCountDTO::getCount,
|
||||
(k1, k2) -> k1));
|
||||
Map<String, String> businessNameMap = this.getBusinessNameMap();
|
||||
Map<String, String> sourceApplicationNameMap = this.getSourceApplicationNameMap(businessId);
|
||||
ArrayList<PageImageStoreResult> resultList = new ArrayList<PageImageStoreResult>(agDatas.size());
|
||||
for (AgImageStoreResult agData : agDatas) {
|
||||
PageImageStoreResult temp = (PageImageStoreResult)BeanCopyUtils.copyProperties((Object)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 countByImageStoreIds = this.groupPersonRefMapper.getCountByImageStoreIds((List)Lists.newArrayList((Object[])new String[]{id}));
|
||||
if (CollectionUtils.isEmpty((Collection)countByImageStoreIds) || countByImageStoreIds.get(0) == null) {
|
||||
return 0;
|
||||
}
|
||||
return ((ImageStoreCountDTO)countByImageStoreIds.get(0)).getCount();
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
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(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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+699
@@ -0,0 +1,699 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.aggregate.group.param.AgFeatureExtractParam;
|
||||
import cn.cloudwalk.client.aggregate.group.result.AgFeatureExtractResult;
|
||||
import cn.cloudwalk.client.organization.param.AddFaceParam;
|
||||
import cn.cloudwalk.client.organization.param.BatchAddFaceParam;
|
||||
import cn.cloudwalk.client.organization.param.BatchRemoveFaceParam;
|
||||
import cn.cloudwalk.client.organization.param.ExtractFeatureParam;
|
||||
import cn.cloudwalk.client.organization.param.FaceDetectParam;
|
||||
import cn.cloudwalk.client.organization.param.RemoveFaceParam;
|
||||
import cn.cloudwalk.client.organization.param.SearchFaceMutipleParam;
|
||||
import cn.cloudwalk.client.organization.param.SearchFaceParam;
|
||||
import cn.cloudwalk.client.organization.result.BatchHandleFaceResult;
|
||||
import cn.cloudwalk.client.organization.result.BatchSearchFaceResult;
|
||||
import cn.cloudwalk.client.organization.result.ExtractFeatureResult;
|
||||
import cn.cloudwalk.client.organization.result.FaceDetectResult;
|
||||
import cn.cloudwalk.client.organization.result.HandleFaceResult;
|
||||
import cn.cloudwalk.client.organization.result.PineappleBaseResult;
|
||||
import cn.cloudwalk.client.organization.result.SearchFaceMutiplePerGroupResult;
|
||||
import cn.cloudwalk.client.organization.result.SearchFaceMutipleResult;
|
||||
import cn.cloudwalk.client.organization.result.SearchFaceResult;
|
||||
import cn.cloudwalk.client.organization.service.store.param.CpBatchHandleFaceParam;
|
||||
import cn.cloudwalk.client.organization.service.store.param.CpFaceDetectParam;
|
||||
import cn.cloudwalk.client.organization.service.store.param.CpFeatureQueryParam;
|
||||
import cn.cloudwalk.client.organization.service.store.param.CpHandleFaceParam;
|
||||
import cn.cloudwalk.client.organization.service.store.param.CpSearchFaceParam;
|
||||
import cn.cloudwalk.client.organization.service.store.result.CpFeatureQueryResult;
|
||||
import cn.cloudwalk.client.organization.service.store.service.CpImageStoreToolService;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.cloud.utils.BeanCopyUtils;
|
||||
import cn.cloudwalk.data.organization.dto.ImgStorePersonQueryDto;
|
||||
import cn.cloudwalk.data.organization.entity.GroupPersonRef;
|
||||
import cn.cloudwalk.data.organization.entity.ImgStorePerson;
|
||||
import cn.cloudwalk.data.organization.mapper.GroupPersonRefMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonMapper;
|
||||
import cn.cloudwalk.intelligent.davinci.storage.manager.FileStorageManager;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import cn.cloudwalk.service.organization.common.ImageUtil;
|
||||
import cn.cloudwalk.service.organization.service.feign.PineappleEngineClient;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.google.common.collect.Lists;
|
||||
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;
|
||||
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;
|
||||
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 {
|
||||
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.Item item = new BatchAddFaceParam.Item();
|
||||
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.Item item = new BatchRemoveFaceParam.Item();
|
||||
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 =
|
||||
entry.getValue().stream()
|
||||
.map((SearchFaceMutipleResult.FaceData x) -> 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;
|
||||
}
|
||||
}
|
||||
+862
@@ -0,0 +1,862 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.aggregate.common.enums.DelStatusEnum;
|
||||
import cn.cloudwalk.client.aggregate.device.param.DeviceImageStoreQueryParam;
|
||||
import cn.cloudwalk.client.aggregate.device.param.DeviceImageStoreSynLogAddParam;
|
||||
import cn.cloudwalk.client.aggregate.device.result.DeviceImageStoreQueryResult;
|
||||
import cn.cloudwalk.client.aggregate.device.service.AggDeviceImageStoreService;
|
||||
import cn.cloudwalk.client.aggregate.device.service.AggImageStoreSyncLogService;
|
||||
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.DeviceAbilityEnum;
|
||||
import cn.cloudwalk.client.organization.common.enums.StatusEnum;
|
||||
import cn.cloudwalk.client.organization.common.enums.SyncStatusEnum;
|
||||
import cn.cloudwalk.client.organization.service.CpOrgDevieKitService;
|
||||
import cn.cloudwalk.client.organization.service.store.enums.EndFlagEnum;
|
||||
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.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.service.CpDeviceImagePersonService;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkCallContext;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
import cn.cloudwalk.cloud.page.CloudwalkPageAble;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.cloud.serial.UUIDSerial;
|
||||
import cn.cloudwalk.cloud.utils.BeanCopyUtils;
|
||||
import cn.cloudwalk.data.organization.dto.DevicePersonSyncLogDTO;
|
||||
import cn.cloudwalk.data.organization.dto.QueryGroupPersonDTO;
|
||||
import cn.cloudwalk.data.organization.entity.DeviceImageStore;
|
||||
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.mapper.DeviceImageStoreMapper;
|
||||
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.ImgStorePersonMapper;
|
||||
import cn.cloudwalk.device.sdk.protocol.entity.v2proto.http.param.UpdateFeatureParam;
|
||||
import cn.cloudwalk.device.sdk.protocol.entity.v2proto.http.param.UpdateGroupParam;
|
||||
import cn.cloudwalk.device.sdk.protocol.entity.v2proto.http.param.UpdatePersonParam;
|
||||
import cn.cloudwalk.device.sdk.protocol.entity.v2proto.http.param.UpdatePictureParam;
|
||||
import cn.cloudwalk.device.sdk.protocol.entity.v2proto.http.result.UpdateFeatureResult;
|
||||
import cn.cloudwalk.device.sdk.protocol.entity.v2proto.http.result.UpdateGroupResult;
|
||||
import cn.cloudwalk.device.sdk.protocol.entity.v2proto.http.result.UpdatePersonResult;
|
||||
import cn.cloudwalk.device.sdk.protocol.entity.v2proto.http.result.UpdatePictureResult;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
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.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
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.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springside.modules.utils.Collections3;
|
||||
|
||||
@Service
|
||||
public class CpOrgDevieKitServiceImpl extends AbstractImagStoreService
|
||||
implements CpOrgDevieKitService {
|
||||
private static final Logger log = LoggerFactory.getLogger(CpOrgDevieKitServiceImpl.class);
|
||||
private static final String SYNC_LOG_KEY = "lock_sync_log_";
|
||||
|
||||
@Value("${cloudwalk.person.max-page-size:50}")
|
||||
private Integer cwMaxPageSize;
|
||||
|
||||
@Value("${cwos.image.store.sync.log:false}")
|
||||
private boolean isSyncLog;
|
||||
|
||||
@Value("${cloudwalk.person.sync-log-expire-time:10}")
|
||||
private long syncLogExpireTime;
|
||||
|
||||
@Autowired CpDeviceImagePersonService cpDeviceImagePersonService;
|
||||
@Autowired private AggDeviceImageStoreService aggDeviceImageStoreService;
|
||||
@Autowired private AtomicDeviceService atomicDeviceService;
|
||||
@Autowired AggImageStoreSyncLogService aggImageStoreSyncLogService;
|
||||
@Resource private DevicePersonSyncLogMapper devicePersonSyncLogMapper;
|
||||
@Resource private ImgStorePersonMapper imgStorePersonMapper;
|
||||
@Resource private GroupPersonRefMapper groupPersonRefMapper;
|
||||
@Resource private DevicePersonMapper devicePersonMapper;
|
||||
@Resource private DeviceImageStoreMapper deviceImageStoreMapper;
|
||||
@Resource private UUIDSerial uuidSerial;
|
||||
@Autowired private StringRedisTemplate redisTemplate;
|
||||
|
||||
@Value("${support.muti.group.device.type:CW-IS1330}")
|
||||
private String mutiGroupDeviceType;
|
||||
|
||||
public CloudwalkResult<UpdateGroupResult> onUpdateGroupRequest(
|
||||
UpdateGroupParam updateGroupParam, CloudwalkCallContext cloudwalkCallContext)
|
||||
throws ServiceException {
|
||||
AtomicDeviceGetResult device =
|
||||
checkAndGetDeviceByCode(updateGroupParam.getDeviceId(), cloudwalkCallContext);
|
||||
List<UpdateGroupResult.Group> groups =
|
||||
getImageStoreRelationGroup(device.getId(), cloudwalkCallContext);
|
||||
UpdateGroupResult updateGroupResult = new UpdateGroupResult();
|
||||
BeanCopyUtils.copyProperties(updateGroupParam, updateGroupResult);
|
||||
updateGroupResult.setGroups(groups);
|
||||
return CloudwalkResult.success(updateGroupResult);
|
||||
}
|
||||
|
||||
public CloudwalkResult<UpdateFeatureResult> onUpdateFeatureRequest(
|
||||
UpdateFeatureParam updateFeatureParam, CloudwalkCallContext cloudwalkCallContext)
|
||||
throws ServiceException {
|
||||
UpdateFeatureResult updateFeatureResult = new UpdateFeatureResult();
|
||||
BeanCopyUtils.copyProperties(updateFeatureParam, updateFeatureResult);
|
||||
AtomicDeviceGetResult device =
|
||||
checkAndGetDeviceByCode(updateFeatureParam.getDeviceId(), cloudwalkCallContext);
|
||||
boolean checkBoolean =
|
||||
checkDeviceImageStoreIdRefExist(
|
||||
updateFeatureParam.getGroupId(), device.getId(), cloudwalkCallContext);
|
||||
if (!checkBoolean) {
|
||||
return CloudwalkResult.success(updateFeatureResult);
|
||||
}
|
||||
DeviceImageUpdateFeatureQuery updatePersonQuery = new DeviceImageUpdateFeatureQuery();
|
||||
updatePersonQuery.setImageStoreId(updateFeatureParam.getGroupId());
|
||||
updatePersonQuery.setLastUpdateTime(updateFeatureParam.getLastUpdateTime());
|
||||
if (updateFeatureParam.getSequenceId() != null) {
|
||||
updatePersonQuery.setSequenceId(updateFeatureParam.getSequenceId());
|
||||
}
|
||||
if (updateFeatureParam.getPageSize() != null
|
||||
&& updateFeatureParam.getPageSize().intValue() <= this.cwMaxPageSize.intValue()) {
|
||||
updatePersonQuery.setRowsOfPage(updateFeatureParam.getPageSize().intValue());
|
||||
}
|
||||
CloudwalkResult<CloudwalkPageAble<DeviceImageUpdateFeautreResult>> updatePersonInfo =
|
||||
this.cpDeviceImagePersonService.getDeviceImageUpdateFeatureInfo(
|
||||
updatePersonQuery, cloudwalkCallContext);
|
||||
if (!updatePersonInfo.isSuccess()) {
|
||||
this.logger.warn(
|
||||
"get feature info error,device:{}, imageStore:{}",
|
||||
updateFeatureParam.getDeviceId(),
|
||||
updateFeatureParam.getGroupId());
|
||||
return CloudwalkResult.success(updateFeatureResult);
|
||||
}
|
||||
CloudwalkPageAble<DeviceImageUpdateFeautreResult> personInfoData =
|
||||
(CloudwalkPageAble<DeviceImageUpdateFeautreResult>) updatePersonInfo.getData();
|
||||
updateFeatureResult.setCurrentPage(Integer.valueOf((int) personInfoData.getCurrentPage()));
|
||||
updateFeatureResult.setGroupId(updateFeatureParam.getGroupId());
|
||||
updateFeatureResult.setPagePize(Integer.valueOf((int) personInfoData.getPageSize()));
|
||||
updateFeatureResult.setTotalPages(Integer.valueOf((int) personInfoData.getTotalPages()));
|
||||
List<UpdateFeatureResult.FeatureData> featureDatas = new ArrayList<>();
|
||||
Collection<DeviceImageUpdateFeautreResult> personInfoDataDatas = personInfoData.getDatas();
|
||||
for (DeviceImageUpdateFeautreResult deviceUpdatePersonResult : personInfoDataDatas) {
|
||||
UpdateFeatureResult.FeatureData featureData = new UpdateFeatureResult.FeatureData();
|
||||
featureData.setFaceId(deviceUpdatePersonResult.getFaceId());
|
||||
featureData.setFeature(deviceUpdatePersonResult.getFeature());
|
||||
featureData.setSequenceId(deviceUpdatePersonResult.getSequenceId());
|
||||
featureData.setTimestamp(deviceUpdatePersonResult.getTimestamp());
|
||||
featureData.setType(deviceUpdatePersonResult.getType());
|
||||
featureDatas.add(featureData);
|
||||
}
|
||||
addSyncLogForFeatureUpdate(device.getId(), updateFeatureParam.getGroupId(), featureDatas);
|
||||
updateFeatureResult.setFeatureData(featureDatas);
|
||||
if (personInfoData.getCurrentPage() == personInfoData.getTotalPages()
|
||||
|| personInfoData.getTotalPages() == 0L) {
|
||||
this.logger.info(
|
||||
"device [{}] group [{}] update feature end",
|
||||
updateFeatureParam.getDeviceId(),
|
||||
updateFeatureParam.getGroupId());
|
||||
updateFeatureResult.setEndFlag(EndFlagEnum.END.getCode());
|
||||
} else {
|
||||
updateFeatureResult.setEndFlag(EndFlagEnum.NO_END.getCode());
|
||||
}
|
||||
return CloudwalkResult.success(updateFeatureResult);
|
||||
}
|
||||
|
||||
public CloudwalkResult<UpdatePictureResult> onUpdatePictureRequest(
|
||||
UpdatePictureParam updatePictureParam, CloudwalkCallContext cloudwalkCallContext)
|
||||
throws ServiceException {
|
||||
UpdatePictureResult updatePictureResult = new UpdatePictureResult();
|
||||
BeanCopyUtils.copyProperties(updatePictureParam, updatePictureResult);
|
||||
AtomicDeviceGetResult device =
|
||||
checkAndGetDeviceByCode(updatePictureParam.getDeviceId(), cloudwalkCallContext);
|
||||
boolean checkBoolean =
|
||||
checkDeviceImageStoreIdRefExist(
|
||||
updatePictureParam.getGroupId(), device.getId(), cloudwalkCallContext);
|
||||
if (!checkBoolean) {
|
||||
return CloudwalkResult.success(updatePictureResult);
|
||||
}
|
||||
DeviceImageUpdatePersonQuery updatePersonQuery = new DeviceImageUpdatePersonQuery();
|
||||
updatePersonQuery.setImageStoreId(updatePictureParam.getGroupId());
|
||||
updatePersonQuery.setLastUpdateTime(updatePictureParam.getLastUpdateTime());
|
||||
if (updatePictureParam.getSequenceId() != null) {
|
||||
updatePersonQuery.setSequenceId(updatePictureParam.getSequenceId());
|
||||
}
|
||||
if (updatePictureParam.getPageSize() != null
|
||||
&& updatePictureParam.getPageSize().intValue() <= this.cwMaxPageSize.intValue()) {
|
||||
updatePersonQuery.setRowsOfPage(updatePictureParam.getPageSize().intValue());
|
||||
}
|
||||
CloudwalkResult<CloudwalkPageAble<DeviceImageUpdatePersonResult>> updatePersonInfo =
|
||||
this.cpDeviceImagePersonService.getDeviceImageUpdatePersonInfo(
|
||||
updatePersonQuery, cloudwalkCallContext);
|
||||
if (!updatePersonInfo.isSuccess()) {
|
||||
this.logger.warn(
|
||||
"get picture info error,device:{}, imageStore:{}",
|
||||
updatePictureParam.getDeviceId(),
|
||||
updatePictureParam.getGroupId());
|
||||
return CloudwalkResult.success(updatePictureResult);
|
||||
}
|
||||
CloudwalkPageAble<DeviceImageUpdatePersonResult> personInfoData =
|
||||
(CloudwalkPageAble<DeviceImageUpdatePersonResult>) updatePersonInfo.getData();
|
||||
updatePictureParam.setCurrentPage(Integer.valueOf((int) personInfoData.getCurrentPage()));
|
||||
updatePictureParam.setGroupId(updatePictureParam.getGroupId());
|
||||
updatePictureParam.setPageSize(Integer.valueOf((int) personInfoData.getPageSize()));
|
||||
List<UpdatePictureResult.ImageData> personDatas = new ArrayList<>();
|
||||
Collection<DeviceImageUpdatePersonResult> personInfoDataDatas = personInfoData.getDatas();
|
||||
for (DeviceImageUpdatePersonResult deviceUpdatePersonResult : personInfoDataDatas) {
|
||||
UpdatePictureResult.ImageData imageData = new UpdatePictureResult.ImageData();
|
||||
imageData.setFaceId(deviceUpdatePersonResult.getImageId());
|
||||
imageData.setPictureUrl(
|
||||
((DeviceImageUpdatePersonResult.FaceData) deviceUpdatePersonResult.getFaceData().get(0))
|
||||
.getPictureUrl());
|
||||
imageData.setSequenceId(deviceUpdatePersonResult.getSequenceId());
|
||||
imageData.setType(deviceUpdatePersonResult.getType());
|
||||
imageData.setTimestamp(deviceUpdatePersonResult.getTimestamp());
|
||||
personDatas.add(imageData);
|
||||
}
|
||||
updatePictureResult.setImageData(personDatas);
|
||||
addSyncLogForPicUpdate(device.getId(), updatePictureParam.getGroupId(), personDatas);
|
||||
if (personInfoData.getCurrentPage() == personInfoData.getTotalPages()
|
||||
|| personInfoData.getTotalPages() == 0L) {
|
||||
this.logger.info(
|
||||
"device [{}] group [{}] update image end",
|
||||
updatePictureParam.getDeviceId(),
|
||||
updatePictureParam.getGroupId());
|
||||
updatePictureResult.setEndFlag(EndFlagEnum.END.getCode());
|
||||
} else {
|
||||
updatePictureResult.setEndFlag(EndFlagEnum.NO_END.getCode());
|
||||
}
|
||||
BeanCopyUtils.copyProperties(updatePictureParam, updatePictureResult);
|
||||
return CloudwalkResult.success(updatePictureResult);
|
||||
}
|
||||
|
||||
public CloudwalkResult<UpdatePersonResult> onUpdatePersonRequest(
|
||||
UpdatePersonParam updatePersonParam, CloudwalkCallContext cloudwalkCallContext)
|
||||
throws ServiceException {
|
||||
UpdatePersonResult updatePersonResult = new UpdatePersonResult();
|
||||
BeanCopyUtils.copyProperties(updatePersonParam, updatePersonResult);
|
||||
AtomicDeviceGetResult device =
|
||||
checkAndGetDeviceByCode(updatePersonParam.getDeviceId(), cloudwalkCallContext);
|
||||
List<String> supportList = Arrays.asList(this.mutiGroupDeviceType.split(","));
|
||||
if (supportList.stream()
|
||||
.filter(x -> device.getDeviceTypeName().contains(x))
|
||||
.findFirst()
|
||||
.isPresent()) {
|
||||
device.setSupportMultiPersonGroup(Short.valueOf((short) 0));
|
||||
}
|
||||
boolean deviceGroupRefExist =
|
||||
checkDeviceImageStoreIdRefExist(
|
||||
updatePersonParam.getGroupId(), device.getId(), cloudwalkCallContext);
|
||||
if (!deviceGroupRefExist) {
|
||||
DeviceImageStore query = new DeviceImageStore();
|
||||
query.setDeviceId(device.getId());
|
||||
query.setImageStoreId(updatePersonParam.getGroupId());
|
||||
List<DeviceImageStore> deviceImageStoreList = this.deviceImageStoreMapper.select(query);
|
||||
if (!CollectionUtils.isEmpty(deviceImageStoreList)) {
|
||||
DeviceImageStore deviceImageStore = deviceImageStoreList.get(0);
|
||||
if (deviceImageStore.getType().intValue() == 2
|
||||
&& null != deviceImageStore.getFinishPullTime()) {
|
||||
updatePersonResult.setEndFlag(EndFlagEnum.END.getCode());
|
||||
return CloudwalkResult.success(updatePersonResult);
|
||||
}
|
||||
}
|
||||
}
|
||||
DeviceImageUpdatePersonQuery updatePersonQuery = new DeviceImageUpdatePersonQuery();
|
||||
updatePersonQuery.setDeviceId(device.getId());
|
||||
updatePersonQuery.setImageStoreId(updatePersonParam.getGroupId());
|
||||
updatePersonQuery.setLastUpdateTime(updatePersonParam.getLastUpdateTime());
|
||||
if (updatePersonParam.getSequenceId() != null) {
|
||||
updatePersonQuery.setSequenceId(updatePersonParam.getSequenceId());
|
||||
}
|
||||
if (updatePersonParam.getPageSize() != null
|
||||
&& updatePersonParam.getPageSize().intValue() <= this.cwMaxPageSize.intValue()) {
|
||||
updatePersonQuery.setRowsOfPage(updatePersonParam.getPageSize().intValue());
|
||||
}
|
||||
updatePersonQuery.setSupportPersonValiddate(updatePersonParam.getSupportPersonValiddate());
|
||||
long t1 = System.currentTimeMillis();
|
||||
CloudwalkResult<CloudwalkPageAble<DeviceImageUpdatePersonResult>> updatePersonInfo =
|
||||
this.cpDeviceImagePersonService.getDeviceUpdatePersonInfo(
|
||||
updatePersonQuery, cloudwalkCallContext);
|
||||
long t2 = System.currentTimeMillis();
|
||||
this.logger.info("20113 getDeviceUpdatePersonInfo,spend time {} millis", Long.valueOf(t2 - t1));
|
||||
if (!updatePersonInfo.isSuccess()) {
|
||||
this.logger.warn(
|
||||
"get person info error,device:{}, imageStore:{}",
|
||||
updatePersonParam.getDeviceId(),
|
||||
updatePersonParam.getGroupId());
|
||||
return CloudwalkResult.success(updatePersonResult);
|
||||
}
|
||||
CloudwalkPageAble<DeviceImageUpdatePersonResult> personInfoData =
|
||||
(CloudwalkPageAble<DeviceImageUpdatePersonResult>) updatePersonInfo.getData();
|
||||
updatePersonResult.setCurrentPage(Integer.valueOf((int) personInfoData.getCurrentPage()));
|
||||
updatePersonResult.setGroupId(updatePersonParam.getGroupId());
|
||||
updatePersonResult.setTotalPages(Integer.valueOf((int) personInfoData.getTotalPages()));
|
||||
updatePersonResult.setPagePize(Integer.valueOf((int) personInfoData.getPageSize()));
|
||||
List<UpdatePersonResult.PersonData> personData = new ArrayList<>();
|
||||
Collection<DeviceImageUpdatePersonResult> personInfoDataDatas = personInfoData.getDatas();
|
||||
for (DeviceImageUpdatePersonResult deviceUpdatePersonResult : personInfoDataDatas) {
|
||||
UpdatePersonResult.PersonData personDataTemp = new UpdatePersonResult.PersonData();
|
||||
personDataTemp.setUserId(deviceUpdatePersonResult.getPersonId());
|
||||
personDataTemp.setCreateDate(deviceUpdatePersonResult.getCreateDate());
|
||||
personDataTemp.setSequenceId(deviceUpdatePersonResult.getSequenceId());
|
||||
personDataTemp.setTimestamp(deviceUpdatePersonResult.getTimestamp());
|
||||
personDataTemp.setGroupId(updatePersonParam.getGroupId());
|
||||
personDataTemp.setMobileNumber(deviceUpdatePersonResult.getMobileNumber());
|
||||
personDataTemp.setName(deviceUpdatePersonResult.getName());
|
||||
personDataTemp.setStatus(deviceUpdatePersonResult.getStatus());
|
||||
personDataTemp.setType(deviceUpdatePersonResult.getType());
|
||||
if (!deviceGroupRefExist) {
|
||||
personDataTemp.setStatus(Integer.valueOf(0));
|
||||
personDataTemp.setType(Integer.valueOf(DelStatusEnum.DELETED.getCode().shortValue()));
|
||||
}
|
||||
personDataTemp.setUserType(deviceUpdatePersonResult.getUser_type());
|
||||
if (deviceUpdatePersonResult.getFaceData() != null) {
|
||||
List<UpdatePersonResult.PersonData.FaceData> faceDataList =
|
||||
BeanCopyUtils.copy(
|
||||
deviceUpdatePersonResult.getFaceData(),
|
||||
UpdatePersonResult.PersonData.FaceData.class);
|
||||
personDataTemp.setFaceData(faceDataList);
|
||||
}
|
||||
if (deviceUpdatePersonResult.getShowImage() != null) {
|
||||
UpdatePersonResult.ImageData imageData =
|
||||
(UpdatePersonResult.ImageData)
|
||||
BeanCopyUtils.copyProperties(
|
||||
deviceUpdatePersonResult.getShowImage(), UpdatePersonResult.ImageData.class);
|
||||
personDataTemp.setShowImage(imageData);
|
||||
}
|
||||
personDataTemp.setReserveInfo(deviceUpdatePersonResult.getReserveInfo());
|
||||
personDataTemp.setExpiryBeginDate(deviceUpdatePersonResult.getExpiryBeginDate());
|
||||
personDataTemp.setExpiryEndDate(deviceUpdatePersonResult.getExpiryEndDate());
|
||||
personData.add(personDataTemp);
|
||||
}
|
||||
saveSyncLog(device.getId(), updatePersonParam.getGroupId(), personData);
|
||||
updatePersonData(device, updatePersonParam, personData);
|
||||
updatePersonResult.setPersonDatas(personData);
|
||||
if (personInfoData.getPageSize() > personInfoData.getDatas().size()) {
|
||||
this.logger.info(
|
||||
"device [{}] group [{}] update person end",
|
||||
updatePersonParam.getDeviceId(),
|
||||
updatePersonParam.getGroupId());
|
||||
updatePersonResult.setEndFlag(EndFlagEnum.END.getCode());
|
||||
if (!deviceGroupRefExist) {
|
||||
DeviceImageStore deviceImageStore = new DeviceImageStore();
|
||||
deviceImageStore.setDeviceId(device.getId());
|
||||
deviceImageStore.setImageStoreId(updatePersonParam.getGroupId());
|
||||
deviceImageStore.setStatus(StatusEnum.NOTIFY.getValue());
|
||||
deviceImageStore.setFinishPullTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.deviceImageStoreMapper.update(deviceImageStore);
|
||||
}
|
||||
} else {
|
||||
updatePersonResult.setEndFlag(EndFlagEnum.NO_END.getCode());
|
||||
}
|
||||
return CloudwalkResult.success(updatePersonResult);
|
||||
}
|
||||
|
||||
private void addSyncLogForFeatureUpdate(
|
||||
String deviceId, String groupId, List<UpdateFeatureResult.FeatureData> featureDatas) {
|
||||
if (CollectionUtils.isEmpty(featureDatas)) {
|
||||
return;
|
||||
}
|
||||
DeviceImageStoreSynLogAddParam addParam = new DeviceImageStoreSynLogAddParam();
|
||||
addParam.setDeviceId(deviceId);
|
||||
addParam.setGroupId(groupId);
|
||||
List<DeviceImageStoreSynLogAddParam.ImageData> imageData = new ArrayList<>();
|
||||
for (UpdateFeatureResult.FeatureData featureData : featureDatas) {
|
||||
DeviceImageStoreSynLogAddParam.ImageData image =
|
||||
new DeviceImageStoreSynLogAddParam.ImageData();
|
||||
image.setType(Short.valueOf(featureData.getType().shortValue()));
|
||||
image.setFaceId(featureData.getFaceId());
|
||||
imageData.add(image);
|
||||
}
|
||||
addParam.setImageData(imageData);
|
||||
CloudwalkResult<Boolean> result = this.aggImageStoreSyncLogService.addLog(addParam);
|
||||
if (!result.isSuccess()) {
|
||||
this.logger.error(
|
||||
"addSyncLogForPicUpdate error, deviceId:[{}],gourpId:[{}],result:[{}]",
|
||||
new Object[] {deviceId, groupId, JSON.toJSON(result)});
|
||||
}
|
||||
}
|
||||
|
||||
private void addSyncLogForPersonUpdate(
|
||||
String deviceId, String groupId, List<UpdatePersonResult.PersonData> personData) {
|
||||
if (CollectionUtils.isEmpty(personData)) {
|
||||
return;
|
||||
}
|
||||
DeviceImageStoreSynLogAddParam addParam = new DeviceImageStoreSynLogAddParam();
|
||||
addParam.setDeviceId(deviceId);
|
||||
addParam.setGroupId(groupId);
|
||||
List<DeviceImageStoreSynLogAddParam.ImageData> imageData = new ArrayList<>();
|
||||
for (UpdatePersonResult.PersonData personInfo : personData) {
|
||||
if (CollectionUtils.isEmpty(personInfo.getFaceData())) {
|
||||
continue;
|
||||
}
|
||||
DeviceImageStoreSynLogAddParam.ImageData image =
|
||||
new DeviceImageStoreSynLogAddParam.ImageData();
|
||||
image.setPersonId(personInfo.getUserId());
|
||||
image.setType(Short.valueOf(personInfo.getType().shortValue()));
|
||||
for (UpdatePersonResult.PersonData.FaceData faceData : personInfo.getFaceData()) {
|
||||
image.setFaceId(faceData.getFaceId());
|
||||
}
|
||||
image.setNotifyTime(personInfo.getTimestamp());
|
||||
imageData.add(image);
|
||||
}
|
||||
addParam.setImageData(imageData);
|
||||
CloudwalkResult<Boolean> result = this.aggImageStoreSyncLogService.addLog(addParam);
|
||||
if (!result.isSuccess()) {
|
||||
this.logger.error(
|
||||
"addSyncLogForPersonUpdate error, deviceId:[{}],gourpId:[{}],result:[{}]",
|
||||
new Object[] {deviceId, groupId, JSON.toJSON(result)});
|
||||
}
|
||||
}
|
||||
|
||||
private void unbindPersonData(
|
||||
AtomicDeviceGetResult device,
|
||||
List<UpdatePersonResult.PersonData> personData,
|
||||
boolean deviceGroupRefExist) {
|
||||
if (deviceGroupRefExist) {
|
||||
return;
|
||||
}
|
||||
personData.stream()
|
||||
.forEach(
|
||||
personInfo -> {
|
||||
personInfo.setStatus(Integer.valueOf(0));
|
||||
personInfo.setType(Integer.valueOf(DelStatusEnum.DELETED.getCode().shortValue()));
|
||||
});
|
||||
}
|
||||
|
||||
private 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 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 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 updatePersonData(
|
||||
AtomicDeviceGetResult device,
|
||||
UpdatePersonParam updatePersonParam,
|
||||
List<UpdatePersonResult.PersonData> personData) {
|
||||
if (null != device.getSupportMultiPersonGroup()
|
||||
&& Objects.equals(
|
||||
Integer.valueOf(device.getSupportMultiPersonGroup().intValue()),
|
||||
Integer.valueOf(DeviceAbilityEnum.SUPPORT_MULTI_PERSON_GROUP.getCode()))) {
|
||||
this.logger.debug("设备code[{}]支持多图库", updatePersonParam.getDeviceId());
|
||||
return;
|
||||
}
|
||||
List<String> imageStoreIds =
|
||||
Optional.<List<String>>ofNullable(
|
||||
this.deviceImageStoreMapper.findImageStoreIds(
|
||||
device.getId(), Short.valueOf((short) 1)))
|
||||
.orElse(new ArrayList<>());
|
||||
imageStoreIds =
|
||||
(List<String>)
|
||||
imageStoreIds.stream()
|
||||
.filter(id -> !id.equals(updatePersonParam.getGroupId()))
|
||||
.collect(Collectors.toList());
|
||||
DevicePersonSyncLogDTO dto = new DevicePersonSyncLogDTO();
|
||||
dto.setDeviceId(device.getId());
|
||||
dto.setImageStoreIds(imageStoreIds);
|
||||
DevicePerson devicePerson = new DevicePerson();
|
||||
devicePerson.setDeviceId(device.getId());
|
||||
personData.stream()
|
||||
.forEach(
|
||||
personInfo -> {
|
||||
try {
|
||||
if (personInfo
|
||||
.getType()
|
||||
.equals(Integer.valueOf(DelStatusEnum.NORAML.getCode().shortValue()))) {
|
||||
handlePersonValidDate(updatePersonParam, dto, personInfo, false);
|
||||
} else if (personInfo
|
||||
.getType()
|
||||
.equals(Integer.valueOf(DelStatusEnum.DELETED.getCode().shortValue()))) {
|
||||
handlePersonValidDate(updatePersonParam, dto, personInfo, true);
|
||||
}
|
||||
devicePerson.setPersonId(personInfo.getUserId());
|
||||
devicePerson.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
devicePerson.setType(personInfo.getType());
|
||||
this.devicePersonMapper.updateSelective(devicePerson);
|
||||
} catch (Exception e) {
|
||||
this.logger.error("更新personData异常:{}", e.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void handlePersonValidDate(
|
||||
UpdatePersonParam updatePersonParam,
|
||||
DevicePersonSyncLogDTO dto,
|
||||
UpdatePersonResult.PersonData personInfo,
|
||||
boolean del) {
|
||||
this.logger.debug(
|
||||
"设备[{}]处理人员[{}],Type[{}]",
|
||||
new Object[] {dto.getDeviceId(), dto.getPersonId(), personInfo.getType()});
|
||||
if (CollectionUtils.isEmpty(dto.getImageStoreIds())) {
|
||||
this.logger.warn("设备[{}]未关联其他图库", dto.getDeviceId());
|
||||
return;
|
||||
}
|
||||
QueryGroupPersonDTO queryGroupPersonDTO = new QueryGroupPersonDTO();
|
||||
queryGroupPersonDTO.setPersonId(personInfo.getUserId());
|
||||
queryGroupPersonDTO.setImageStoreIds(dto.getImageStoreIds());
|
||||
List<GroupPersonRef> otherGroupPersons =
|
||||
Optional.<List<GroupPersonRef>>ofNullable(
|
||||
this.groupPersonRefMapper.query(queryGroupPersonDTO))
|
||||
.orElse(new ArrayList<>());
|
||||
otherGroupPersons =
|
||||
(List<GroupPersonRef>)
|
||||
otherGroupPersons.stream()
|
||||
.filter(
|
||||
groupPersonRef ->
|
||||
(-1 != groupPersonRef.getStatus().shortValue()
|
||||
|| DelStatusEnum.DELETED.getCode().shortValue()
|
||||
!= groupPersonRef.getIsDel().shortValue()))
|
||||
.collect(Collectors.toList());
|
||||
if (CollectionUtils.isEmpty(otherGroupPersons)) {
|
||||
this.logger.warn("设备[{}]人员[{}]未关联其他图库", dto.getDeviceId(), dto.getPersonId());
|
||||
return;
|
||||
}
|
||||
Long currentTime = Long.valueOf(System.currentTimeMillis());
|
||||
if (null == updatePersonParam.getSupportPersonValiddate()
|
||||
|| updatePersonParam.getSupportPersonValiddate().intValue()
|
||||
== DeviceAbilityEnum.NOT_SUPPORT_PERSON_VALIDDATE.getCode()) {
|
||||
this.logger.debug("设备[{}]不支持有效期", dto.getDeviceId());
|
||||
Optional<GroupPersonRef> optional =
|
||||
otherGroupPersons.stream()
|
||||
.filter(
|
||||
result ->
|
||||
((null == result.getExpiryBeginDate() && null == result.getExpiryEndDate())
|
||||
|| (currentTime.longValue() >= result.getExpiryBeginDate().longValue()
|
||||
&& currentTime.longValue() <= result.getExpiryEndDate().longValue())))
|
||||
.findFirst();
|
||||
if (optional.isPresent()) {
|
||||
GroupPersonRef groupPersonRef = optional.get();
|
||||
this.logger.debug(
|
||||
"设备[{}]人员[{}]在图库[{}]中有效,有效期[{}]-[{}]",
|
||||
new Object[] {
|
||||
dto.getDeviceId(),
|
||||
dto.getPersonId(),
|
||||
groupPersonRef.getImageStoreId(),
|
||||
groupPersonRef.getExpiryBeginDate(),
|
||||
groupPersonRef.getExpiryEndDate()
|
||||
});
|
||||
personInfo.setType(Integer.valueOf(DelStatusEnum.NORAML.getCode().shortValue()));
|
||||
personInfo.setStatus(Integer.valueOf(1));
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.logger.debug("设备[{}]支持有效期", dto.getDeviceId());
|
||||
Set<String> validDateCronSet = new HashSet<>();
|
||||
JSONObject jsonObject = JSONObject.parseObject(personInfo.getReserveInfo());
|
||||
JSONArray jsonArray = jsonObject.getJSONArray("passCrons");
|
||||
if (null != jsonArray && jsonArray.size() > 0) {
|
||||
jsonArray.stream().forEach(json -> validDateCronSet.add(json.toString()));
|
||||
}
|
||||
Long expiryBeginDate = personInfo.getExpiryBeginDate();
|
||||
Long expiryEndDate = personInfo.getExpiryEndDate();
|
||||
if (del) {
|
||||
expiryBeginDate = ((GroupPersonRef) otherGroupPersons.get(0)).getExpiryBeginDate();
|
||||
expiryEndDate = ((GroupPersonRef) otherGroupPersons.get(0)).getExpiryEndDate();
|
||||
}
|
||||
for (GroupPersonRef groupPersonRef : otherGroupPersons) {
|
||||
if (null == groupPersonRef.getExpiryBeginDate()
|
||||
&& null == groupPersonRef.getExpiryEndDate()) {
|
||||
expiryBeginDate = null;
|
||||
expiryEndDate = null;
|
||||
break;
|
||||
}
|
||||
if (null != groupPersonRef.getExpiryBeginDate()
|
||||
&& null != expiryBeginDate
|
||||
&& groupPersonRef.getExpiryBeginDate().longValue() < expiryBeginDate.longValue()) {
|
||||
expiryBeginDate = groupPersonRef.getExpiryBeginDate();
|
||||
}
|
||||
if (null != groupPersonRef.getExpiryEndDate()
|
||||
&& null != expiryEndDate
|
||||
&& groupPersonRef.getExpiryEndDate().longValue() > expiryEndDate.longValue()) {
|
||||
expiryEndDate = groupPersonRef.getExpiryEndDate();
|
||||
}
|
||||
if (StringUtils.isNotBlank(groupPersonRef.getValidDateCron())) {
|
||||
JSONArray.parseArray(groupPersonRef.getValidDateCron()).stream()
|
||||
.forEach(json -> validDateCronSet.add(json.toString()));
|
||||
}
|
||||
}
|
||||
personInfo.setType(Integer.valueOf(DelStatusEnum.NORAML.getCode().shortValue()));
|
||||
personInfo.setStatus(Integer.valueOf(1));
|
||||
if (null != expiryBeginDate && currentTime.longValue() < expiryBeginDate.longValue()) {
|
||||
personInfo.setStatus(Integer.valueOf(0));
|
||||
}
|
||||
personInfo.setExpiryBeginDate(expiryBeginDate);
|
||||
personInfo.setExpiryEndDate(expiryEndDate);
|
||||
jsonObject.put("passCrons", validDateCronSet);
|
||||
personInfo.setReserveInfo(JSON.toJSONString(jsonObject));
|
||||
this.logger.debug(
|
||||
"设备[{}]人员[{}]设置有效期[{}]-[{}]",
|
||||
new Object[] {dto.getDeviceId(), dto.getPersonId(), expiryBeginDate, expiryEndDate});
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
private void addSyncLogForPicUpdate(
|
||||
String deviceId, String groupId, List<UpdatePictureResult.ImageData> personDatas) {
|
||||
if (CollectionUtils.isEmpty(personDatas)) {
|
||||
return;
|
||||
}
|
||||
DeviceImageStoreSynLogAddParam addParam = new DeviceImageStoreSynLogAddParam();
|
||||
addParam.setDeviceId(deviceId);
|
||||
addParam.setGroupId(groupId);
|
||||
List<DeviceImageStoreSynLogAddParam.ImageData> imageData = new ArrayList<>();
|
||||
for (UpdatePictureResult.ImageData personData : personDatas) {
|
||||
DeviceImageStoreSynLogAddParam.ImageData image =
|
||||
new DeviceImageStoreSynLogAddParam.ImageData();
|
||||
image.setType(Short.valueOf(personData.getType().shortValue()));
|
||||
image.setFaceId(personData.getFaceId());
|
||||
imageData.add(image);
|
||||
}
|
||||
addParam.setImageData(imageData);
|
||||
CloudwalkResult<Boolean> result = this.aggImageStoreSyncLogService.addLog(addParam);
|
||||
if (!result.isSuccess()) {
|
||||
this.logger.error(
|
||||
"addSyncLogForPicUpdate error, deviceId:[{}],gourpId:[{}],result:[{}]",
|
||||
new Object[] {deviceId, groupId, JSON.toJSON(result)});
|
||||
}
|
||||
}
|
||||
|
||||
private boolean checkDeviceImageStoreIdRefExist(
|
||||
String groupId, String deviceId, CloudwalkCallContext cloudwalkCallContext) {
|
||||
DeviceImageStoreQueryParam queryParam = new DeviceImageStoreQueryParam();
|
||||
queryParam.setDeviceId(deviceId);
|
||||
queryParam.setImageStoreId(groupId);
|
||||
CloudwalkResult<List<DeviceImageStoreQueryResult>> queryResult =
|
||||
this.aggDeviceImageStoreService.query(queryParam, cloudwalkCallContext);
|
||||
if (queryResult.isSuccess() && CollectionUtils.isNotEmpty((Collection) queryResult.getData())) {
|
||||
return true;
|
||||
}
|
||||
this.logger.warn("{} device no bind imageStore {}", deviceId, groupId);
|
||||
return false;
|
||||
}
|
||||
|
||||
private List<UpdateGroupResult.Group> getImageStoreRelationGroup(
|
||||
String deviceId, CloudwalkCallContext cloudwalkCallContext) throws ServiceException {
|
||||
List<DeviceImageStoreQueryResult> imageStoreRelation =
|
||||
getImageStoreRelation(deviceId, cloudwalkCallContext);
|
||||
List<UpdateGroupResult.Group> imageStoreIds = new ArrayList<>();
|
||||
if (CollectionUtils.isEmpty(imageStoreRelation)) {
|
||||
return imageStoreIds;
|
||||
}
|
||||
DeviceImagePersonRefQuery query = new DeviceImagePersonRefQuery();
|
||||
query.setImageStoreIds(Collections3.extractToList(imageStoreRelation, "imageStoreId"));
|
||||
CloudwalkResult<List<DeviceImagePersonRefResult>> personRefs =
|
||||
this.cpDeviceImagePersonService.getImagePersonRefs(query, cloudwalkCallContext);
|
||||
if (!personRefs.isSuccess()) {
|
||||
throw new ServiceException(personRefs.getCode(), personRefs.getMessage());
|
||||
}
|
||||
Map<String, Long> personRefMap = new HashMap<>();
|
||||
List<DeviceImagePersonRefResult> personRefsData =
|
||||
(List<DeviceImagePersonRefResult>) personRefs.getData();
|
||||
for (DeviceImagePersonRefResult deviceImagePersonRefResult : personRefsData) {
|
||||
personRefMap.put(
|
||||
deviceImagePersonRefResult.getImageStoreId(),
|
||||
deviceImagePersonRefResult.getImageLastUpdateTime());
|
||||
}
|
||||
for (DeviceImageStoreQueryResult relationStatusResult : imageStoreRelation) {
|
||||
if (!personRefMap.containsKey(relationStatusResult.getImageStoreId())) {
|
||||
continue;
|
||||
}
|
||||
UpdateGroupResult.Group groupResult = new UpdateGroupResult.Group();
|
||||
groupResult.setGroupId(relationStatusResult.getImageStoreId());
|
||||
groupResult.setGroupInfo(relationStatusResult.getImageStoreName());
|
||||
groupResult.setLastUpdateTime(personRefMap.get(relationStatusResult.getImageStoreId()));
|
||||
imageStoreIds.add(groupResult);
|
||||
}
|
||||
return imageStoreIds;
|
||||
}
|
||||
|
||||
private List<DeviceImageStoreQueryResult> getImageStoreRelation(
|
||||
String deviceId, CloudwalkCallContext cloudwalkCallContext) throws ServiceException {
|
||||
DeviceImageStoreQueryParam storeQueryParam = new DeviceImageStoreQueryParam();
|
||||
storeQueryParam.setDeviceId(deviceId);
|
||||
CloudwalkResult<List<DeviceImageStoreQueryResult>> queryResult =
|
||||
this.aggDeviceImageStoreService.query(storeQueryParam, cloudwalkCallContext);
|
||||
if (!"00000000".equals(queryResult.getCode())) {
|
||||
throw new ServiceException(queryResult.getCode(), queryResult.getMessage());
|
||||
}
|
||||
List<DeviceImageStoreQueryResult> withRelationStatusData =
|
||||
(List<DeviceImageStoreQueryResult>) queryResult.getData();
|
||||
if (CollectionUtils.isEmpty(withRelationStatusData)) {
|
||||
throw new ServiceException("53012488", getMessage("53012488") + "---" + deviceId);
|
||||
}
|
||||
return withRelationStatusData;
|
||||
}
|
||||
|
||||
private AtomicDeviceGetResult checkAndGetDeviceByCode(
|
||||
String deviceCode, CloudwalkCallContext context) throws ServiceException {
|
||||
CoreDeviceQueryParam coreDeviceQueryParam = new CoreDeviceQueryParam();
|
||||
coreDeviceQueryParam.setDeviceCode(deviceCode);
|
||||
try {
|
||||
CloudwalkResult<List<AtomicDeviceGetResult>> deviceQueryResult =
|
||||
this.atomicDeviceService.list(coreDeviceQueryParam, context);
|
||||
if (!deviceQueryResult.isSuccess()
|
||||
|| CollectionUtils.isEmpty((Collection) deviceQueryResult.getData())) {
|
||||
throw new ServiceException("53013548", getMessage("53013548"));
|
||||
}
|
||||
return ((List<AtomicDeviceGetResult>) deviceQueryResult.getData()).get(0);
|
||||
} catch (ServiceException e) {
|
||||
this.logger.error("check device exist exception, deviceCode:[{}]", deviceCode, e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.aggregate.application.param.ApplicationImageStoreAddParam;
|
||||
import cn.cloudwalk.client.aggregate.application.param.ApplicationImageStoreDeleteParam;
|
||||
import cn.cloudwalk.client.aggregate.application.service.ApplicationImageStoreService;
|
||||
import cn.cloudwalk.client.organization.service.store.param.BaseOrgImageStoreParam;
|
||||
import cn.cloudwalk.client.organization.service.store.param.QueryOrgImageStoreParam;
|
||||
import cn.cloudwalk.client.organization.service.store.result.OrgImageStoreResult;
|
||||
import cn.cloudwalk.client.organization.service.store.service.CpOrgImageStoreService;
|
||||
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.data.organization.dto.OrganizationImageStoreQueryDTO;
|
||||
import cn.cloudwalk.data.organization.entity.OrganizationImageStore;
|
||||
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.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(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()));
|
||||
}
|
||||
}
|
||||
|
||||
+264
@@ -0,0 +1,264 @@
|
||||
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.service.AggDeviceImageStoreService;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.param.AtomicDeviceCommonParam;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.result.CoreDeviceDetailResult;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.service.AtomicDeviceService;
|
||||
import cn.cloudwalk.client.organization.common.enums.DeviceAbilityEnum;
|
||||
import cn.cloudwalk.client.organization.common.enums.StatusEnum;
|
||||
import cn.cloudwalk.client.organization.common.enums.SyncStatusEnum;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.cloud.serial.UUIDSerial;
|
||||
import cn.cloudwalk.cwos.client.event.event.DeviceGroupRefChangeEvent;
|
||||
import cn.cloudwalk.data.organization.dto.DevicePersonSyncLogDTO;
|
||||
import cn.cloudwalk.data.organization.entity.DeviceImageStore;
|
||||
import cn.cloudwalk.data.organization.entity.DevicePersonSyncLog;
|
||||
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.List;
|
||||
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.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<List<DeviceImageStoreQueryResult>> imageStoreResult =
|
||||
this.aggDeviceImageStoreService.query(storeQueryParam, this.getCloudwalkContext());
|
||||
if (imageStoreResult.isSuccess() && !CollectionUtils.isEmpty(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 =
|
||||
imageStoreResult.getData().stream()
|
||||
.map(DeviceImageStoreQueryResult::getImageStoreId)
|
||||
.collect(Collectors.toList());
|
||||
this.updateSyncLog(event, imageStoreIds);
|
||||
Set<String> changeGroupIdSet = Sets.newHashSet();
|
||||
changeGroupIdSet.add(event.getGroupId());
|
||||
imageStoreResult
|
||||
.getData()
|
||||
.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<DevicePersonSyncLog> dbSyncLogList = this.devicePersonSyncLogMapper.query(query);
|
||||
Set<String> personIdSet =
|
||||
dbSyncLogList.stream().map(DevicePersonSyncLog::getPersonId).collect(Collectors.toSet());
|
||||
List<List<String>> personIdPartition =
|
||||
Lists.partition(Lists.newArrayList(personIdSet), (int) this.personPartitionSize);
|
||||
for (List<String> personIds : personIdPartition) {
|
||||
query.setImageStoreIds(imageStoreIds);
|
||||
query.setPersonIds(personIds);
|
||||
List<String> 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(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});
|
||||
Set<String> changeGroupIdSet = Sets.newHashSet();
|
||||
changeGroupIdSet.add(event.getGroupId());
|
||||
this.cpImageStoreSyncManager.sendChangeToDevice(event.getDeviceId(), changeGroupIdSet, false);
|
||||
}
|
||||
}
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
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;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.result.AtomicDeviceGetResult;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.result.CoreDeviceDetailResult;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.service.AtomicDeviceService;
|
||||
import cn.cloudwalk.client.organization.common.enums.DeviceAbilityEnum;
|
||||
import cn.cloudwalk.client.organization.common.enums.StatusEnum;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.data.organization.dto.DevicePersonSyncLogDTO;
|
||||
import cn.cloudwalk.data.organization.entity.DeviceImageStore;
|
||||
import cn.cloudwalk.data.organization.entity.DevicePersonSyncLog;
|
||||
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 com.google.common.collect.Sets;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
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.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("${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()});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+480
@@ -0,0 +1,480 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.aggregate.device.param.DeviceImageStoreQueryParam;
|
||||
import cn.cloudwalk.client.aggregate.device.param.DeviceImageStoreSynLogQueryParam;
|
||||
import cn.cloudwalk.client.aggregate.device.result.DeviceImageStoreQueryResult;
|
||||
import cn.cloudwalk.client.aggregate.device.result.DeviceImageStoreSynLogQueryResult;
|
||||
import cn.cloudwalk.client.aggregate.device.service.AggDeviceImageStoreService;
|
||||
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.device.sdk.param.DeviceVersionGetsParam;
|
||||
import cn.cloudwalk.client.device.sdk.result.DeviceVersionResult;
|
||||
import cn.cloudwalk.client.device.sdk.service.DeviceVersionService;
|
||||
import cn.cloudwalk.client.organization.common.enums.StatusEnum;
|
||||
import cn.cloudwalk.client.organization.common.enums.SyncStatusEnum;
|
||||
import cn.cloudwalk.client.organization.param.DevicePersonResyncParam;
|
||||
import cn.cloudwalk.client.organization.param.PersonGroupRelationsRequestParam;
|
||||
import cn.cloudwalk.client.organization.param.QueryDevicePersonSyncLogParam;
|
||||
import cn.cloudwalk.client.organization.param.QueryDevicePersonSyncParam;
|
||||
import cn.cloudwalk.client.organization.personimg.service.DevicePersonSyncService;
|
||||
import cn.cloudwalk.client.organization.result.DeviceImageStoreRefResult;
|
||||
import cn.cloudwalk.client.organization.result.DevicePersonSyncDetailResult;
|
||||
import cn.cloudwalk.client.organization.result.DevicePersonSyncLogResult;
|
||||
import cn.cloudwalk.client.organization.result.DevicePersonSyncResult;
|
||||
import cn.cloudwalk.client.organization.result.PersonGroupRelationsResult;
|
||||
import cn.cloudwalk.client.organization.service.store.result.DeviceImageStoreSynLogResult;
|
||||
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.dto.DevicePersonSyncLogDTO;
|
||||
import cn.cloudwalk.data.organization.dto.DevicePersonSyncLogQueryDTO;
|
||||
import cn.cloudwalk.data.organization.dto.ImgStorePersonQueryDto;
|
||||
import cn.cloudwalk.data.organization.entity.DevicePersonSyncLog;
|
||||
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;
|
||||
import com.github.pagehelper.Page;
|
||||
import com.github.pagehelper.PageHelper;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Maps;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Resource;
|
||||
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.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("${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 =
|
||||
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(imageStoreResult.getData())) {
|
||||
List<String> imageStoreIds =
|
||||
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(imageStoreResult.getData())) {
|
||||
imageStoreMap =
|
||||
imageStoreResult.getData().stream()
|
||||
.collect(
|
||||
Collectors.toMap(
|
||||
r -> r.getImageStoreId(),
|
||||
r -> r.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;
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.device.mgn.atomic.param.CoreDistrictQueryParam;
|
||||
import cn.cloudwalk.client.device.mgn.atomic.result.CoreDistrictTreeResult;
|
||||
import cn.cloudwalk.client.organization.personimg.service.DistrictService;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.service.organization.service.feign.DistrictFeignClient;
|
||||
import java.util.List;
|
||||
import javax.annotation.Resource;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class DistrictServiceImpl implements DistrictService {
|
||||
@Resource private DistrictFeignClient districtFeignClient;
|
||||
|
||||
public CloudwalkResult<List<CoreDistrictTreeResult>> getAllTree(CoreDistrictQueryParam param)
|
||||
throws ServiceException {
|
||||
return this.districtFeignClient.getAllTree(param);
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
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()));
|
||||
}
|
||||
}
|
||||
|
||||
+645
@@ -0,0 +1,645 @@
|
||||
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()));
|
||||
}
|
||||
}
|
||||
|
||||
+818
@@ -0,0 +1,818 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.account.account.service.AcAccountService;
|
||||
import cn.cloudwalk.client.account.account.service.AcBusinessService;
|
||||
import cn.cloudwalk.client.aggregate.common.enums.DelStatusEnum;
|
||||
import cn.cloudwalk.client.aggregate.group.param.AgFeatureExtractParam;
|
||||
import cn.cloudwalk.client.aggregate.group.param.AgImageKeyParam;
|
||||
import cn.cloudwalk.client.aggregate.group.result.AgFeatureExtractResult;
|
||||
import cn.cloudwalk.client.aggregate.group.service.AgImageService;
|
||||
import cn.cloudwalk.client.organization.common.constant.ImageStoreConstants;
|
||||
import cn.cloudwalk.client.organization.common.enums.CertPropertyEnum;
|
||||
import cn.cloudwalk.client.organization.common.enums.CpPersonAuditEnum;
|
||||
import cn.cloudwalk.client.organization.common.enums.CpPersonSourceEnum;
|
||||
import cn.cloudwalk.client.organization.common.enums.RegistryTypeEnum;
|
||||
import cn.cloudwalk.client.organization.common.exception.ImageStoreException;
|
||||
import cn.cloudwalk.client.organization.param.AddVehiclePersonParam;
|
||||
import cn.cloudwalk.client.organization.personaudit.param.AddPersonAuditParam;
|
||||
import cn.cloudwalk.client.organization.personimg.param.AddImgPersonParam;
|
||||
import cn.cloudwalk.client.organization.personimg.param.EditImgPersonParam;
|
||||
import cn.cloudwalk.client.organization.personimg.param.QueryImgPersonParam;
|
||||
import cn.cloudwalk.client.organization.service.PersonZoneRefService;
|
||||
import cn.cloudwalk.client.organization.service.PictureRevisionService;
|
||||
import cn.cloudwalk.client.organization.service.store.param.QueryPersonRegistryParam;
|
||||
import cn.cloudwalk.client.organization.service.store.result.PersonPropertiesResult;
|
||||
import cn.cloudwalk.client.organization.service.store.service.CpImageStoreToolService;
|
||||
import cn.cloudwalk.client.organization.service.store.service.PersonRegistryService;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkCallContext;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
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.dto.DelPersonLabelDTO;
|
||||
import cn.cloudwalk.data.organization.dto.DelPersonOrgDTO;
|
||||
import cn.cloudwalk.data.organization.dto.GroupPersonSynData;
|
||||
import cn.cloudwalk.data.organization.dto.ImgStorePersonDeleteDto;
|
||||
import cn.cloudwalk.data.organization.dto.ImgStorePersonQueryDto;
|
||||
import cn.cloudwalk.data.organization.entity.GroupPersonRef;
|
||||
import cn.cloudwalk.data.organization.entity.ImgStorePerson;
|
||||
import cn.cloudwalk.data.organization.entity.ImgStorePersonAudit;
|
||||
import cn.cloudwalk.data.organization.entity.ImgStorePersonAuditApply;
|
||||
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.mapper.ImgStoreLabelMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStoreOrganizationMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonAuditMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonLabelMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonOrganizationMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonPropertiesMapper;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import cn.cloudwalk.service.organization.common.JsonUtils;
|
||||
import cn.cloudwalk.service.organization.service.feign.VehicleFeignClient;
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Sets;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
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.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
@Service
|
||||
public class ImgPersonHandler extends AbstractImagStoreService {
|
||||
@Value("${imageQualityScore}")
|
||||
private Double imgQualityScore;
|
||||
|
||||
@Autowired private ImgStorePersonMapper imgStorePersonMapper;
|
||||
@Autowired private ImgStorePersonPropertiesMapper propertiesMapper;
|
||||
@Autowired private ImgStorePersonOrganizationMapper imgStorePersonOrganizationMapper;
|
||||
@Autowired private ImgStoreOrganizationMapper imgStoreOrganizationMapper;
|
||||
@Autowired private ImgStorePersonLabelMapper imgStorePersonLabelMapper;
|
||||
@Autowired private ImgStoreLabelMapper imgStoreLabelMapper;
|
||||
@Autowired private ImgPersonManager imgPersonManager;
|
||||
@Autowired private ImgStorePersonAuditMapper imgStorePersonAuditMapper;
|
||||
@Autowired private CpImageStorePersonSynManager cpImageStorePersonSynManager;
|
||||
@Resource private CpImageStorePersonManager cpImageStorePersonManager;
|
||||
@Autowired private MessageSource messageSource;
|
||||
@Autowired private CpImageStoreToolService cpImageStoreToolService;
|
||||
@Autowired private AgImageService agImageService;
|
||||
@Autowired private PortalUserService portalUserService;
|
||||
@Autowired private PersonRegistryService personRegistryService;
|
||||
@Autowired private AcBusinessService acBusinessService;
|
||||
@Autowired private AcAccountService acAccountService;
|
||||
@Autowired private UUIDSerial uuidSerial;
|
||||
@Autowired private PersonZoneRefService personZoneRefService;
|
||||
@Resource private PictureRevisionService pictureRevisionService;
|
||||
@Resource private VehicleFeignClient vehicleFeignClient;
|
||||
|
||||
@Transactional(
|
||||
propagation = Propagation.REQUIRED,
|
||||
rollbackFor = {Exception.class},
|
||||
value = "transactionManager")
|
||||
public List<String> addTransactional(
|
||||
AddImgPersonParam param, CloudwalkCallContext context, String personId)
|
||||
throws ImageStoreException, ServiceException {
|
||||
String businessId =
|
||||
StringUtils.isEmpty(param.getBusinessId())
|
||||
? context.getCompany().getCompanyId()
|
||||
: param.getBusinessId();
|
||||
ImgStorePerson personDto = new ImgStorePerson();
|
||||
boolean syncAccount =
|
||||
(param.getCreateSysAccount() != null && param.getCreateSysAccount().intValue() == 1);
|
||||
if (syncAccount && StringUtils.isBlank(param.getSysAccountId())) {
|
||||
String errorMessage =
|
||||
this.messageSource.getMessage("53014027", null, LocaleContextHolder.getLocale());
|
||||
throw new ServiceException("53014027", errorMessage);
|
||||
}
|
||||
if (CollectionUtils.isEmpty(param.getLabelIds())
|
||||
&& CollectionUtils.isEmpty(param.getOrganizationIds())) {
|
||||
String errorMessage =
|
||||
this.messageSource.getMessage("53014020", null, LocaleContextHolder.getLocale());
|
||||
throw new ServiceException("53014020", errorMessage);
|
||||
}
|
||||
if (!StringUtils.isEmpty(param.getComparePicture())) {
|
||||
AgFeatureExtractParam featureExtractParam = new AgFeatureExtractParam();
|
||||
featureExtractParam.setImageUrl(param.getComparePicture());
|
||||
CloudwalkResult<AgFeatureExtractResult> result =
|
||||
this.cpImageStoreToolService.extractFeature(featureExtractParam);
|
||||
this.logger.info("scoreResult:{}", JSONObject.toJSONString(result));
|
||||
if (result.isSuccess()) {
|
||||
AgFeatureExtractResult featureExtractResult = (AgFeatureExtractResult) result.getData();
|
||||
if (featureExtractResult != null) {
|
||||
Double score = featureExtractResult.getScore();
|
||||
this.logger.info("score:{}", score);
|
||||
if (this.imgQualityScore.doubleValue() > score.doubleValue()) {
|
||||
String errorMessage =
|
||||
"系统要求识别质量分>=" + this.imgQualityScore + ",当前识别质量分:" + score + ",请重新上传。";
|
||||
throw new ServiceException("53003820", errorMessage);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw new ServiceException(result.getCode(), result.getMessage());
|
||||
}
|
||||
}
|
||||
ImgStorePersonProperties properties = new ImgStorePersonProperties();
|
||||
properties.setBusinessId(businessId);
|
||||
List<ImgStorePersonProperties> personProperties = this.propertiesMapper.select(properties);
|
||||
checkPersonProperties(personProperties);
|
||||
for (ImgStorePersonProperties property : personProperties) {
|
||||
checkParam(property, param);
|
||||
populateBean(property, param, personDto);
|
||||
}
|
||||
if (syncAccount) {
|
||||
addAccount(param, businessId, personId);
|
||||
} else {
|
||||
param.setCreateSysAccount(Short.valueOf((short) 0));
|
||||
param.setSysAccountId(null);
|
||||
}
|
||||
BeanCopyUtils.copyProperties(param, context, personDto);
|
||||
personDto.setId(personId);
|
||||
if (!StringUtils.isEmpty(param.getComparePicture())) {
|
||||
personDto.setImageId(this.imgPersonManager.addAgImage(param.getComparePicture(), context));
|
||||
}
|
||||
personDto.setShowPicture(param.getShowPicture());
|
||||
personDto.setComparePicture(param.getComparePicture());
|
||||
personDto.setBusinessId(businessId);
|
||||
String caller = context.getUser().getCaller();
|
||||
long time = System.currentTimeMillis();
|
||||
personDto.setCreateUserId(caller);
|
||||
personDto.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
personDto.setStatus(Short.valueOf((short) 0));
|
||||
personDto.setCreateTime(Long.valueOf(time));
|
||||
personDto.setLastUpdateTime(Long.valueOf(time));
|
||||
personDto.setLastUpdateUserId(caller);
|
||||
personDto.setCreateSysAccount(
|
||||
Short.valueOf(
|
||||
(param.getCreateSysAccount() == null) ? 0 : param.getCreateSysAccount().shortValue()));
|
||||
personDto.setSource(
|
||||
(param.getSource() != null) ? param.getSource() : CpPersonSourceEnum.PAGE.getCode());
|
||||
personDto.setReserveInfo(param.getReserveInfo());
|
||||
personDto.setWelcome(param.getWelcome());
|
||||
personDto.setExpiryBeginDate(param.getExpiryBeginDate());
|
||||
personDto.setExpiryEndDate(param.getExpiryEndDate());
|
||||
personDto.setIcCardNo(param.getIcCardNo());
|
||||
personDto.setIcCardType(param.getIcCardType());
|
||||
personDto.setDefaultFloor(param.getDefaultFloor());
|
||||
personDto.setChooseFloor(param.getChooseFloor());
|
||||
this.imgStorePersonMapper.insert(personDto);
|
||||
List<String> organizationIds = param.getOrganizationIds();
|
||||
if (!CollectionUtil.isEmpty(organizationIds)) {
|
||||
List<ImgStorePersonOrganization> list1 = new ArrayList<>(organizationIds.size());
|
||||
for (String orgId : organizationIds) {
|
||||
ImgStorePersonOrganization imgStorePersonOrganization = new ImgStorePersonOrganization();
|
||||
imgStorePersonOrganization.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
imgStorePersonOrganization.setCreateUserId(caller);
|
||||
imgStorePersonOrganization.setPersonId(personId);
|
||||
imgStorePersonOrganization.setOrgId(orgId);
|
||||
imgStorePersonOrganization.setId(CloudwalkDateUtils.getUUID());
|
||||
list1.add(imgStorePersonOrganization);
|
||||
}
|
||||
this.imgStorePersonOrganizationMapper.insertBatch(list1);
|
||||
}
|
||||
List<String> labelIds = param.getLabelIds();
|
||||
if (!CollectionUtil.isEmpty(labelIds)) {
|
||||
List<ImgStorePersonLabel> list2 = new ArrayList<>(labelIds.size());
|
||||
for (String labelId : labelIds) {
|
||||
ImgStorePersonLabel imgStorePersonLabel = new ImgStorePersonLabel();
|
||||
imgStorePersonLabel.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
imgStorePersonLabel.setCreateUserId(caller);
|
||||
imgStorePersonLabel.setLabelId(labelId);
|
||||
imgStorePersonLabel.setPersonId(personId);
|
||||
imgStorePersonLabel.setId(CloudwalkDateUtils.getUUID());
|
||||
list2.add(imgStorePersonLabel);
|
||||
}
|
||||
this.imgStorePersonLabelMapper.insertBatch(list2);
|
||||
}
|
||||
List<String> zoneList = param.getZoneList();
|
||||
if (!CollectionUtils.isEmpty(zoneList)) {
|
||||
this.personZoneRefService.add(personDto.getId(), zoneList, personDto.getCreateUserId());
|
||||
}
|
||||
bindPersonVehicle(personDto.getId(), param.getVehicleList());
|
||||
return this.cpImageStorePersonSynManager.addGroupPersonSynTask(personId);
|
||||
}
|
||||
|
||||
private void bindPersonVehicle(String personId, List<String> vehicleList)
|
||||
throws ServiceException {
|
||||
if (StringUtils.isBlank(personId) || CollectionUtils.isEmpty(vehicleList)) {
|
||||
return;
|
||||
}
|
||||
AddVehiclePersonParam addVehiclePersonParam = new AddVehiclePersonParam();
|
||||
addVehiclePersonParam.setPersonId(personId);
|
||||
addVehiclePersonParam.setVehicleList(vehicleList);
|
||||
CloudwalkResult<Boolean> result =
|
||||
this.vehicleFeignClient.setVehiclePerson(addVehiclePersonParam);
|
||||
if (result == null
|
||||
|| result.getData() == null
|
||||
|| !((Boolean) result.getData()).booleanValue()) {
|
||||
this.logger.error("人员绑定车辆关系失败");
|
||||
throw new ServiceException("50001", "人员绑定车辆关系失败");
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(
|
||||
propagation = Propagation.REQUIRED,
|
||||
rollbackFor = {Exception.class},
|
||||
value = "transactionManager")
|
||||
public List<String> addExtTransactional(
|
||||
AddImgPersonParam param,
|
||||
ImgStorePerson personDto,
|
||||
CloudwalkCallContext context,
|
||||
String businessId,
|
||||
String userId,
|
||||
boolean syncAccount,
|
||||
String personId)
|
||||
throws ImageStoreException, ServiceException {
|
||||
ImgStorePersonProperties properties = new ImgStorePersonProperties();
|
||||
properties.setBusinessId(businessId);
|
||||
List<ImgStorePersonProperties> personProperties = this.propertiesMapper.select(properties);
|
||||
checkPersonProperties(personProperties);
|
||||
for (ImgStorePersonProperties property : personProperties) {
|
||||
checkParam(property, param);
|
||||
populateBean(property, param, personDto);
|
||||
}
|
||||
if (syncAccount) {
|
||||
addAccount(param, businessId, personId);
|
||||
} else {
|
||||
param.setCreateSysAccount(Short.valueOf((short) 0));
|
||||
param.setSysAccountId(null);
|
||||
}
|
||||
BeanCopyUtils.copyProperties(param, context, personDto);
|
||||
personDto.setId(personId);
|
||||
if (!StringUtils.isEmpty(param.getComparePicture())) {
|
||||
personDto.setImageId(this.imgPersonManager.addAgImage(param.getComparePicture(), context));
|
||||
}
|
||||
if (StringUtils.isEmpty(param.getShowPicture())
|
||||
&& !StringUtils.isEmpty(param.getComparePicture())) {
|
||||
personDto.setShowPicture(param.getComparePicture());
|
||||
}
|
||||
personDto.setComparePicture(param.getComparePicture());
|
||||
personDto.setBusinessId(businessId);
|
||||
personDto.setCreateUserId(userId);
|
||||
personDto.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
personDto.setIcCardType(param.getIcCardType());
|
||||
personDto.setIcCardNo(param.getIcCardNo());
|
||||
personDto.setWelcome(param.getWelcome());
|
||||
personDto.setStatus(Short.valueOf((short) 0));
|
||||
personDto.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
personDto.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
personDto.setLastUpdateUserId(userId);
|
||||
personDto.setCreateSysAccount(
|
||||
Short.valueOf(
|
||||
(param.getCreateSysAccount() == null) ? 0 : param.getCreateSysAccount().shortValue()));
|
||||
personDto.setSource(CpPersonSourceEnum.PAGE.getCode());
|
||||
this.imgStorePersonMapper.insert(personDto);
|
||||
List<String> organizationIds = param.getOrganizationIds();
|
||||
if (!CollectionUtil.isEmpty(organizationIds)) {
|
||||
List<ImgStorePersonOrganization> list1 = new ArrayList<>(organizationIds.size());
|
||||
for (String orgId : organizationIds) {
|
||||
ImgStorePersonOrganization imgStorePersonOrganization = new ImgStorePersonOrganization();
|
||||
imgStorePersonOrganization.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
imgStorePersonOrganization.setCreateUserId(userId);
|
||||
imgStorePersonOrganization.setPersonId(personId);
|
||||
imgStorePersonOrganization.setOrgId(orgId);
|
||||
imgStorePersonOrganization.setId(CloudwalkDateUtils.getUUID());
|
||||
list1.add(imgStorePersonOrganization);
|
||||
}
|
||||
this.imgStorePersonOrganizationMapper.insertBatch(list1);
|
||||
}
|
||||
List<String> labelIds = param.getLabelIds();
|
||||
if (!CollectionUtil.isEmpty(labelIds)) {
|
||||
List<ImgStorePersonLabel> list2 = new ArrayList<>(labelIds.size());
|
||||
for (String labelId : labelIds) {
|
||||
ImgStorePersonLabel imgStorePersonLabel = new ImgStorePersonLabel();
|
||||
imgStorePersonLabel.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
imgStorePersonLabel.setCreateUserId(userId);
|
||||
imgStorePersonLabel.setLabelId(labelId);
|
||||
imgStorePersonLabel.setPersonId(personId);
|
||||
imgStorePersonLabel.setId(CloudwalkDateUtils.getUUID());
|
||||
list2.add(imgStorePersonLabel);
|
||||
}
|
||||
this.imgStorePersonLabelMapper.insertBatch(list2);
|
||||
}
|
||||
return this.cpImageStorePersonSynManager.addGroupPersonSynTask(personId);
|
||||
}
|
||||
|
||||
@Transactional(
|
||||
propagation = Propagation.REQUIRED,
|
||||
rollbackFor = {Exception.class},
|
||||
value = "transactionManager")
|
||||
public List<String> editTransactional(
|
||||
ImgStorePerson person,
|
||||
String personId,
|
||||
List<String> organizationIds,
|
||||
List<String> labelIds,
|
||||
String caller,
|
||||
String oldImageId,
|
||||
List<String> vehicleList,
|
||||
CloudwalkCallContext context)
|
||||
throws ServiceException {
|
||||
Map<String, GroupPersonRef> imageStoreIdsMap =
|
||||
this.cpImageStorePersonManager.getImageStoreIdsByPerson(personId);
|
||||
List<String> oldImageStoreIds = Lists.newArrayList(imageStoreIdsMap.keySet());
|
||||
this.imgStorePersonMapper.updateByPrimaryKey(person);
|
||||
ImgStorePersonOrganization personOrganization = new ImgStorePersonOrganization();
|
||||
personOrganization.setPersonId(personId);
|
||||
this.imgStorePersonOrganizationMapper.delete(personOrganization);
|
||||
if (!CollectionUtils.isEmpty(organizationIds)) {
|
||||
List<ImgStorePersonOrganization> list1 = new ArrayList<>(organizationIds.size());
|
||||
for (String orgId : organizationIds) {
|
||||
ImgStorePersonOrganization imgStorePersonOrganization = new ImgStorePersonOrganization();
|
||||
imgStorePersonOrganization.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
imgStorePersonOrganization.setCreateUserId(caller);
|
||||
imgStorePersonOrganization.setPersonId(personId);
|
||||
imgStorePersonOrganization.setOrgId(orgId);
|
||||
imgStorePersonOrganization.setId(CloudwalkDateUtils.getUUID());
|
||||
list1.add(imgStorePersonOrganization);
|
||||
}
|
||||
this.imgStorePersonOrganizationMapper.insertBatch(list1);
|
||||
}
|
||||
ImgStorePersonLabel personLabel = new ImgStorePersonLabel();
|
||||
personLabel.setPersonId(personId);
|
||||
this.imgStorePersonLabelMapper.delete(personLabel);
|
||||
if (!CollectionUtils.isEmpty(labelIds)) {
|
||||
List<ImgStorePersonLabel> list2 = new ArrayList<>(labelIds.size());
|
||||
for (String labelId : labelIds) {
|
||||
ImgStorePersonLabel imgStorePersonLabel = new ImgStorePersonLabel();
|
||||
imgStorePersonLabel.setCreateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
imgStorePersonLabel.setCreateUserId(caller);
|
||||
imgStorePersonLabel.setLabelId(labelId);
|
||||
imgStorePersonLabel.setPersonId(personId);
|
||||
imgStorePersonLabel.setId(CloudwalkDateUtils.getUUID());
|
||||
list2.add(imgStorePersonLabel);
|
||||
}
|
||||
this.imgStorePersonLabelMapper.insertBatch(list2);
|
||||
}
|
||||
bindPersonVehicle(person.getId(), vehicleList);
|
||||
return this.cpImageStorePersonSynManager.addGroupPersonSynTask(
|
||||
personId, oldImageId, oldImageStoreIds);
|
||||
}
|
||||
|
||||
@Transactional(
|
||||
propagation = Propagation.REQUIRED,
|
||||
rollbackFor = {Exception.class},
|
||||
value = "transactionManager")
|
||||
public List<String> editSyncTransactional(ImgStorePerson person, String oldImageId) {
|
||||
Map<String, GroupPersonRef> imageStoreIdsMap =
|
||||
this.cpImageStorePersonManager.getImageStoreIdsByPerson(person.getId());
|
||||
List<String> oldImageStoreIds = Lists.newArrayList(imageStoreIdsMap.keySet());
|
||||
this.imgStorePersonMapper.updateSync(person);
|
||||
return this.cpImageStorePersonSynManager.addGroupPersonSynTask(
|
||||
person.getId(), oldImageId, oldImageStoreIds);
|
||||
}
|
||||
|
||||
@Transactional(
|
||||
propagation = Propagation.REQUIRED,
|
||||
rollbackFor = {Exception.class},
|
||||
value = "transactionManager")
|
||||
public List<String> deleteTransactional(
|
||||
QueryImgPersonParam param, CloudwalkCallContext context, Map<String, List<String>> delMap)
|
||||
throws ServiceException {
|
||||
ImgStorePersonDeleteDto deleteDto = new ImgStorePersonDeleteDto();
|
||||
deleteDto.setIds(param.getIds());
|
||||
deleteDto.setLastUpdateTime(Long.valueOf(System.currentTimeMillis()));
|
||||
this.imgStorePersonMapper.delete(deleteDto);
|
||||
ImgStorePersonQueryDto queryDto = new ImgStorePersonQueryDto();
|
||||
queryDto.setIds(param.getIds());
|
||||
List<ImgStorePerson> imgStorePersonList = this.imgStorePersonMapper.gets(queryDto);
|
||||
for (ImgStorePerson imgStorePerson : imgStorePersonList) {
|
||||
if (!StringUtils.isEmpty(imgStorePerson.getImageId())) {
|
||||
deleteAgImage(imgStorePerson.getImageId(), context);
|
||||
}
|
||||
}
|
||||
DelPersonOrgDTO delPersonOrgDTO = new DelPersonOrgDTO();
|
||||
delPersonOrgDTO.setPersonIds(param.getIds());
|
||||
this.imgStoreOrganizationMapper.delPerson(delPersonOrgDTO);
|
||||
DelPersonLabelDTO delPersonLabelDTO = new DelPersonLabelDTO();
|
||||
delPersonLabelDTO.setPersonIds(param.getIds());
|
||||
this.imgStoreLabelMapper.deletePerson(delPersonLabelDTO);
|
||||
List<String> imageIdResultList = Lists.newArrayList();
|
||||
for (Map.Entry<String, List<String>> entry : delMap.entrySet()) {
|
||||
GroupPersonSynData groupPersonSynData = new GroupPersonSynData();
|
||||
groupPersonSynData.setDelPersonIds(Lists.newArrayList(entry.getKey()));
|
||||
String jsonData = JsonUtils.toJson(groupPersonSynData);
|
||||
for (String imageStoreId : entry.getValue()) {
|
||||
this.cpImageStorePersonSynManager.addWaitSynTask(imageStoreId, jsonData);
|
||||
}
|
||||
imageIdResultList.addAll(entry.getValue());
|
||||
}
|
||||
return imageIdResultList;
|
||||
}
|
||||
|
||||
@Transactional(
|
||||
propagation = Propagation.REQUIRED,
|
||||
rollbackFor = {Exception.class},
|
||||
value = "transactionManager")
|
||||
public List<String> batchAgreeTransactional(
|
||||
CloudwalkCallContext context, List<ImgStorePersonAudit> auditList, String updateUserId)
|
||||
throws ServiceException, ImageStoreException {
|
||||
Set<String> imageIdResultSet = Sets.newHashSet();
|
||||
for (ImgStorePersonAudit item : auditList) {
|
||||
AddPersonAuditParam addPersonParam =
|
||||
(AddPersonAuditParam) BeanCopyUtils.copyProperties(item, AddPersonAuditParam.class);
|
||||
if (StringUtils.isNotEmpty(item.getOrganizationIds())) {
|
||||
addPersonParam.setOrganizationIds(Arrays.asList(item.getOrganizationIds().split(",")));
|
||||
}
|
||||
if (StringUtils.isNotEmpty(item.getLabelIds())) {
|
||||
addPersonParam.setLabelIds(Arrays.asList(item.getLabelIds().split(",")));
|
||||
}
|
||||
this.imgStorePersonAuditMapper.batchUpdate(
|
||||
Collections.singletonList(
|
||||
new ImgStorePersonAuditApply(
|
||||
item.getId(),
|
||||
Long.valueOf(System.currentTimeMillis()),
|
||||
updateUserId,
|
||||
CpPersonAuditEnum.AGREE.getCode())),
|
||||
CpPersonAuditEnum.INIT.getCode());
|
||||
String personId = this.uuidSerial.uuid();
|
||||
imageIdResultSet.addAll(
|
||||
addTransactional((AddImgPersonParam) addPersonParam, context, personId));
|
||||
}
|
||||
return Lists.newArrayList(imageIdResultSet);
|
||||
}
|
||||
|
||||
CloudwalkResult<String> checkUniqueProperty(
|
||||
String systemIdFiledName, AddImgPersonParam param, CloudwalkCallContext context)
|
||||
throws ServiceException {
|
||||
Field sourceField = ReflectionUtils.findField(param.getClass(), systemIdFiledName);
|
||||
Field targetField = ReflectionUtils.findField(ImgStorePersonQueryDto.class, systemIdFiledName);
|
||||
if (null == sourceField || null == targetField) {
|
||||
return CloudwalkResult.fail("53014016", getMessage("53014016"));
|
||||
}
|
||||
sourceField.setAccessible(true);
|
||||
targetField.setAccessible(true);
|
||||
Object systemIdFieldValue = ReflectionUtils.getField(sourceField, param);
|
||||
if (null == systemIdFieldValue || StringUtils.isBlank(systemIdFieldValue.toString())) {
|
||||
return CloudwalkResult.fail("53014027", getMessage("53014027"));
|
||||
}
|
||||
String businessId =
|
||||
StringUtils.isEmpty(param.getBusinessId())
|
||||
? context.getCompany().getCompanyId()
|
||||
: param.getBusinessId();
|
||||
ImgStorePersonQueryDto queryDto = new ImgStorePersonQueryDto();
|
||||
queryDto.setBusinessId(businessId);
|
||||
queryDto.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
queryDto.setCreateSysAccount(Short.valueOf((short) 1));
|
||||
ReflectionUtils.setField(targetField, queryDto, systemIdFieldValue);
|
||||
List<ImgStorePerson> queryList = this.imgStorePersonMapper.gets(queryDto);
|
||||
if (!CollectionUtils.isEmpty(queryList)) {
|
||||
if (systemIdFiledName.equals("personCode"))
|
||||
return CloudwalkResult.fail("53014012", getMessage("53014012"));
|
||||
if (systemIdFiledName.equals("phone"))
|
||||
return CloudwalkResult.fail("53014014", getMessage("53014014"));
|
||||
if (systemIdFiledName.equals("email"))
|
||||
return CloudwalkResult.fail("53014015", getMessage("53014015"));
|
||||
if (systemIdFiledName.equals("userName")) {
|
||||
return CloudwalkResult.fail("53014013", getMessage("53014013"));
|
||||
}
|
||||
return CloudwalkResult.fail("53014028", getMessage("53014028"));
|
||||
}
|
||||
if (null != param.getSource()
|
||||
&& Objects.equals(CpPersonSourceEnum.CERT.getCode(), param.getSource())) {
|
||||
QueryPersonRegistryParam registryParam = new QueryPersonRegistryParam();
|
||||
registryParam.setBusinessId(businessId);
|
||||
registryParam.setType(RegistryTypeEnum.CERT_REGISTRY.getValue());
|
||||
registryParam.setBindPropertyCode(CertPropertyEnum.CARD_ID.getValue());
|
||||
CloudwalkResult<PersonPropertiesResult> personPropertiesResult =
|
||||
this.personRegistryService.getBindProperty(registryParam, context);
|
||||
if (personPropertiesResult.isSuccess() && personPropertiesResult.getData() != null) {
|
||||
PersonPropertiesResult personProperties =
|
||||
(PersonPropertiesResult) personPropertiesResult.getData();
|
||||
ImgStorePerson personParam = new ImgStorePerson();
|
||||
personParam.setBusinessId(businessId);
|
||||
personParam.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
Field paramField = ReflectionUtils.findField(param.getClass(), personProperties.getCode());
|
||||
paramField.setAccessible(true);
|
||||
Object value = ReflectionUtils.getField(paramField, param);
|
||||
Field personParamField =
|
||||
ReflectionUtils.findField(personParam.getClass(), personProperties.getCode());
|
||||
personParamField.setAccessible(true);
|
||||
ReflectionUtils.setField(personParamField, personParam, value);
|
||||
queryList = this.imgStorePersonMapper.query(personParam);
|
||||
if (!CollectionUtil.isEmpty(queryList)) {
|
||||
String errorMessage =
|
||||
this.messageSource.getMessage("53014023", null, LocaleContextHolder.getLocale());
|
||||
return CloudwalkResult.fail("53014023", errorMessage);
|
||||
}
|
||||
} else {
|
||||
String errorMessage =
|
||||
this.messageSource.getMessage("53014022", null, LocaleContextHolder.getLocale());
|
||||
return CloudwalkResult.fail("53014022", errorMessage);
|
||||
}
|
||||
}
|
||||
return CloudwalkResult.success("");
|
||||
}
|
||||
|
||||
CloudwalkResult<String> checkUniqueProperty(AddImgPersonParam param, CloudwalkCallContext context)
|
||||
throws ServiceException {
|
||||
String businessId =
|
||||
StringUtils.isEmpty(param.getBusinessId())
|
||||
? context.getCompany().getCompanyId()
|
||||
: param.getBusinessId();
|
||||
if (!StringUtils.isEmpty(param.getPersonCode())) {
|
||||
ImgStorePersonQueryDto queryDto = new ImgStorePersonQueryDto();
|
||||
queryDto.setBusinessId(businessId);
|
||||
queryDto.setPersonCode(param.getPersonCode());
|
||||
queryDto.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
List<ImgStorePerson> queryList = this.imgStorePersonMapper.gets(queryDto);
|
||||
if (!CollectionUtil.isEmpty(queryList)) {
|
||||
String errorMessage =
|
||||
this.messageSource.getMessage("53014012", null, LocaleContextHolder.getLocale());
|
||||
return CloudwalkResult.fail("53014012", errorMessage);
|
||||
}
|
||||
}
|
||||
if (!StringUtils.isEmpty(param.getUserName())) {
|
||||
ImgStorePersonQueryDto queryDto = new ImgStorePersonQueryDto();
|
||||
queryDto.setBusinessId(businessId);
|
||||
queryDto.setUserName(param.getUserName());
|
||||
queryDto.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
List<ImgStorePerson> queryList = this.imgStorePersonMapper.gets(queryDto);
|
||||
if (!CollectionUtil.isEmpty(queryList)) {
|
||||
String errorMessage =
|
||||
this.messageSource.getMessage("53014013", null, LocaleContextHolder.getLocale());
|
||||
return CloudwalkResult.fail("53014013", errorMessage);
|
||||
}
|
||||
}
|
||||
if (null != param.getSource()
|
||||
&& Objects.equals(CpPersonSourceEnum.CERT.getCode(), param.getSource())) {
|
||||
QueryPersonRegistryParam registryParam = new QueryPersonRegistryParam();
|
||||
registryParam.setBusinessId(businessId);
|
||||
registryParam.setType(RegistryTypeEnum.CERT_REGISTRY.getValue());
|
||||
registryParam.setBindPropertyCode(CertPropertyEnum.CARD_ID.getValue());
|
||||
CloudwalkResult<PersonPropertiesResult> personPropertiesResult =
|
||||
this.personRegistryService.getBindProperty(registryParam, context);
|
||||
if (personPropertiesResult.isSuccess() && personPropertiesResult.getData() != null) {
|
||||
PersonPropertiesResult personProperties =
|
||||
(PersonPropertiesResult) personPropertiesResult.getData();
|
||||
ImgStorePerson personParam = new ImgStorePerson();
|
||||
personParam.setBusinessId(businessId);
|
||||
personParam.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
Field paramField = ReflectionUtils.findField(param.getClass(), personProperties.getCode());
|
||||
paramField.setAccessible(true);
|
||||
Object value = ReflectionUtils.getField(paramField, param);
|
||||
Field personParamField =
|
||||
ReflectionUtils.findField(personParam.getClass(), personProperties.getCode());
|
||||
personParamField.setAccessible(true);
|
||||
ReflectionUtils.setField(personParamField, personParam, value);
|
||||
List<ImgStorePerson> queryList = this.imgStorePersonMapper.query(personParam);
|
||||
if (!CollectionUtil.isEmpty(queryList)) {
|
||||
String errorMessage =
|
||||
this.messageSource.getMessage("53014023", null, LocaleContextHolder.getLocale());
|
||||
return CloudwalkResult.fail("53014023", errorMessage);
|
||||
}
|
||||
} else {
|
||||
String errorMessage =
|
||||
this.messageSource.getMessage("53014022", null, LocaleContextHolder.getLocale());
|
||||
return CloudwalkResult.fail("53014022", errorMessage);
|
||||
}
|
||||
}
|
||||
return CloudwalkResult.success("");
|
||||
}
|
||||
|
||||
void addAccount(AddImgPersonParam param, String businessId, String personId)
|
||||
throws ServiceException {
|
||||
PortalUserAccountBatchAddParam userAccountBatchAddParam = new PortalUserAccountBatchAddParam();
|
||||
userAccountBatchAddParam.setBusinessId(businessId);
|
||||
userAccountBatchAddParam.setUserInfos(generateUserInfo(param, personId));
|
||||
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());
|
||||
}
|
||||
List<PortalUserAccountBatchAddResult.ErrorInfo> errorInfoList =
|
||||
((PortalUserAccountBatchAddResult) batchAddResult.getData()).getErrorInfoList();
|
||||
if (!CollectionUtils.isEmpty(errorInfoList)) {
|
||||
PortalUserAccountBatchAddResult.ErrorInfo errorInfo = errorInfoList.get(0);
|
||||
throw new ServiceException("53014028", errorInfo.getErrorMsg());
|
||||
}
|
||||
}
|
||||
|
||||
void checkPersonProperties(List<ImgStorePersonProperties> personProperties)
|
||||
throws ImageStoreException {
|
||||
if (CollectionUtils.isEmpty(personProperties) || personProperties.size() < 10) {
|
||||
throw new ImageStoreException(
|
||||
"53014018",
|
||||
this.messageSource.getMessage("53014018", null, LocaleContextHolder.getLocale()));
|
||||
}
|
||||
}
|
||||
|
||||
void checkPropertiesDuplicate(EditImgPersonParam param, String businessId)
|
||||
throws ServiceException {
|
||||
if (StringUtils.isNotEmpty(param.getPhone())) {
|
||||
ImgStorePersonQueryDto queryDto = new ImgStorePersonQueryDto();
|
||||
queryDto.setBusinessId(businessId);
|
||||
queryDto.setPhone(param.getPhone());
|
||||
queryDto.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
List<ImgStorePerson> queryList = this.imgStorePersonMapper.gets(queryDto);
|
||||
if (!CollectionUtil.isEmpty(queryList)) {
|
||||
for (ImgStorePerson imgStorePerson : queryList) {
|
||||
if (!param.getId().equals(imgStorePerson.getId())) {
|
||||
String errorMessage =
|
||||
this.messageSource.getMessage("53014014", null, LocaleContextHolder.getLocale());
|
||||
throw new ServiceException("53014014", errorMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (StringUtils.isNotEmpty(param.getEmail())) {
|
||||
ImgStorePersonQueryDto queryDto = new ImgStorePersonQueryDto();
|
||||
queryDto.setBusinessId(businessId);
|
||||
queryDto.setEmail(param.getEmail());
|
||||
queryDto.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
List<ImgStorePerson> queryList = this.imgStorePersonMapper.gets(queryDto);
|
||||
if (!CollectionUtil.isEmpty(queryList)) {
|
||||
for (ImgStorePerson imgStorePerson : queryList) {
|
||||
if (!param.getId().equals(imgStorePerson.getId())) {
|
||||
String errorMessage =
|
||||
this.messageSource.getMessage("53014015", null, LocaleContextHolder.getLocale());
|
||||
throw new ServiceException("53014015", errorMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (StringUtils.isNotEmpty(param.getPersonCode())) {
|
||||
ImgStorePersonQueryDto queryDto = new ImgStorePersonQueryDto();
|
||||
queryDto.setBusinessId(businessId);
|
||||
queryDto.setPersonCode(param.getPersonCode());
|
||||
queryDto.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
List<ImgStorePerson> queryList = this.imgStorePersonMapper.gets(queryDto);
|
||||
if (!CollectionUtil.isEmpty(queryList)) {
|
||||
for (ImgStorePerson imgStorePerson : queryList) {
|
||||
if (!param.getId().equals(imgStorePerson.getId())) {
|
||||
String errorMessage =
|
||||
this.messageSource.getMessage("53014012", null, LocaleContextHolder.getLocale());
|
||||
throw new ServiceException("53014012", errorMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (StringUtils.isNotEmpty(param.getUserName())) {
|
||||
ImgStorePersonQueryDto queryDto = new ImgStorePersonQueryDto();
|
||||
queryDto.setBusinessId(businessId);
|
||||
queryDto.setUserName(param.getUserName());
|
||||
queryDto.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
List<ImgStorePerson> queryList = this.imgStorePersonMapper.gets(queryDto);
|
||||
if (!CollectionUtil.isEmpty(queryList)) {
|
||||
for (ImgStorePerson imgStorePerson : queryList) {
|
||||
if (!param.getId().equals(imgStorePerson.getId())) {
|
||||
String errorMessage =
|
||||
this.messageSource.getMessage("53014013", null, LocaleContextHolder.getLocale());
|
||||
throw new ServiceException("53014013", errorMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void checkPropertiesDuplicate(
|
||||
EditImgPersonParam param, String businessId, String systemIdFiledName)
|
||||
throws ServiceException {
|
||||
Field sourceField = ReflectionUtils.findField(param.getClass(), systemIdFiledName);
|
||||
Field targetField = ReflectionUtils.findField(ImgStorePersonQueryDto.class, systemIdFiledName);
|
||||
if (null == sourceField || null == targetField) {
|
||||
throw new ServiceException("53014016", getMessage("53014016"));
|
||||
}
|
||||
sourceField.setAccessible(true);
|
||||
targetField.setAccessible(true);
|
||||
Object fieldValue = ReflectionUtils.getField(sourceField, param);
|
||||
if (null == fieldValue || StringUtils.isBlank(fieldValue.toString())) {
|
||||
throw new ServiceException("53014027", getMessage("53014027"));
|
||||
}
|
||||
ImgStorePersonQueryDto queryDto = new ImgStorePersonQueryDto();
|
||||
queryDto.setBusinessId(businessId);
|
||||
queryDto.setIsDel(DelStatusEnum.NORAML.getCode());
|
||||
queryDto.setCreateSysAccount(Short.valueOf((short) 1));
|
||||
ReflectionUtils.setField(targetField, queryDto, fieldValue);
|
||||
List<ImgStorePerson> queryList = this.imgStorePersonMapper.gets(queryDto);
|
||||
if (!CollectionUtils.isEmpty(queryList)) {
|
||||
for (ImgStorePerson imgStorePerson : queryList) {
|
||||
if (!param.getId().equals(imgStorePerson.getId())) {
|
||||
if (systemIdFiledName.equals("personCode"))
|
||||
throw new ServiceException("53014012", getMessage("53014012"));
|
||||
if (systemIdFiledName.equals("phone"))
|
||||
throw new ServiceException("53014014", getMessage("53014014"));
|
||||
if (systemIdFiledName.equals("email"))
|
||||
throw new ServiceException("53014015", getMessage("53014015"));
|
||||
if (systemIdFiledName.equals("userName")) {
|
||||
throw new ServiceException("53014013", getMessage("53014013"));
|
||||
}
|
||||
throw new ServiceException("53014028", getMessage("53014028"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<PortalUserAccountBatchAddParam.UserInfo> generateUserInfo(
|
||||
AddImgPersonParam param, String personId) {
|
||||
PortalUserAccountBatchAddParam.UserInfo userInfo =
|
||||
new PortalUserAccountBatchAddParam.UserInfo();
|
||||
userInfo.setPersonId(personId);
|
||||
userInfo.setSystemId(param.getSysAccountId());
|
||||
userInfo.setName(param.getName());
|
||||
userInfo.setUserName(param.getUserName());
|
||||
userInfo.setEmail(param.getEmail());
|
||||
userInfo.setPhone(param.getPhone());
|
||||
userInfo.setPersonCode(param.getPersonCode());
|
||||
userInfo.setCorpAdmin(Short.valueOf((short) 2));
|
||||
userInfo.setUserLevel(Short.valueOf((short) 3));
|
||||
return Lists.newArrayList(userInfo);
|
||||
}
|
||||
|
||||
String updateAgImage(
|
||||
ImgStorePerson imgStorePersonById, String comparePicture, CloudwalkCallContext context)
|
||||
throws ServiceException {
|
||||
if (!StringUtils.isEmpty(imgStorePersonById.getImageId())) {
|
||||
deleteAgImage(imgStorePersonById.getImageId(), context);
|
||||
}
|
||||
return this.imgPersonManager.addAgImage(comparePicture, context);
|
||||
}
|
||||
|
||||
void deleteAgImage(String imageId, CloudwalkCallContext context) throws ServiceException {
|
||||
AgImageKeyParam keyParam = new AgImageKeyParam();
|
||||
keyParam.setImageId(imageId);
|
||||
CloudwalkResult<Boolean> deleteResult = this.agImageService.deleteImage(keyParam, context);
|
||||
if (!deleteResult.isSuccess()) {
|
||||
throw new ServiceException(deleteResult.getCode(), deleteResult.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
<T> void checkParam(ImgStorePersonProperties properties, T param) throws ImageStoreException {
|
||||
short required = properties.getHasRequired().shortValue();
|
||||
String fieldName = properties.getCode();
|
||||
Field field = ReflectionUtils.findField(param.getClass(), fieldName);
|
||||
if (field == null) {
|
||||
throw new ImageStoreException(
|
||||
"53014016",
|
||||
this.messageSource.getMessage("53014016", null, LocaleContextHolder.getLocale()));
|
||||
}
|
||||
field.setAccessible(true);
|
||||
Object fieldValue = ReflectionUtils.getField(field, param);
|
||||
if (required == 1 && (fieldValue == null || StringUtils.isBlank(String.valueOf(fieldValue)))) {
|
||||
throw new ImageStoreException("53014017", properties.getReminder());
|
||||
}
|
||||
}
|
||||
|
||||
<S, T> void populateBean(ImgStorePersonProperties properties, S source, T target)
|
||||
throws ImageStoreException {
|
||||
String fieldName = properties.getCode();
|
||||
if (!ImageStoreConstants.getCustProperties().contains(fieldName)) {
|
||||
return;
|
||||
}
|
||||
Field sourceField = ReflectionUtils.findField(source.getClass(), fieldName);
|
||||
Field targetField = ReflectionUtils.findField(target.getClass(), fieldName);
|
||||
if (sourceField == null || targetField == null) {
|
||||
throw new ImageStoreException(
|
||||
"53014016",
|
||||
this.messageSource.getMessage("53014016", null, LocaleContextHolder.getLocale()));
|
||||
}
|
||||
sourceField.setAccessible(true);
|
||||
targetField.setAccessible(true);
|
||||
Object fieldValue = ReflectionUtils.getField(sourceField, source);
|
||||
ReflectionUtils.setField(targetField, target, fieldValue);
|
||||
}
|
||||
}
|
||||
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.aggregate.group.param.AgImageUploadParam;
|
||||
import cn.cloudwalk.client.aggregate.group.result.AgImageUploadResult;
|
||||
import cn.cloudwalk.client.aggregate.group.service.AgImageService;
|
||||
import cn.cloudwalk.client.organization.common.constant.ImageStoreConstants;
|
||||
import cn.cloudwalk.client.organization.common.exception.ImageStoreException;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkCallContext;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
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.mapper.ImgStorePersonLabelMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonOrganizationMapper;
|
||||
import com.google.common.collect.Lists;
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
@Component
|
||||
public class ImgPersonManager {
|
||||
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
private static final List<String> IMAGE_FILE_FORMAT =
|
||||
Lists.newArrayList("bmp", "jpg", "jpeg", "png", "BMP", "JPG", "PNG");
|
||||
private static final String FILE_DOT = ".";
|
||||
@Autowired private AgImageService agImageService;
|
||||
@Autowired private ImgStorePersonOrganizationMapper personOrganizationMapper;
|
||||
@Autowired private ImgStorePersonLabelMapper personLabelMapper;
|
||||
@Autowired private ImgStorePersonMapper personMapper;
|
||||
|
||||
public String addAgImage(String comparePicture, CloudwalkCallContext context)
|
||||
throws ServiceException {
|
||||
this.logger.info("addAgImage start:{}", (Object) comparePicture);
|
||||
AgImageUploadParam uploadParam = new AgImageUploadParam();
|
||||
uploadParam.setType("person");
|
||||
uploadParam.setPath(comparePicture);
|
||||
CloudwalkResult addAgImageResult = this.agImageService.uploadImage(uploadParam, context);
|
||||
this.logger.info("addAgImage end:{}", (Object) comparePicture);
|
||||
if (!addAgImageResult.isSuccess()) {
|
||||
throw new ServiceException(addAgImageResult.getCode(), addAgImageResult.getMessage());
|
||||
}
|
||||
return ((AgImageUploadResult) addAgImageResult.getData()).getId();
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
public void batchInsertWithTx(
|
||||
List<ImgStorePerson> needInsertList,
|
||||
List<ImgStorePersonOrganization> personOrganizationList,
|
||||
List<ImgStorePersonLabel> personLabelList) {
|
||||
if (!CollectionUtils.isEmpty(needInsertList)) {
|
||||
this.personMapper.insertBatch(needInsertList);
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(personOrganizationList)) {
|
||||
this.personOrganizationMapper.insertBatch(personOrganizationList);
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(personLabelList)) {
|
||||
this.personLabelMapper.insertBatch(personLabelList);
|
||||
}
|
||||
}
|
||||
|
||||
public void checkImageFile(String filePath) throws ImageStoreException {
|
||||
File imageFile = new File(filePath);
|
||||
if (!imageFile.exists() || !imageFile.isFile()) {
|
||||
throw new ImageStoreException("53014017", "文件不存在");
|
||||
}
|
||||
if (!filePath.contains(FILE_DOT)) {
|
||||
throw new ImageStoreException("53014017", "获取文件格式失败");
|
||||
}
|
||||
String format = filePath.substring(filePath.lastIndexOf(FILE_DOT) + 1);
|
||||
if (!IMAGE_FILE_FORMAT.contains(format)) {
|
||||
throw new ImageStoreException("53014017", "图片格式不支持");
|
||||
}
|
||||
if (imageFile.length() > (long) ImageStoreConstants.MAX_FILE.intValue()) {
|
||||
throw new ImageStoreException("53014017", "图片大小不能超过3M");
|
||||
}
|
||||
}
|
||||
}
|
||||
+614
@@ -0,0 +1,614 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.common.constant.ImageStoreConstants;
|
||||
import cn.cloudwalk.client.organization.param.EngineListParam;
|
||||
import cn.cloudwalk.client.organization.personimg.param.AddImgPersonProParam;
|
||||
import cn.cloudwalk.client.organization.personimg.param.ImgPersonProParam;
|
||||
import cn.cloudwalk.client.organization.personimg.param.SwitchParam;
|
||||
import cn.cloudwalk.client.organization.personimg.result.ImgPersonProGetResult;
|
||||
import cn.cloudwalk.client.organization.personimg.service.ImgStorePersonPropertiesService;
|
||||
import cn.cloudwalk.client.organization.result.EngineListResult;
|
||||
import cn.cloudwalk.client.organization.result.EngineResult;
|
||||
import cn.cloudwalk.client.organization.result.PersonProListResult;
|
||||
import cn.cloudwalk.client.organization.result.PersonPropertiesSwitchResult;
|
||||
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.serial.UUIDSerial;
|
||||
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;
|
||||
import cn.cloudwalk.data.organization.mapper.PersonRegistryMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.PersonRegistryPropertiesMapper;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
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.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import javax.annotation.Resource;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
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("${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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1414
File diff suppressed because one or more lines are too long
+552
@@ -0,0 +1,552 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.aggregate.common.enums.DelStatusEnum;
|
||||
import cn.cloudwalk.client.organization.common.enums.OperationLogEnum;
|
||||
import cn.cloudwalk.client.organization.param.AcsDeviceRestructureConditionForm;
|
||||
import cn.cloudwalk.client.organization.param.AcsRestructureQueryForm;
|
||||
import cn.cloudwalk.client.organization.param.AddLabelParam;
|
||||
import cn.cloudwalk.client.organization.param.DelLabelParam;
|
||||
import cn.cloudwalk.client.organization.param.DelPersonLabelParam;
|
||||
import cn.cloudwalk.client.organization.param.EditLabelParam;
|
||||
import cn.cloudwalk.client.organization.param.LabelAddPersonParam;
|
||||
import cn.cloudwalk.client.organization.param.LabelResult;
|
||||
import cn.cloudwalk.client.organization.param.PageLabelParam;
|
||||
import cn.cloudwalk.client.organization.result.AcsDeviceNewResult;
|
||||
import cn.cloudwalk.client.organization.result.AcsDeviceRestructureResult;
|
||||
import cn.cloudwalk.client.organization.result.PageLabelResult;
|
||||
import cn.cloudwalk.client.organization.service.LabelService;
|
||||
import cn.cloudwalk.client.resource.user.result.UserQueryResult;
|
||||
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.data.organization.dto.AddPersonLabelDTO;
|
||||
import cn.cloudwalk.data.organization.dto.DelPersonLabelDTO;
|
||||
import cn.cloudwalk.data.organization.dto.GetsLabelDTO;
|
||||
import cn.cloudwalk.data.organization.dto.ImgStorePersonBatchUpdateDto;
|
||||
import cn.cloudwalk.data.organization.dto.ImgStorePersonQueryDto;
|
||||
import cn.cloudwalk.data.organization.dto.LabelCountDTO;
|
||||
import cn.cloudwalk.data.organization.dto.PageLabelDTO;
|
||||
import cn.cloudwalk.data.organization.entity.ImgStorePersonLabel;
|
||||
import cn.cloudwalk.data.organization.entity.Label;
|
||||
import cn.cloudwalk.data.organization.entity.SysLog;
|
||||
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.feign.CrkAccessFeignClient;
|
||||
import cn.cloudwalk.service.organization.service.feign.ElevatorFeignClient;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.github.pagehelper.Page;
|
||||
import com.github.pagehelper.PageHelper;
|
||||
import com.google.common.collect.Lists;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
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.util.CollectionUtils;
|
||||
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("${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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.param.OperationLogAddParam;
|
||||
import cn.cloudwalk.client.organization.param.OperationLogDelParam;
|
||||
import cn.cloudwalk.client.organization.service.IOperationLogService;
|
||||
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.OperationLog;
|
||||
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(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));
|
||||
}
|
||||
}
|
||||
|
||||
+1337
File diff suppressed because it is too large
Load Diff
+515
@@ -0,0 +1,515 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.common.enums.OrganizationTypeCodeEnum;
|
||||
import cn.cloudwalk.client.organization.param.AddVehiclePersonForm;
|
||||
import cn.cloudwalk.client.organization.param.QueryZoneUnitParam;
|
||||
import cn.cloudwalk.client.organization.param.organization.AddOrganizationParam;
|
||||
import cn.cloudwalk.client.organization.param.organization.DelOrganizationParam;
|
||||
import cn.cloudwalk.client.organization.param.organization.QueryOrganizationParam;
|
||||
import cn.cloudwalk.client.organization.result.VehicleCountCompany;
|
||||
import cn.cloudwalk.client.organization.result.ZoneUnitResultDTO;
|
||||
import cn.cloudwalk.client.organization.service.OrganizationService;
|
||||
import cn.cloudwalk.client.organization.service.store.result.OrganizationExtendResult;
|
||||
import cn.cloudwalk.client.organization.service.store.result.OrganizationResult;
|
||||
import cn.cloudwalk.cloud.annotation.CloudwalkParamsValidate;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkCallContext;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.cloud.utils.BeanCopyUtils;
|
||||
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.feign.VehicleFeignClient;
|
||||
import cn.cloudwalk.service.organization.service.feign.ZoneFeignClient;
|
||||
import java.util.ArrayList;
|
||||
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("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;
|
||||
|
||||
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("暂不支持新增单位");
|
||||
}
|
||||
}
|
||||
|
||||
+252
@@ -0,0 +1,252 @@
|
||||
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.result.OrganizationTypeListResult;
|
||||
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.List;
|
||||
import java.util.Map;
|
||||
import javax.annotation.Resource;
|
||||
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();
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
+1072
File diff suppressed because it is too large
Load Diff
+163
@@ -0,0 +1,163 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.common.enums.CertPropertyEnum;
|
||||
import cn.cloudwalk.client.organization.common.enums.CpPersonSourceEnum;
|
||||
import cn.cloudwalk.client.organization.common.enums.RegistryTypeEnum;
|
||||
import cn.cloudwalk.client.organization.personaudit.param.AddPersonAuditParam;
|
||||
import cn.cloudwalk.client.organization.personaudit.service.IPersonAuditServcie;
|
||||
import cn.cloudwalk.client.organization.service.PersonFileService;
|
||||
import cn.cloudwalk.client.organization.service.store.param.QueryPersonRegistryParam;
|
||||
import cn.cloudwalk.client.organization.service.store.result.PersonPropertiesResult;
|
||||
import cn.cloudwalk.client.organization.service.store.service.PersonRegistryService;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkCallContext;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
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 com.alibaba.fastjson.JSON;
|
||||
import java.lang.reflect.Field;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Collection;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Resource;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
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(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.ofNullable(value).map(Object::toString).orElse("0"))
|
||||
.intValue();
|
||||
if (1 == sexValue) {
|
||||
value = "男";
|
||||
} else if (2 == sexValue) {
|
||||
value = "女";
|
||||
} else {
|
||||
value = "未知";
|
||||
}
|
||||
}
|
||||
if (CertPropertyEnum.BIRTHDAY.getValue().equals(personProperties.getBindProp())) {
|
||||
String birthdayValue = Optional.ofNullable(value).map(Object::toString).orElse("");
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
+458
@@ -0,0 +1,458 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.aggregate.group.param.AgFeatureExtractParam;
|
||||
import cn.cloudwalk.client.aggregate.group.result.AgFeatureExtractResult;
|
||||
import cn.cloudwalk.client.organization.common.constant.ImageStoreConstants;
|
||||
import cn.cloudwalk.client.organization.result.FaceDetectResult;
|
||||
import cn.cloudwalk.client.organization.service.PersonFileService;
|
||||
import cn.cloudwalk.client.organization.service.store.param.CpFaceDetectParam;
|
||||
import cn.cloudwalk.client.organization.service.store.service.CpImageStoreToolService;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.cloud.serial.UUIDSerial;
|
||||
import cn.cloudwalk.intelligent.davinci.storage.bean.file.dto.FileRemoveDTO;
|
||||
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.FileContentType;
|
||||
import cn.cloudwalk.service.organization.common.FileType;
|
||||
import cn.cloudwalk.service.organization.common.FileUtil;
|
||||
import cn.cloudwalk.service.organization.common.ImageEditUtils;
|
||||
import cn.cloudwalk.service.organization.common.ImageUtil;
|
||||
import cn.cloudwalk.service.organization.common.OpenCvUtils;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import javax.annotation.Resource;
|
||||
import javax.imageio.ImageIO;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
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("${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;
|
||||
}
|
||||
}
|
||||
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
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.PersonPropertiesResult;
|
||||
import cn.cloudwalk.client.organization.service.store.result.PersonRegistryResult;
|
||||
import cn.cloudwalk.client.organization.service.store.service.PersonRegistryService;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkCallContext;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import cn.cloudwalk.service.organization.service.ServiceFactory;
|
||||
import java.util.List;
|
||||
import javax.annotation.Resource;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class PersonRegistryServiceImpl extends AbstractImagStoreService
|
||||
implements PersonRegistryService {
|
||||
@Resource private ServiceFactory serviceFactory;
|
||||
|
||||
public CloudwalkResult<Boolean> save(AddPersonRegistryParam param, CloudwalkCallContext context)
|
||||
throws ServiceException {
|
||||
return this.serviceFactory.getPersonRegistryHandler(param.getType()).save(param, context);
|
||||
}
|
||||
|
||||
public CloudwalkResult<PersonRegistryResult> detail(
|
||||
QueryPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
return this.serviceFactory.getPersonRegistryHandler(param.getType()).detail(param, context);
|
||||
}
|
||||
|
||||
public CloudwalkResult<List<PersonPropertiesResult>> getRegistryPropertyList(
|
||||
QueryPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
return this.serviceFactory
|
||||
.getPersonRegistryHandler(param.getType())
|
||||
.getRegistryPropertyList(param, context);
|
||||
}
|
||||
|
||||
public CloudwalkResult<List<PersonPropertiesResult>> getAuditPropertyList(
|
||||
QueryPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
return this.serviceFactory
|
||||
.getPersonRegistryHandler(param.getType())
|
||||
.getAuditPropertyList(param, context);
|
||||
}
|
||||
|
||||
public CloudwalkResult<PersonPropertiesResult> getUniqueRegistryProperty(
|
||||
QueryPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
return this.serviceFactory
|
||||
.getPersonRegistryHandler(param.getType())
|
||||
.getUniqueRegistryProperty(param, context);
|
||||
}
|
||||
|
||||
public CloudwalkResult<PersonPropertiesResult> getBindProperty(
|
||||
QueryPersonRegistryParam param, CloudwalkCallContext context) throws ServiceException {
|
||||
return this.serviceFactory
|
||||
.getPersonRegistryHandler(param.getType())
|
||||
.getBindProperty(param, context);
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.result.PersonZoneRefResult;
|
||||
import cn.cloudwalk.client.organization.service.PersonZoneRefService;
|
||||
import cn.cloudwalk.cloud.utils.BeanCopyUtils;
|
||||
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.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<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);
|
||||
}
|
||||
}
|
||||
|
||||
+274
@@ -0,0 +1,274 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.common.enums.SyncStatusEnum;
|
||||
import cn.cloudwalk.cwos.client.event.event.PictureResultEvent;
|
||||
import cn.cloudwalk.cwos.client.event.event.mode.ImageData;
|
||||
import cn.cloudwalk.data.organization.dto.DevicePersonSyncLogDTO;
|
||||
import cn.cloudwalk.data.organization.dto.QueryGroupPersonDTO;
|
||||
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.DevicePersonSyncLogMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.GroupPersonRefMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonMapper;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import javax.annotation.Resource;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
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.Component;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
@Component
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
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;
|
||||
import cn.cloudwalk.client.organization.param.PicChangeBackgroundParam;
|
||||
import cn.cloudwalk.client.organization.param.PicCropParam;
|
||||
import cn.cloudwalk.client.organization.param.PicRevisionParam;
|
||||
import cn.cloudwalk.client.organization.result.PictureRevisionResult;
|
||||
import cn.cloudwalk.client.organization.service.PictureRevisionService;
|
||||
import cn.cloudwalk.client.organization.service.store.param.ChangeBackgroundParam;
|
||||
import cn.cloudwalk.client.organization.service.store.param.CropParam;
|
||||
import cn.cloudwalk.client.organization.service.store.param.RevisionParam;
|
||||
import cn.cloudwalk.client.organization.service.store.service.CpImageStorePersonService;
|
||||
import cn.cloudwalk.client.organization.service.store.service.CpImageStoreToolService;
|
||||
import cn.cloudwalk.cloud.context.CloudwalkCallContext;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.data.organization.entity.ImgStorePerson;
|
||||
import cn.cloudwalk.data.organization.entity.PersonPropertiesSwitch;
|
||||
import cn.cloudwalk.data.organization.mapper.ImgStorePersonMapper;
|
||||
import cn.cloudwalk.data.organization.mapper.PersonPropertiesSwitchMapper;
|
||||
import cn.cloudwalk.intelligent.davinci.storage.manager.FileStorageManager;
|
||||
import cn.cloudwalk.service.organization.common.AbstractImagStoreService;
|
||||
import cn.cloudwalk.service.organization.common.ImageUtil;
|
||||
import cn.cloudwalk.service.organization.service.feign.PineappleEngineClient;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import java.util.Date;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import javax.annotation.Resource;
|
||||
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("${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();
|
||||
}
|
||||
}
|
||||
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.service.store.param.PortalUserQueryParam;
|
||||
import cn.cloudwalk.client.resource.user.result.UserQueryResult;
|
||||
import cn.cloudwalk.cloud.result.CloudwalkResult;
|
||||
import cn.cloudwalk.service.organization.service.feign.UserFeignClient;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import javax.annotation.Resource;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
@Service
|
||||
public class PortalUserServiceImpl {
|
||||
private static final Logger log = LoggerFactory.getLogger(PortalUserServiceImpl.class);
|
||||
@Resource private UserFeignClient userFeignClient;
|
||||
|
||||
public List<UserQueryResult> query(List<String> userIdList) {
|
||||
if (CollectionUtils.isEmpty(userIdList)) {
|
||||
return new ArrayList<UserQueryResult>();
|
||||
}
|
||||
PortalUserQueryParam userQueryParam = new PortalUserQueryParam();
|
||||
userQueryParam.setUserIds(userIdList);
|
||||
CloudwalkResult<List<UserQueryResult>> queryResult = null;
|
||||
try {
|
||||
queryResult = this.userFeignClient.query(userQueryParam);
|
||||
} catch (Exception e) {
|
||||
log.error("查询用户信息失败", e);
|
||||
}
|
||||
if (queryResult != null && queryResult.isSuccess()) {
|
||||
return (List) queryResult.getData();
|
||||
}
|
||||
return new ArrayList<UserQueryResult>();
|
||||
}
|
||||
}
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
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 cn.cloudwalk.service.organization.service.CommonPersonRegistryService;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.google.common.collect.Lists;
|
||||
import java.util.ArrayList;
|
||||
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(value="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 = this.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());
|
||||
this.update(param, context);
|
||||
} else {
|
||||
this.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((String)"53014502", (String)this.getMessage("53014502"));
|
||||
}
|
||||
if (CollectionUtils.isEmpty((Collection)param.getPropertyIdList())) {
|
||||
return CloudwalkResult.fail((String)"53014503", (String)this.getMessage("53014503"));
|
||||
}
|
||||
List<ImgStorePersonProperties> dbPersonProList = this.imgStorePersonPropertiesMapper.selectByIds(param.getBusinessId(), param.getPropertyIdList());
|
||||
if (CollectionUtils.isEmpty((Collection)dbPersonProList) || dbPersonProList.size() != param.getPropertyIdList().size()) {
|
||||
this.logger.warn("\u6ce8\u518c\u5c5e\u6027\u4e0d\u5c5e\u4e8e\u4eba\u5458\u57fa\u672c\u5c5e\u6027,\u6ce8\u518c\u5c5e\u6027Id\u5217\u8868:[{}]", (Object)JSONObject.toJSONString((Object)param.getPropertyIdList()));
|
||||
return CloudwalkResult.fail((String)"53014508", (String)this.getMessage("53014508"));
|
||||
}
|
||||
for (DefaultPropertyEnum default_property : DefaultPropertyEnum.values()) {
|
||||
Optional<ImgStorePersonProperties> requiredOptional = dbPersonProList.stream().filter((ImgStorePersonProperties property) -> default_property.getValue().equals(property.getCode())).findFirst();
|
||||
if (requiredOptional.isPresent()) continue;
|
||||
this.logger.warn("{}\u672a\u52fe\u9009,\u6ce8\u518c\u5c5e\u6027Id\u5217\u8868:[{}]", (Object)default_property.getDescription(), (Object)JSONObject.toJSONString((Object)param.getPropertyIdList()));
|
||||
return CloudwalkResult.fail((String)"53014511", (String)("\u6ce8\u518c\u5c5e\u6027" + default_property.getDescription() + "\u5fc5\u987b\u52fe\u9009"));
|
||||
}
|
||||
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((Collection)requiredPersonProList)) {
|
||||
List requiredPersonProIdList = Collections3.extractToList((Collection)requiredPersonProList, (String)"id");
|
||||
if ((dbPersonProList = dbPersonProList.stream().filter((ImgStorePersonProperties pro) -> requiredPersonProIdList.contains(pro.getId())).collect(Collectors.toList())).size() != requiredPersonProList.size()) {
|
||||
this.logger.warn("\u8bbe\u5907\u6ce8\u518c\u5ba1\u6838\u548c\u626b\u7801\u6ce8\u518c\u5ba1\u6838\u672a\u540c\u65f6\u6253\u5f00,\u6709\u672a\u52fe\u9009\u7684\u5fc5\u586b\u5c5e\u6027,\u6ce8\u518c\u5c5e\u6027Id\u5217\u8868:[{}]", (Object)JSONObject.toJSONString((Object)param.getPropertyIdList()));
|
||||
return CloudwalkResult.fail((String)"53014511", (String)this.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 = this.getPrimaryId();
|
||||
this.commonPersonRegistryService.insertPersonRegistry(id, param, context);
|
||||
this.commonPersonRegistryService.batchInsertPersonRegistryProperty(id, param);
|
||||
this.commonPersonRegistryService.batchInsertPersonRegistryDevice(id, param, context, 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, 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((CharSequence)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((Collection)personPropertyList)) {
|
||||
this.logger.warn("\u4e0d\u5b58\u5728\u4eba\u5458\u5c5e\u6027");
|
||||
return CloudwalkResult.fail((String)"53014524", (String)this.getMessage("53014524"));
|
||||
}
|
||||
List<PersonPropertiesResult> proResultList = BeanCopyUtils.copy((Collection)personPropertyList, PersonPropertiesResult.class);
|
||||
proResultList.forEach(propertyResult -> {
|
||||
if (DefaultPropertyEnum.hasProperty((String)propertyResult.getCode())) {
|
||||
propertyResult.setHasChecked(StatusEnum.CHECKED.getValue());
|
||||
propertyResult.setHasDisabled(StatusEnum.DISABLED.getValue());
|
||||
}
|
||||
});
|
||||
proResultList = 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((Object)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((Collection)dbPersonRegistryDeviceList)) {
|
||||
CoreDeviceQueryParam coreDeviceQueryParam = new CoreDeviceQueryParam();
|
||||
coreDeviceQueryParam.setBusinessId(businessId);
|
||||
coreDeviceQueryParam.setDeviceCodes(Collections3.extractToList((Collection)dbPersonRegistryDeviceList, (String)"deviceCode"));
|
||||
CloudwalkResult<List<AtomicDeviceGetResult>> deviceGetResult = this.atomicDeviceService.list(coreDeviceQueryParam, context);
|
||||
if (!CollectionUtils.isEmpty(deviceGetResult.getData())) {
|
||||
List<AtomicDeviceGetResult> deviceData = deviceGetResult.getData();
|
||||
List<DeviceResult> deviceResultList = Lists.newArrayListWithCapacity(deviceData.size());
|
||||
deviceData.forEach((AtomicDeviceGetResult 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 personPropertyIdList = Collections3.extractToList((Collection)dbPersonRegistryProList, (String)"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((CharSequence)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(this.getPersonPropertyList(dbPersonRegistry, true));
|
||||
}
|
||||
|
||||
@CloudwalkParamsValidate
|
||||
public CloudwalkResult<List<PersonPropertiesResult>> getAuditPropertyList(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.SELF_REGISTRY.getValue()).getData();
|
||||
return CloudwalkResult.success(this.getPersonPropertyList(dbPersonRegistry, false));
|
||||
}
|
||||
|
||||
private List<PersonPropertiesResult> getPersonPropertyList(PersonRegistry personRegistry, boolean isChecked) {
|
||||
List<PersonRegistryProperties> dbPersonRegistryProList = this.personRegistryPropertiesMapper.select(personRegistry.getId(), null);
|
||||
List personProIdList = Collections3.extractToList((Collection)dbPersonRegistryProList, (String)"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((Collection)dbPersonProList, PersonPropertiesResult.class);
|
||||
List<PersonPropertiesResult> defaultProList = BeanCopyUtils.copy((Collection)dbPersonProList, PersonPropertiesResult.class);
|
||||
proResultList = proResultList.stream().filter((PersonPropertiesResult proResult) -> personProIdList.contains(proResult.getId()) == isChecked).collect(Collectors.toList());
|
||||
defaultProList = defaultProList.stream().filter((PersonPropertiesResult proResult) -> DefaultPropertyEnum.hasProperty((String)proResult.getCode())).collect(Collectors.toList());
|
||||
if (isChecked) {
|
||||
proResultList.removeAll(defaultProList);
|
||||
proResultList.addAll(defaultProList);
|
||||
proResultList.forEach(proResult -> {
|
||||
proResult.setHasChecked(StatusEnum.CHECKED.getValue());
|
||||
if (DefaultPropertyEnum.hasProperty((String)proResult.getCode())) {
|
||||
proResult.setHasDisabled(StatusEnum.DISABLED.getValue());
|
||||
}
|
||||
});
|
||||
} else {
|
||||
proResultList.removeAll(defaultProList);
|
||||
}
|
||||
proResultList = 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((CharSequence)businessId)) {
|
||||
businessId = context.getCompany().getCompanyId();
|
||||
}
|
||||
PersonRegistry dbPersonRegistry = (PersonRegistry)this.commonPersonRegistryService.getResultByBusinessAndType(businessId, RegistryTypeEnum.SELF_REGISTRY.getValue()).getData();
|
||||
List<PersonPropertiesResult> propertyList = this.getPersonPropertyList(dbPersonRegistry, true);
|
||||
AtomicReference<PersonPropertiesResult> result = new AtomicReference<PersonPropertiesResult>();
|
||||
propertyList.stream().filter(property -> UniquePropertyEnum.hasProperty((String)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;
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package cn.cloudwalk.service.organization.service;
|
||||
|
||||
// 业务服务
|
||||
import cn.cloudwalk.client.organization.common.enums.RegistryTypeEnum;
|
||||
import cn.cloudwalk.client.organization.service.store.service.IPersonRegistryHandler;
|
||||
import cn.cloudwalk.cloud.exception.ServiceException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import javax.annotation.Resource;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class ServiceFactory {
|
||||
@Resource
|
||||
Map<String, IPersonRegistryHandler> registryHandlerMap =
|
||||
new ConcurrentHashMap<String, IPersonRegistryHandler>(10);
|
||||
|
||||
public IPersonRegistryHandler getPersonRegistryHandler(Integer component)
|
||||
throws ServiceException {
|
||||
AtomicReference<String> handler =
|
||||
new AtomicReference<String>(RegistryTypeEnum.SELF_REGISTRY.getHandler());
|
||||
Arrays.asList(RegistryTypeEnum.values()).stream()
|
||||
.filter(type -> Objects.equals(component, type.getValue()))
|
||||
.findFirst()
|
||||
.ifPresent(type -> handler.set(type.getHandler()));
|
||||
IPersonRegistryHandler personRegistryHandler = this.registryHandlerMap.get(handler.get());
|
||||
if (null == personRegistryHandler) {
|
||||
throw new ServiceException("No PersonRegistryHandler Defined");
|
||||
}
|
||||
return personRegistryHandler;
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package cn.cloudwalk.service.organization.service.common;
|
||||
|
||||
// 业务服务
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
|
||||
public abstract class AbstractFallback {
|
||||
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
@Autowired private MessageSource messageSource;
|
||||
|
||||
public String getMessage(String code, String defaultMsg) {
|
||||
return this.messageSource.getMessage(
|
||||
code, (Object[]) null, defaultMsg, LocaleContextHolder.getLocale());
|
||||
}
|
||||
|
||||
public String getMessage(String code) {
|
||||
return this.getMessage(code, "");
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
package cn.cloudwalk.service.organization.service.common;
|
||||
|
||||
// 业务服务
|
||||
import com.netflix.hystrix.HystrixThreadPoolKey;
|
||||
import com.netflix.hystrix.HystrixThreadPoolProperties;
|
||||
import com.netflix.hystrix.strategy.HystrixPlugins;
|
||||
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
|
||||
import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariable;
|
||||
import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableLifecycle;
|
||||
import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier;
|
||||
import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook;
|
||||
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisher;
|
||||
import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy;
|
||||
import com.netflix.hystrix.strategy.properties.HystrixProperty;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.request.RequestAttributes;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
|
||||
@Component
|
||||
public class RequestAttributeHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {
|
||||
private static final Logger log =
|
||||
LoggerFactory.getLogger(RequestAttributeHystrixConcurrencyStrategy.class);
|
||||
private HystrixConcurrencyStrategy delegate;
|
||||
|
||||
public RequestAttributeHystrixConcurrencyStrategy() {
|
||||
try {
|
||||
this.delegate = HystrixPlugins.getInstance().getConcurrencyStrategy();
|
||||
if (this.delegate instanceof RequestAttributeHystrixConcurrencyStrategy) {
|
||||
return;
|
||||
}
|
||||
HystrixCommandExecutionHook commandExecutionHook =
|
||||
HystrixPlugins.getInstance().getCommandExecutionHook();
|
||||
HystrixEventNotifier eventNotifier = HystrixPlugins.getInstance().getEventNotifier();
|
||||
HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance().getMetricsPublisher();
|
||||
HystrixPropertiesStrategy propertiesStrategy =
|
||||
HystrixPlugins.getInstance().getPropertiesStrategy();
|
||||
this.logCurrentStateOfHystrixPlugins(eventNotifier, metricsPublisher, propertiesStrategy);
|
||||
HystrixPlugins.reset();
|
||||
HystrixPlugins.getInstance().registerConcurrencyStrategy((HystrixConcurrencyStrategy) this);
|
||||
HystrixPlugins.getInstance().registerCommandExecutionHook(commandExecutionHook);
|
||||
HystrixPlugins.getInstance().registerEventNotifier(eventNotifier);
|
||||
HystrixPlugins.getInstance().registerMetricsPublisher(metricsPublisher);
|
||||
HystrixPlugins.getInstance().registerPropertiesStrategy(propertiesStrategy);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to register Sleuth Hystrix Concurrency Strategy", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void logCurrentStateOfHystrixPlugins(
|
||||
HystrixEventNotifier eventNotifier,
|
||||
HystrixMetricsPublisher metricsPublisher,
|
||||
HystrixPropertiesStrategy propertiesStrategy) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(
|
||||
"Current Hystrix plugins configuration is [concurrencyStrategy ["
|
||||
+ this.delegate
|
||||
+ "],eventNotifier ["
|
||||
+ eventNotifier
|
||||
+ "],metricPublisher ["
|
||||
+ metricsPublisher
|
||||
+ "],propertiesStrategy ["
|
||||
+ propertiesStrategy
|
||||
+ "],]");
|
||||
log.debug("Registering Sleuth Hystrix Concurrency Strategy.");
|
||||
}
|
||||
}
|
||||
|
||||
public <T> Callable<T> wrapCallable(Callable<T> callable) {
|
||||
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
|
||||
return new WrappedCallable<T>(callable, requestAttributes);
|
||||
}
|
||||
|
||||
public ThreadPoolExecutor getThreadPool(
|
||||
HystrixThreadPoolKey threadPoolKey,
|
||||
HystrixProperty<Integer> corePoolSize,
|
||||
HystrixProperty<Integer> maximumPoolSize,
|
||||
HystrixProperty<Integer> keepAliveTime,
|
||||
TimeUnit unit,
|
||||
BlockingQueue<Runnable> workQueue) {
|
||||
return this.delegate.getThreadPool(
|
||||
threadPoolKey, corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
|
||||
}
|
||||
|
||||
public ThreadPoolExecutor getThreadPool(
|
||||
HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties threadPoolProperties) {
|
||||
return this.delegate.getThreadPool(threadPoolKey, threadPoolProperties);
|
||||
}
|
||||
|
||||
public BlockingQueue<Runnable> getBlockingQueue(int maxQueueSize) {
|
||||
return this.delegate.getBlockingQueue(maxQueueSize);
|
||||
}
|
||||
|
||||
public <T> HystrixRequestVariable<T> getRequestVariable(HystrixRequestVariableLifecycle<T> rv) {
|
||||
return this.delegate.getRequestVariable(rv);
|
||||
}
|
||||
|
||||
static class WrappedCallable<T> implements Callable<T> {
|
||||
private final Callable<T> target;
|
||||
private final RequestAttributes requestAttributes;
|
||||
|
||||
public WrappedCallable(Callable<T> target, RequestAttributes requestAttributes) {
|
||||
this.target = target;
|
||||
this.requestAttributes = requestAttributes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T call() throws Exception {
|
||||
try {
|
||||
RequestContextHolder.setRequestAttributes((RequestAttributes) this.requestAttributes);
|
||||
T t = this.target.call();
|
||||
return t;
|
||||
} finally {
|
||||
RequestContextHolder.resetRequestAttributes();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user