迁移代码

topo_dev
xueqingkun 11 months ago
parent a7171abf33
commit 4bd793e1e2

@ -0,0 +1,191 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.supervision</groupId>
<artifactId>spring-ai-demo</artifactId>
<version>1.0.0</version>
<name>spring-ai-demo</name>
<description>spring-ai-demo</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 引入ollama的依赖.版本号来自于 dependencyManagement中 spring-ai-bom中的版本号.-->
<dependency>
<groupId>io.springboot.ai</groupId>
<artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.26</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-3-starter</artifactId>
<version>1.2.21</version>
</dependency>
<!-- neo4j 驱动 -->
<dependency>
<groupId>org.neo4j.driver</groupId>
<artifactId>neo4j-java-driver</artifactId>
<version>5.21.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-neo4j</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.8</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-api</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
<version>2.0.2</version>
</dependency>
<!-- Hibernate Validator 实现 -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.7.Final</version>
</dependency>
<!-- 可能还需要验证器提供的依赖项,如 EL 实现 -->
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>jakarta.el</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<!-- minio -->
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.2.2</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.springboot.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>1.0.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>

@ -0,0 +1,15 @@
package com.supervision;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan(basePackages = {"com.supervision.**.mapper"})
@SpringBootApplication(scanBasePackages = {"com.supervision.**"})
public class SpringAiDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringAiDemoApplication.class, args);
}
}

@ -0,0 +1,69 @@
package com.supervision.common.constant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
*
*
* @author qimaoyu
* @version 1.0.0 2020/10/20 11:07
* @since JDK17
*/
public class Constants {//常量类
/**
* UTF-8
*/
public static final String UTF8 = "UTF-8";
/**
* GBK
*/
public static final String GBK = "GBK";
/**
* http
*/
public static final String HTTP = "http://";
/**
* https
*/
public static final String HTTPS = "https://";
/**
*
*/
public static final Integer SUCCESS = 200;
/**
*
*/
public static final Integer FAIL = 500;
/**
*
*/
public static final String PHONE_ENCODING = "UTF-8";
/**
* jwt:
* secret: XX$^^&^%%VHGZ!@@$#%@#%$%$^VBJHA7938217649&*^GBHU
* issuer: dareway.user
* expires: 12
*
*/
public static final String SECRET = "XX$^^&^%%VHGZ!@@$#%@#%$%$^VBJHA7938217649&*^GBHU";
public static final String ISSUER = "dareway.user";
public static final int EXPIRES_TIME = 12;
public static final String TOTAL_COUNT = "total";
public static final String RESULT_LIST = "result";
public static final String COMMA = ",";
public static final String CONTENT_TYPE_OCTET_STREAM = "application/octet-stream";
}

@ -0,0 +1,147 @@
package com.supervision.common.domain;
import com.supervision.common.constant.Constants;
import com.supervision.common.enums.ResultStatusEnum;
import lombok.Data;
import java.io.Serializable;
import java.util.*;
/**
*
*
* @author qimaoyu
*/
@Data
public class R<T> implements Serializable {
private static final long serialVersionUID = 1L;
public static final String TOTAL_COUNT = "total";
public static final String RESULT_LIST = "result";
/** 成功 */
public static final int SUCCESS = Constants.SUCCESS;
/** 失败 */
public static final int FAIL = Constants.FAIL;
private int code;
private String msg;
private T data;
public static <T> R<T> ok() {
return restResult(null, SUCCESS, null);
}
public static <T> R<T> okMsg(String msg) {
return restResult(null, SUCCESS, msg);
}
public static <T> R<T> ok(T data) {
return restResult(data, SUCCESS, null);
}
public static <T> R<T> ok(T data, String msg) {
return restResult(data, SUCCESS, msg);
}
public static <T> R<T> fail() {
return restResult(null, FAIL, null);
}
public static <T> R<T> fail(String msg) {
return restResult(null, FAIL, msg);
}
public static <T> R<T> fail(T data) {
return restResult(data, FAIL, null);
}
public static <T> R<T> fail(T data, String msg) {
return restResult(data, FAIL, msg);
}
public static <T> R<T> fail(int code, String msg) {
return restResult(null, code, msg);
}
public static <T> R<T> fail(ResultStatusEnum resultStatusEnum) {
return restResult(resultStatusEnum);
}
public static <T> R<T> fail(ResultStatusEnum resultStatusEnum, T data) {return restResult(resultStatusEnum,data);}
private static <T> R<T> restResult(ResultStatusEnum resultStatusEnum, T data) {
R<T> apiResult = new R<>();
apiResult.setCode(resultStatusEnum.getCode());
apiResult.setData(data);
apiResult.setMsg(resultStatusEnum.getMessage());
return apiResult;
}
private static <T> R<T> restResult(ResultStatusEnum resultStatusEnum) {
R<T> apiResult = new R<>();
apiResult.setCode(resultStatusEnum.getCode());
apiResult.setData(null);
apiResult.setMsg(resultStatusEnum.getMessage());
return apiResult;
}
private static <T> R<T> restResult(T data, int code, String msg) {
R<T> apiResult = new R<>();
apiResult.setCode(code);
apiResult.setData(data);
apiResult.setMsg(msg);
return apiResult;
}
public static Map<String, Object> buildDataMap(List list) {
Map<String, Object> dataMap = new HashMap<>();
if (list == null) {
dataMap.put(TOTAL_COUNT, 0);
dataMap.put(RESULT_LIST, new ArrayList<>());
} else {
dataMap.put(TOTAL_COUNT, list.size());
dataMap.put(RESULT_LIST, list);
}
return dataMap;
}
public static Map<String, Object> buildDataMap(List list, Long total) {
Map<String, Object> dataMap = new HashMap<>();
dataMap.put(TOTAL_COUNT, total);
dataMap.put(RESULT_LIST, list);
return dataMap;
}
public static Map<String, Object> buildDataMap(Set list) {
Map<String, Object> dataMap = new HashMap<>();
if (list == null) {
dataMap.put(TOTAL_COUNT, 0);
dataMap.put(RESULT_LIST, new ArrayList<>());
} else {
dataMap.put(TOTAL_COUNT, list.size());
dataMap.put(RESULT_LIST, list);
}
return dataMap;
}
public static Map<String, Object> buildDataMap(Object object) {
if (object == null) {
return null;
}
List<Object> resultList = new ArrayList<>();
resultList.add(object);
Map<String, Object> dataMap = new HashMap<>();
dataMap.put(TOTAL_COUNT, resultList.size());
dataMap.put(RESULT_LIST, resultList);
return dataMap;
}
}

@ -0,0 +1,51 @@
package com.supervision.common.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
*
* @author qimaoyu
* @create 2019-07-14 10:22
*/
@NoArgsConstructor
@AllArgsConstructor
public enum ResultStatusEnum {
AUTHENTICATION_FAILED(320, "token失效请重新登录"),
NO_ACCESS_TO_THIS_INTERFACE(320, "无权访问此接口!"),
FAILED_TO_GENERATE_TOKEN(321, "生成token失败"),
ACCOUNT_PASSWORD_INCORRECT(322, "账号或密码错误!"),
ACCOUNT_NOT_CREATE(323, "账号未创建!"),
HAS_BEEN_PULLED_BLACK(324, "已被删除或禁用,无法登录!"),
USERNAME_MAIL_IS_EXIST(341, "登录名称已经被注册!"),
USERNAME_IS_BLANK(342, "登录名称为空!"),
VERIFICATION_CODE_EXPIRED(350,"验证码已过期,请重新获取。"),
VERIFICATION_CODE_FAILURE(351,"验证码输入错误。"),
OPERATE_FAIL(360,"修改毕业生信息失败。"),
DATA_IS_EMPTY(370,"查询到的结果为空"),
SYSTEM_ABNORMAL(500, "系统繁忙,请稍后重试!"),
UPLOAD_EXCEPTION(501, "文件上传异常!"),
EXPORT_EXCEPTION(502, "文件导出异常!"),
INCORRECT_FILE_FORMAT(503, "文件格式不正确!"),
PARAMETER_CANNOT_BE_EMPTY(504, "参数不能为空,操作失败!"),
NO_TEMP_UPLOADFILEPATH(505,"未配置文件上传临时存储路径"),
USER_DOES_NOT_EXIST(507, "用户不存在,操作失败!"),
IMPORT_COMPANY_FORMAT_ERROR(521,"Excel表格格式错误"),
IMPORT_COMPANY_FAIL(522,"部分数据导入失败"),
INSERT_FAIL(600,"新增失败"),
DuplicateKeyException(601,"该条信息已经存在,请勿重复添加"),
UPDATE_FAIL(700,"更新失败"),
DELETE_FAIL(800,"删除失败"),
YEAR_IS_CLOSE(1001,"该年度暂未开启");
@Getter
@Setter
private int code;
@Getter
@Setter
private String message;
}

@ -0,0 +1,29 @@
package com.supervision.common.exception;
import com.supervision.common.enums.ResultStatusEnum;
import lombok.Getter;
/**
*
* @create 2019-07-14 10:33
* @author qmy
*/
@Getter
public class CustomException extends RuntimeException {
private int code;
private String message;
public CustomException(int code, String message) {
this.code = code;
this.message = message;
}
public CustomException(ResultStatusEnum resultStatusEnum) {
this.code = resultStatusEnum.getCode();
this.message = resultStatusEnum.getMessage();
}
public CustomException setEnum(ResultStatusEnum resultStatusEnum){
return new CustomException(resultStatusEnum.getCode(),resultStatusEnum.getMessage());
}
}

@ -0,0 +1,277 @@
package com.supervision.common.utils;
import com.supervision.common.constant.Constants;
import com.supervision.police.domain.ModelCase;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
@Slf4j
public class ExcelReader {
/**
* Excel xls
*/
public static List<List<String>> readExcelLow2007(InputStream is, String sheetName) throws IOException {
HSSFWorkbook wb = null;
try {
wb = new HSSFWorkbook(is);
} catch (IOException e) {
e.printStackTrace();
}
Sheet sheet;
if (StringUtils.isEmpty(sheetName)) {
sheet = wb.getSheetAt(0);
} else {
// 得到第一个sheet
sheet = wb.getSheet(sheetName);
}
// 得到Excel的行数
int totalRows = sheet.getPhysicalNumberOfRows();
// 得到Excel的列数
int totalCells = 0;
if (totalRows >= 1 && sheet.getRow(0) != null) {
totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
}
List<List<String>> dataLst = new ArrayList<>();
// 循环Excel的行
for (int r = 0; r < totalRows; r++) {
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
List<String> rowLst = new ArrayList<>();
// 循环Excel的列
for (int c = 0; c < totalCells; c++) {
Cell cell = row.getCell(c);
String cellValue = "";
if (null != cell) {
// 以下是判断数据的类
switch (cell.getCellType()) {
case NUMERIC: // 数字
cell.setCellType(CellType.STRING);
cellValue = String.valueOf(cell.getRichStringCellValue().getString());
break;
case STRING: // 字符串
cellValue = String.valueOf(cell.getStringCellValue());
break;
case BOOLEAN: // Boolean
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case FORMULA: // 公式
//判断嵌入单元格的图片
if (cell.getStringCellValue().contains("=DISPIMG(")) {
cellValue = "";
} else {
cellValue = String.valueOf(cell.getNumericCellValue());
}
break;
case BLANK: // 空值
cellValue = null;
break;
case ERROR: // 故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
}
rowLst.add(cellValue);
}
//如果出现空行,则结束
boolean isNull = false;
for (String str : rowLst) {
if (StringUtils.isNotEmpty(str)) {
isNull = false;
break;
}
isNull = true;
}
if (isNull) {
return dataLst;
}
// 保存第r行的第c列
dataLst.add(rowLst);
}
return dataLst;
}
/**
* Excel 2007+ xlsx
*/
public static List<List<String>> readExcel2007(InputStream is, String sheetName) throws IOException {
XSSFWorkbook wb = null;
try {
wb = new XSSFWorkbook(is);
} catch (IOException e) {
e.printStackTrace();
}
Sheet sheet;
if (StringUtils.isEmpty(sheetName)) {
sheet = wb.getSheetAt(0);
} else {
// 得到第一个sheet
sheet = wb.getSheet(sheetName);
}
// 得到Excel的行数
int totalRows = sheet.getPhysicalNumberOfRows();
// 得到Excel的列数
int totalCells = 0;
if (totalRows >= 1 && sheet.getRow(0) != null) {
totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
}
List<List<String>> dataLst = new ArrayList<>();
// 循环Excel的行
for (int r = 0; r < totalRows; r++) {
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
List<String> rowLst = new ArrayList<>();
// 循环Excel的列
for (int c = 0; c < totalCells; c++) {
Cell cell = row.getCell(c);
String cellValue = "";
if (null != cell) {
// 以下是判断数据的类
switch (cell.getCellType()) {
case NUMERIC: // 数字
// cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellType(CellType.STRING);
cellValue = String.valueOf(cell.getRichStringCellValue().getString());
break;
case STRING: // 字符串
cellValue = String.valueOf(cell.getStringCellValue());
break;
case BOOLEAN: // Boolean
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case FORMULA: // 公式
if (cell.getCellFormula().contains("=DISPIMG(")) {
cellValue = "";
} else {
cellValue = cell.getCellFormula();
}
break;
case BLANK: // 空值
cellValue = null;
break;
case ERROR: // 故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
}
rowLst.add(cellValue);
}
//如果出现空行,则结束
boolean isNull = false;
for (String str : rowLst) {
if (StringUtils.isNotEmpty(str)) {
isNull = false;
break;
}
isNull = true;
}
if (isNull) {
return dataLst;
}
// 保存第r行的第c列
dataLst.add(rowLst);
}
return dataLst;
}
/**
* excel
*
* @param is
* @return
* @throws IOException
*/
public static List<ModelCase> getCaseList(InputStream is, String fileSuffix, String sheetName) throws IOException {
List<List<String>> list = new ArrayList<>();
if ("xls".equals(fileSuffix)) {
list = ExcelReader.readExcelLow2007(is, sheetName);
} else if ("xlsx".equals(fileSuffix)) {
list = ExcelReader.readExcel2007(is, sheetName);
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//遍历数据到实体集合开始
List<ModelCase> listBean = new ArrayList<>();
for (int i = 1; i < list.size(); i++) { // i=1是因为第一行不要
ModelCase uBean = new ModelCase();
List<String> listStr = list.get(i);
for (int j = 0; j < listStr.size(); j++) {
//.replace((char)12288, ' ') 替换中文全角空格(全角空格无法用trim去掉)为半角空格
String str = listStr.get(j) == null ? null : listStr.get(j).replace((char)12288, ' ').trim();
switch (j) {
case 0:
//案件编号
uBean.setCaseNo(str);
break;
case 1:
//案件名称
uBean.setCaseName(str);
break;
case 2:
//案件类型
uBean.setCaseTypeName(str);
break;
case 3:
//案件状态
uBean.setCaseStatusName(str);
break;
case 4:
//作案方式
uBean.setCrimeModeName(str);
break;
case 5:
//案件描述
uBean.setCaseDetail(str);
break;
case 6:
try {
//立案时间
uBean.setRegisterTime(format.parse(str));
} catch (Exception e) {
uBean.setRegisterTime(null);
}
break;
case 7:
try {
//受理时间
uBean.setAcceptTime(format.parse(str));
} catch (Exception e) {
uBean.setAcceptTime(null);
}
break;
default:
}
}
listBean.add(uBean);
} //遍历数据到实体集合结束
return listBean;
}
}

@ -0,0 +1,28 @@
package com.supervision.common.utils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.supervision.common.constant.Constants.RESULT_LIST;
import static com.supervision.common.constant.Constants.TOTAL_COUNT;
public class IPages {
public static Map<String, Object> buildDataMap(IPage<?> iPage) {
Map<String, Object> dataMap = new HashMap<>();
dataMap.put(TOTAL_COUNT, iPage.getTotal());
dataMap.put(RESULT_LIST, iPage.getRecords());
return dataMap;
}
public static Map<String, Object> buildDataMap(List list, int total) {
Map<String, Object> dataMap = new HashMap();
dataMap.put(TOTAL_COUNT, total);
dataMap.put(RESULT_LIST, list);
return dataMap;
}
}

@ -0,0 +1,88 @@
package com.supervision.common.utils;
import java.util.ArrayList;
import java.util.List;
/**
* @author qmy
* @description
* @createTime 2022/4/22
*/
public class ListUtils {
/**
* list
* list
* @param pageSize
* @param pageIndex
* @param list
* @param <T>
* @return
*/
public static<T> List<T> Pager(int pageSize, int pageIndex, List<T> list){
//使用list 中的sublist方法分页
List<T> dataList = new ArrayList<>();
// 每页显示多少条记录
int currentPage; //当前第几页数据
// 一共多少条记录
int totalRecord = list.size();
// 一共多少页
int totalPage = totalRecord % pageSize;
if (totalPage > 0) {
totalPage = totalRecord / pageSize + 1;
} else {
totalPage = totalRecord / pageSize;
}
System.out.println("总页数:" + totalPage);
// 当前第几页数据
currentPage = totalPage < pageIndex ? totalPage : pageIndex;
// 起始索引
int fromIndex = pageSize * (currentPage - 1);
fromIndex = fromIndex > 0 ? fromIndex : 0;
// 结束索引
int toIndex = pageSize * currentPage > totalRecord ? totalRecord : pageSize * currentPage;
try{
dataList = list.subList(fromIndex, toIndex);
}catch(IndexOutOfBoundsException e){
e.printStackTrace();
}
return dataList;
}
/**
* @description
* @method getCurrentPage
* @param pageSize
* @param pageIndex
* @param list
* @return int
*/
public static<T> int getCurrentPage(int pageSize, int pageIndex, List<T> list){
//使用list 中的sublist方法分页
List<T> dataList = new ArrayList<>();
// 每页显示多少条记录
int currentPage; //当前第几页数据
// 一共多少条记录
int totalRecord = list.size();
// 一共多少页
int totalPage = totalRecord % pageSize;
if (totalPage > 0) {
totalPage = totalRecord / pageSize + 1;
} else {
totalPage = totalRecord / pageSize;
}
System.out.println("总页数:" + totalPage);
// 当前第几页数据
currentPage = totalPage < pageIndex ? totalPage : pageIndex;
return currentPage;
}
}

@ -0,0 +1,619 @@
package com.supervision.common.utils;
import java.util.*;
/**
*
*
* @author qmy
*/
public class StringUtils extends org.apache.commons.lang3.StringUtils {
/** 空字符串 */
private static final String NULLSTR = "";
/** 下划线 */
private static final char SEPARATOR = '_';
/** 星号 */
private static final String START = "*";
/**
*
*
* @param value defaultValue value
* @return value
*/
public static <T> T nvl(T value, T defaultValue)
{
return value != null ? value : defaultValue;
}
/**
* * Collection ListSetQueue
*
* @param coll Collection
* @return true false
*/
public static boolean isEmpty(Collection<?> coll)
{
return isNull(coll) || coll.isEmpty();
}
/**
* * CollectionListSetQueue
*
* @param coll Collection
* @return true false
*/
public static boolean isNotEmpty(Collection<?> coll)
{
return !isEmpty(coll);
}
/**
* *
*
* @param objects
** @return true false
*/
public static boolean isEmpty(Object[] objects)
{
return isNull(objects) || (objects.length == 0);
}
/**
* *
*
* @param objects
* @return true false
*/
public static boolean isNotEmpty(Object[] objects)
{
return !isEmpty(objects);
}
/**
* * Map
*
* @param map Map
* @return true false
*/
public static boolean isEmpty(Map<?, ?> map)
{
return isNull(map) || map.isEmpty();
}
/**
* * Map
*
* @param map Map
* @return true false
*/
public static boolean isNotEmpty(Map<?, ?> map)
{
return !isEmpty(map);
}
/**
* *
*
* @param str String
* @return true false
*/
public static boolean isEmpty(String str)
{
return isNull(str) || NULLSTR.equals(str.trim());
}
/**
* *
*
* @param str String
* @return true false
*/
public static boolean isNotEmpty(String str)
{
return !isEmpty(str);
}
/**
* *
*
* @param object Object
* @return true false
*/
public static boolean isNull(Object object)
{
return object == null;
}
/**
* *
*
* @param object Object
* @return true false
*/
public static boolean isNotNull(Object object)
{
return !isNull(object);
}
/**
* * Java
*
* @param object
* @return true false
*/
public static boolean isArray(Object object)
{
return isNotNull(object) && object.getClass().isArray();
}
/**
*
*/
public static String trim(String str)
{
return (str == null ? "" : str.trim());
}
/**
*
*
* @param str
* @param start
* @return
*/
public static String substring(final String str, int start)
{
if (str == null)
{
return NULLSTR;
}
if (start < 0)
{
start = str.length() + start;
}
if (start < 0)
{
start = 0;
}
if (start > str.length())
{
return NULLSTR;
}
return str.substring(start);
}
/**
*
*
* @param str
* @param start
* @param end
* @return
*/
public static String substring(final String str, int start, int end)
{
if (str == null)
{
return NULLSTR;
}
if (end < 0)
{
end = str.length() + end;
}
if (start < 0)
{
start = str.length() + start;
}
if (end > str.length())
{
end = str.length();
}
if (start > end)
{
return NULLSTR;
}
if (start < 0)
{
start = 0;
}
if (end < 0)
{
end = 0;
}
return str.substring(start, end);
}
/**
* 线
*/
public static String toUnderScoreCase(String str)
{
if (str == null)
{
return null;
}
StringBuilder sb = new StringBuilder();
// 前置字符是否大写
boolean preCharIsUpperCase = true;
// 当前字符是否大写
boolean curreCharIsUpperCase = true;
// 下一字符是否大写
boolean nexteCharIsUpperCase = true;
for (int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);
if (i > 0)
{
preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
}
else
{
preCharIsUpperCase = false;
}
curreCharIsUpperCase = Character.isUpperCase(c);
if (i < (str.length() - 1))
{
nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
}
if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase)
{
sb.append(SEPARATOR);
}
else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase)
{
sb.append(SEPARATOR);
}
sb.append(Character.toLowerCase(c));
}
return sb.toString();
}
/**
*
*
* @param str
* @param strs
* @return true
*/
public static boolean inStringIgnoreCase(String str, String... strs)
{
if (str != null && strs != null)
{
for (String s : strs)
{
if (str.equalsIgnoreCase(trim(s)))
{
return true;
}
}
}
return false;
}
/**
* 线线 HELLO_WORLD->HelloWorld
*
* @param name 线
* @return
*/
public static String convertToCamelCase(String name)
{
StringBuilder result = new StringBuilder();
// 快速检查
if (name == null || name.isEmpty())
{
// 没必要转换
return "";
}
else if (!name.contains("_"))
{
// 不含下划线,仅将首字母大写
return name.substring(0, 1).toUpperCase() + name.substring(1);
}
// 用下划线将原始字符串分割
String[] camels = name.split("_");
for (String camel : camels)
{
// 跳过原始字符串中开头、结尾的下换线或双重下划线
if (camel.isEmpty())
{
continue;
}
// 首字母大写
result.append(camel.substring(0, 1).toUpperCase());
result.append(camel.substring(1).toLowerCase());
}
return result.toString();
}
/**
* user_name->userName
*/
public static String toCamelCase(String s)
{
if (s == null)
{
return null;
}
s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if (c == SEPARATOR)
{
upperCase = true;
}
else if (upperCase)
{
sb.append(Character.toUpperCase(c));
upperCase = false;
}
else
{
sb.append(c);
}
}
return sb.toString();
}
/**
*
*
* @param str
* @param strs
* @return
*/
public static boolean matches(String str, List<String> strs)
{
if (isEmpty(str) || isEmpty(strs))
{
return false;
}
for (String testStr : strs)
{
if (matches(str, testStr))
{
return true;
}
}
return false;
}
/**
*
*
* @param str
* @param strs
* @return
*/
public static boolean matches(String str, String... strs)
{
if (isEmpty(str) || isEmpty(strs))
{
return false;
}
for (String testStr : strs)
{
if (matches(str, testStr))
{
return true;
}
}
return false;
}
/**
*
*
* @param str
* @param pattern
* @return
*/
public static boolean matches(String str, String pattern)
{
if (isEmpty(pattern) || isEmpty(str))
{
return false;
}
pattern = pattern.replaceAll("\\s*", ""); // 替换空格
int beginOffset = 0; // pattern截取开始位置
int formerStarOffset = -1; // 前星号的偏移位置
int latterStarOffset = -1; // 后星号的偏移位置
String remainingURI = str;
String prefixPattern = "";
String suffixPattern = "";
boolean result = false;
do
{
formerStarOffset = indexOf(pattern, START, beginOffset);
prefixPattern = substring(pattern, beginOffset, formerStarOffset > -1 ? formerStarOffset : pattern.length());
// 匹配前缀Pattern
result = remainingURI.contains(prefixPattern);
// 已经没有星号,直接返回
if (formerStarOffset == -1)
{
return result;
}
// 匹配失败,直接返回
if (!result)
return false;
if (!isEmpty(prefixPattern))
{
remainingURI = substringAfter(str, prefixPattern);
}
// 匹配后缀Pattern
latterStarOffset = indexOf(pattern, START, formerStarOffset + 1);
suffixPattern = substring(pattern, formerStarOffset + 1, latterStarOffset > -1 ? latterStarOffset : pattern.length());
result = remainingURI.contains(suffixPattern);
// 匹配失败,直接返回
if (!result)
return false;
if (!isEmpty(suffixPattern))
{
remainingURI = substringAfter(str, suffixPattern);
}
// 移动指针
beginOffset = latterStarOffset + 1;
}
while (!isEmpty(suffixPattern) && !isEmpty(remainingURI));
return true;
}
/**
* ,
*/
public static String getRandomCode() {
String sources = "0123456789"; // 加上一些字母就可以生成pc站的验证码了
Random rand = new Random();
StringBuffer flag = new StringBuffer();
for (int j = 0; j < 6; j++)
{
flag.append(sources.charAt(rand.nextInt(9)) + "");
}
return flag.toString();
}
@SuppressWarnings("unchecked")
public static <T> T cast(Object obj)
{
return (T) obj;
}
/**
* strsstr null
* @param strs
* @param str
* @return
*/
public static boolean isContains(String strs, String str) {
if (str != null && str!="") {
if (strs == null) {
return false;
} else {
return strs.contains(str);
}
} else {
return true;
}
}
/**
* _ , _, _
* @param str
* @return
*/
public static String _toUpper(String str) {
if (str == null) {
return "";
}
if (str.endsWith("_")) {
str = str.substring(0, str.length() - 1);
}
while (str.contains("_")) {
int i = str.indexOf("_");
System.out.println(i);
String lower = str.substring(i + 1, i + 2);
String upper = lower.toUpperCase();
str = str.replace("_" + lower, upper);
}
return str;
}
/**
*
*/
private static char[] cnArr = new char[]{'一', '二', '三', '四', '五', '六', '七', '八', '九'};
/**
*
*
* @param arabicNum
* @return
*/
public static String arabicNumToChineseNum(int arabicNum) {
String si = String.valueOf(arabicNum);
String sd = "";
if (si.length() == 1) {
if (arabicNum == 0) {
return sd;
}
sd += cnArr[arabicNum - 1];
return sd;
} else if (si.length() == 2) {
if (si.substring(0, 1).equals("1")) {
sd += "十";
if (arabicNum % 10 == 0) {
return sd;
}
} else {
sd += (cnArr[arabicNum / 10 - 1] + "十");
}
sd += arabicNumToChineseNum(arabicNum % 10);
} else if (si.length() == 3) {
sd += (cnArr[arabicNum / 100 - 1] + "百");
if (String.valueOf(arabicNum % 100).length() < 2) {
if (arabicNum % 100 == 0) {
return sd;
}
sd += "零";
}
sd += arabicNumToChineseNum(arabicNum % 100);
} else if (si.length() == 4) {
sd += (cnArr[arabicNum / 1000 - 1] + "千");
if (String.valueOf(arabicNum % 1000).length() < 3) {
if (arabicNum % 1000 == 0) {
return sd;
}
sd += "零";
}
sd += arabicNumToChineseNum(arabicNum % 1000);
} else if (si.length() == 5) {
sd += (cnArr[arabicNum / 10000 - 1] + "万");
if (String.valueOf(arabicNum % 10000).length() < 4) {
if (arabicNum % 10000 == 0) {
return sd;
}
sd += "零";
}
sd += arabicNumToChineseNum(arabicNum % 10000);
}
return sd;
}
public static String getUUID() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
}

@ -0,0 +1,54 @@
//package com.supervision.config;
//
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.BeansException;
//import org.springframework.beans.factory.config.BeanPostProcessor;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.util.ReflectionUtils;
//import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
//import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
//import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
//
//import java.lang.reflect.Field;
//import java.util.List;
//import java.util.stream.Collectors;
//
//@Slf4j
//@Configuration
//public class BeanPostProcessorConfig {
//
// @Bean
// public BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
// return new BeanPostProcessor() {
// @Override
// public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
// customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
// }
// return bean;
// }
//
// private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
// List<T> copy = mappings.stream()
// .filter(mapping -> mapping.getPatternParser() == null)
// .collect(Collectors.toList());
// mappings.clear();
// mappings.addAll(copy);
// }
//
// @SuppressWarnings("unchecked")
// private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
// try {
// Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
// field.setAccessible(true);
// return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
// } catch (IllegalArgumentException | IllegalAccessException e) {
// throw new IllegalStateException(e);
// }
// }
// };
// }
//
//}
//

@ -0,0 +1,33 @@
package com.supervision.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
*
*
* @author qmy
* @version 1.0.0 2020/10/21 15:17
* @since JDK1.8
*/
@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
// 设置允许跨域的路径
registry.addMapping("/**")
// 设置允许跨域请求的域名
.allowedOriginPatterns("*")
// 是否允许整数 不再默认开启
.allowCredentials(true)
// 设置允许的方法
.allowedMethods("*")
// 跨域允许时间
.maxAge(3600);
}
}

@ -0,0 +1,41 @@
package com.supervision.config;
import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
/**
* Endpoint URL
* Access Key Access keyID
* Secret Key Secret key
*
* @author qmy
* @since 1.0.0
*/
@Configuration
public class MinioConfig {
@Value("${minio.endpoint}")
private String endpoint;
@Value("${minio.accessKey}")
private String accessKey;
@Value("${minio.secretKey}")
private String secretKey;
@Bean
@Primary
public MinioClient minioClient() {
// Create a minioClient with the MinIO server playground, its access key and secret key.
return MinioClient.builder()
.endpoint(endpoint)
.credentials(accessKey, secretKey)
.build();
}
}

@ -0,0 +1,26 @@
package com.supervision.config;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import java.util.Date;
/**
* @author Ray
*/
public class MyMetaObjectHandler implements MetaObjectHandler {
public MyMetaObjectHandler() {
}
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime", new Date(), metaObject);
this.setFieldValByName("updateTime", new Date(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime", new Date(), metaObject);
}
}

@ -0,0 +1,43 @@
package com.supervision.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* MybatisPlus
*
* @author qmy
* @version 1.0.0 2020/10/22 9:47
* @since JDK1.8
*/
@Configuration
public class MybatisPlusConfig {
@Bean
public MyMetaObjectHandler myMetaObjectHandler() {
return new MyMetaObjectHandler();
}
/**
*
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(this.paginationInterceptor());
return interceptor;
}
private PaginationInnerInterceptor paginationInterceptor() {
PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor();
paginationInterceptor.setOverflow(false);
/**
* ! .
*/
paginationInterceptor.setDbType(DbType.MYSQL);
return paginationInterceptor;
}
}

@ -0,0 +1,32 @@
package com.supervision.config;
import org.neo4j.driver.AuthTokens;
import org.neo4j.driver.Config;
import org.neo4j.driver.Driver;
import org.neo4j.driver.GraphDatabase;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Neo4jConfig {
@Value("${spring.neo4j.uri}")
private String URI;
@Value("${spring.neo4j.authentication.username}")
private String USER;
@Value("${spring.neo4j.authentication.password}")
private String PASSWORD;
@Bean
public Driver neo4jDriver() {
// 这里可以添加额外的配置,比如加密、连接池设置等
Config config = Config.builder()
// 示例:关闭加密(注意:在生产环境中应该启用加密)
.withoutEncryption()
// 你可以在这里添加更多的配置选项
.build();
return GraphDatabase.driver(URI, AuthTokens.basic(USER, PASSWORD), config);
}
}

@ -0,0 +1,214 @@
package com.supervision.minio.client;
import cn.hutool.core.io.IoUtil;
import com.supervision.minio.exception.SysObsException;
import io.minio.*;
import io.minio.errors.MinioException;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* minio Template
*
* @author qmy
* @version 1.0.0 2021/6/22 14:42
* @since JDK1.8
*/
@Component
@Slf4j
public class MinioTemplate {
@Autowired
private MinioClient minioClient;
/**
*
*
* @param bucketName
* @param objectName
* @param userMetadata metaData
* @param stream
* @param objectSize
* @param contentType contentType
* @return void
* @author qmy
* @version 1.0.0 2021/6/30 9:11
* @since JDK1.8
*/
public void putObject(String bucketName, String objectName, Map<String, String> userMetadata, InputStream stream, long objectSize, String contentType) {
try {
minioClient.putObject(PutObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.userMetadata(userMetadata)
.contentType(contentType == null ? "application/octet-stream" : contentType)
.stream(stream, objectSize, -1)
.build());
} catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
e.printStackTrace();
throw new SysObsException(e.getMessage());
}
}
/**
*
*
* @param bucketName
* @param objectName
* @param response response
* @return void
* @author qmy
* @version 1.0.0 2021/6/30 9:11
* @since JDK1.8
*/
public void getObject(String bucketName, String objectName, String fileType, HttpServletResponse response) {
try {
InputStream inputStream = minioClient.getObject(
GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
StatObjectResponse statObjectResponse = minioClient.statObject(
StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
String fileName = objectName + "." + fileType;
response.setHeader("Content-Disposition", "inline;filename=" + fileName);
response.setCharacterEncoding("UTF-8");
response.setContentLengthLong(statObjectResponse.size());
response.setContentType(statObjectResponse.contentType());
IoUtil.copy(inputStream, response.getOutputStream());
inputStream.close();
} catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
e.printStackTrace();
throw new SysObsException(e.getMessage());
}
}
/**
*
*
* @param bucketName
* @param objectName
* @return void
* @author qmy
* @version 1.0.0 2021/6/30 9:11
* @since JDK1.8
*/
public GetObjectResponse getInputStreamObject(String bucketName, String objectName) {
GetObjectResponse inputStream;
try {
inputStream = minioClient.getObject(
GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
return inputStream;
} catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
e.printStackTrace();
throw new SysObsException(e.getMessage());
}
}
/**
*
*
* @param bucketName
* @param objectName
* @return void
* @author qmy
* @version 1.0.0 2021/6/30 9:08
* @since JDK1.8
*/
public void removeObject(String bucketName, String objectName) {
try {
minioClient.removeObject(
RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
} catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
e.printStackTrace();
throw new SysObsException(e.getMessage());
}
}
/**
*
*
* @param bucketName
* @param objectNames
* @return void
* @author qmy
* @version 1.0.0 2021/6/30 9:08
* @since JDK1.8
*/
public List<Map<String, Object>> removeObject(String bucketName, Set<String> objectNames) {
try {
List<DeleteObject> objects = new LinkedList<>();
for (String objectName : objectNames) {
objects.add(new DeleteObject(objectName));
}
Iterable<Result<DeleteError>> results = minioClient.removeObjects(
RemoveObjectsArgs.builder().bucket(bucketName).objects(objects).build());
List<Map<String, Object>> errorInfo = new ArrayList<>();
for (Result<DeleteError> result : results) {
DeleteError error = result.get();
errorInfo.add(new HashMap<String, Object>(2) {{
put("objectName", error.objectName());
put("message", error.message());
}});
}
return errorInfo;
} catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
e.printStackTrace();
throw new SysObsException(e.getMessage());
}
}
/**
*
*
* @param bucketName
* @param objectName
* @return io.minio.StatObjectResponse
* @author qmy
* @version 1.0.0 2021/6/30 9:07
* @since JDK1.8
*/
public StatObjectResponse statObject(String bucketName, String objectName) {
try {
return minioClient.statObject(
StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
} catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
e.printStackTrace();
throw new SysObsException(e.getMessage());
}
}
/**
*
*
* @param bucketName
* @param objectName
* @return boolean
* @author qmy
* @version 1.0.0 2021/6/30 9:15
* @since JDK1.8
*/
public boolean objectExists(String bucketName, String objectName) {
try {
return minioClient.statObject(
StatObjectArgs.builder().bucket(bucketName).object(objectName).build()) != null;
} catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
return false;
}
}
}

@ -0,0 +1,34 @@
package com.supervision.minio.controller;
import com.supervision.common.domain.R;
import com.supervision.minio.service.MinioService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@RestController
@RequestMapping("minio")
public class MinioController {
@Autowired
private MinioService minioService;
@PostMapping("/uploadFile")
public String uploadFile(@RequestPart("file") MultipartFile file) throws IOException {
return minioService.uploadFile(file);
}
@GetMapping("/downloadFile")
public void downloadFile(@RequestParam String fileId, HttpServletResponse response) {
minioService.downloadFile(fileId, response);
}
@PostMapping("/delFile")
public R<?> delFile(@RequestParam String fileId) {
return minioService.delFile(fileId);
}
}

@ -0,0 +1,49 @@
package com.supervision.minio.domain;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
/**
* (MinioFile)
*
* @author qmy
* @since 2024-07-08 14:45:00
*/
@Data
@TableName("minio_file")
public class MinioFile implements Serializable {
@TableId
private String id;
/**
*
*/
private String filename;
/**
*
*/
private Integer size;
/**
*
*/
private Date uploadDate;
/**
*
*/
private String fileType;
/**
*
*/
private String dataStatus;
}

@ -0,0 +1,21 @@
package com.supervision.minio.exception;
/**
* @author qmy
* @version 1.0.0 2021/6/22 15:18
* @since JDK1.8
*/
public class SysObsException extends RuntimeException {
private String message;
public SysObsException(String message) {
this.message = message;
}
@Override
public String getMessage() {
return this.message;
}
}

@ -0,0 +1,15 @@
package com.supervision.minio.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.supervision.minio.domain.MinioFile;
/**
* (MinioFile)访
*
* @author qmy
* @since 2024-07-08 14:49:58
*/
public interface MinioFileMapper extends BaseMapper<MinioFile> {
}

@ -0,0 +1,17 @@
package com.supervision.minio.service;
import com.supervision.common.domain.R;
import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
public interface MinioService {
String uploadFile(MultipartFile file) throws IOException;
void downloadFile(String fileId, HttpServletResponse response);
R<?> delFile(String fileId);
}

@ -0,0 +1,67 @@
package com.supervision.minio.service.impl;
import com.supervision.common.domain.R;
import com.supervision.common.utils.StringUtils;
import com.supervision.minio.client.MinioTemplate;
import com.supervision.minio.domain.MinioFile;
import com.supervision.minio.mapper.MinioFileMapper;
import com.supervision.minio.service.MinioService;
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;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;
@Service
public class MinioServiceImpl implements MinioService {
@Autowired
private MinioTemplate minioTemplate;
@Value("${minio.bucketName}")
private String bucketName;
@Autowired
private MinioFileMapper minioFileMapper;
@Override
public String uploadFile(MultipartFile file) throws IOException {
String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".") + 1);
InputStream in = file.getInputStream();
MinioFile minioFile = new MinioFile();
minioFile.setFilename(file.getOriginalFilename());
minioFile.setUploadDate(new Date());
minioFile.setFileType(suffix);
minioFile.setSize(in.available());
int i = minioFileMapper.insert(minioFile);
if (i > 0) {
minioTemplate.putObject(bucketName, minioFile.getId(), null, in, in.available(), null);
return minioFile.getId();
} else {
return null;
}
}
@Override
public void downloadFile(String fileId, HttpServletResponse response){
MinioFile minioFile = minioFileMapper.selectById(fileId);
String fileType = minioFile.getFileType();
minioTemplate.getObject(bucketName, fileId, fileType, response);
}
@Override
public R<?> delFile(String fileId) {
MinioFile minioFile = minioFileMapper.selectById(fileId);
minioFile.setDataStatus(StringUtils.getUUID());
minioFileMapper.updateById(minioFile);
minioTemplate.removeObject(bucketName, fileId);
return R.ok();
}
}

@ -0,0 +1,83 @@
package com.supervision.neo4j.controller;
import com.supervision.common.domain.R;
import com.supervision.neo4j.domain.CaseNode;
import com.supervision.neo4j.domain.Rel;
import com.supervision.neo4j.service.Neo4jService;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author qmy
* @since 2023-10-26
*/
@RestController
@RequestMapping("/neo4j")
public class Neo4jController {
@Autowired
private Neo4jService neo4jService;
@PostMapping("/save")
public R<?> save(@RequestBody CaseNode caseNode) {
return neo4jService.save(caseNode);
}
@PostMapping("/delNode")
public R<?> delNode(Long id) {
return neo4jService.delNode(id);
}
@PostMapping("/findById")
public R<?> findById(@RequestParam Long id) {
CaseNode node = neo4jService.findById(id);
return R.ok(node);
}
@PostMapping("/findByName")
public R<?> findByName(@RequestParam String caseId,
@RequestParam(required = false, defaultValue = "") String recordsId,
@RequestParam(required = false, defaultValue = "") String nodeType,
@RequestParam String name,
@RequestParam(required = false, defaultValue = "1") String picType) {
List<CaseNode> list = neo4jService.findByName(caseId, recordsId, nodeType, name, picType);
return R.ok(list);
}
@PostMapping("/findOneByName")
public R<?> findOneByName(@RequestParam String caseId,
@RequestParam(required = false, defaultValue = "") String recordsId,
@RequestParam(required = false, defaultValue = "") String nodeType,
@RequestParam String name,
@RequestParam(required = false, defaultValue = "1") String picType) {
CaseNode node = neo4jService.findOneByName(caseId, recordsId, nodeType, name, picType);
return R.ok(node);
}
@PostMapping("/findRelation")
public Rel findRelation(@RequestBody Rel rel) {
return neo4jService.findRelation(rel);
}
@PostMapping("/saveRelation")
public R<?> saveRelation(@RequestBody Rel rel) {
return neo4jService.saveRelation(rel);
}
/*************************************************************************************/
@GetMapping("/getNode")
public R<?> getNode(@RequestParam String picType, @RequestParam String caseId) {
return neo4jService.getNode(picType, caseId);
}
@GetMapping("/test")
public R<?> test() {
return neo4jService.test();
}
}

@ -0,0 +1,58 @@
package com.supervision.neo4j.domain;
import lombok.Data;
import org.springframework.data.neo4j.core.schema.*;
/**
* @author qmy
* @since 2023-10-26
*/
@Data
public class CaseNode {
@Id
@GeneratedValue
private Long id;
private String name;
private String nodeType;
private String recordId;
private String recordsId;
private String caseId;
/**
* 0 1
*/
private String picType;
public CaseNode() {
}
public CaseNode(Long id, String name) {
this.id = id;
this.name = name;
}
public CaseNode(String name, String nodeType, String recordId, String recordsId, String caseId, String picType) {
this.name = name;
this.nodeType = nodeType;
this.recordId = recordId;
this.recordsId = recordsId;
this.caseId = caseId;
this.picType = picType;
}
public CaseNode(Long id, String name, String nodeType, String recordId, String caseId, String picType) {
this.id = id;
this.name = name;
this.nodeType = nodeType;
this.recordId = recordId;
this.caseId = caseId;
this.picType = picType;
}
}

@ -0,0 +1,36 @@
package com.supervision.neo4j.domain;
import lombok.Data;
@Data
public class Rel {
private Long id;
private String source;
private Long sourceId;
private String name;
private String target;
private Long targetId;
public Rel() {
}
public Rel(Long sourceId, String name, Long targetId) {
this.sourceId = sourceId;
this.name = name;
this.targetId = targetId;
}
public Rel(Long id, String source, Long sourceId, String name, String target, Long targetId) {
this.id = id;
this.source = source;
this.sourceId = sourceId;
this.name = name;
this.target = target;
this.targetId = targetId;
}
}

@ -0,0 +1,29 @@
package com.supervision.neo4j.dto;
import lombok.Data;
@Data
public class ResultDTO {
private String startId;
private String endId;
private String relId;
private String recordId;
private String recordsId;
public ResultDTO() {
}
public ResultDTO(String startId, String endId, String relId, String recordId, String recordsId) {
this.startId = startId;
this.endId = endId;
this.relId = relId;
this.recordId = recordId;
this.recordsId = recordsId;
}
}

@ -0,0 +1,40 @@
package com.supervision.neo4j.repository;
import com.supervision.neo4j.domain.CaseNode;
import org.springframework.data.neo4j.core.schema.Relationship;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.data.neo4j.repository.query.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
* @author qmy
* @since 2023-10-26
*/
//@Repository
public interface CaseNodeRepository extends Neo4jRepository<CaseNode,Long> {
@Query("MATCH p=(n:CaseNode) RETURN p")
List<CaseNode> selectAll();
@Query("MATCH(p:Person{name:$name}) return p")
CaseNode findByName(@Param("name") String name);
@Query("match (a)-[r:`:#{literal(#relation)}`]-(b) where a.name = $fromNodeName and b.name = $toNodeName return r")
Relationship queryRelationShip(@Param("fromNodeName") String fromNodeName, @Param("toNodeName") String toNodeName, @Param("relation") String relation);
/**
* (fromNodeId -> relation -> toNodeId)
* @param fromNodeId id
* @param toNodeId id
* @param relation
*/
@Query("match (a),(b) where id(a)= $fromNodeId and id(b)= $toNodeId merge (a)-[:`:#{literal(#relation)}`]->(b)")
void createRelationShip(@Param("fromNodeId") Long fromNodeId, @Param("toNodeId") Long toNodeId, @Param("relation") String relation);
@Query("match (a),(b) where a.name = $fromNodeName and b.name= $toNodeName merge (a)-[:`:#{literal(#relation)}`]->(b)")
void createRelationShip(@Param("fromNodeName") String fromNodeName, @Param("toNodeName") String toNodeName, @Param("relation") String relation);
}

@ -0,0 +1,31 @@
package com.supervision.neo4j.service;
import com.supervision.common.domain.R;
import com.supervision.neo4j.domain.CaseNode;
import com.supervision.neo4j.domain.Rel;
import java.util.List;
/**
* @author qmy
* @since 2023-10-26
*/
public interface Neo4jService {
R<?> save(CaseNode caseNode);
R<?> delNode(Long id);
CaseNode findById(Long id);
List<CaseNode> findByName(String caseId, String recordId, String nodeType, String name, String picType);
CaseNode findOneByName(String caseId, String recordId, String nodeType, String name, String picType);
Rel findRelation(Rel rel);
R<?> saveRelation(Rel rel);
R<?> getNode(String picType, String caseId);
R<?> test();
}

@ -0,0 +1,283 @@
package com.supervision.neo4j.service.impl;
import com.supervision.common.domain.R;
import com.supervision.common.utils.StringUtils;
import com.supervision.neo4j.domain.CaseNode;
import com.supervision.neo4j.domain.Rel;
import com.supervision.neo4j.service.Neo4jService;
import com.supervision.neo4j.utils.Neo4jUtils;
import org.neo4j.driver.*;
import org.neo4j.driver.Record;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author qmy
* @since 2023-10-26
*/
@Service
public class Neo4jServiceImpl implements Neo4jService {
private final Driver driver;
@Autowired
private Neo4jServiceImpl(Driver driver) {
this.driver = driver;
}
@Override
public R<?> save(CaseNode caseNode) {
if (StringUtils.isEmpty(caseNode.getName()) || StringUtils.isEmpty(caseNode.getNodeType())) {
return R.fail("未传节点名称或节点类型或图谱类型!");
}
List<CaseNode> byName = findByName(caseNode.getCaseId(), caseNode.getRecordsId(), caseNode.getNodeType(), caseNode.getName(), caseNode.getPicType());
if (byName != null && !byName.isEmpty()) {
return R.fail("名称已存在");
}
CaseNode res = null;
try {
Session session = driver.session();
StringBuffer cql = new StringBuffer();
Map<String, Object> params = new HashMap<>();
cql.append("CREATE (n:").append(caseNode.getNodeType()).append("{name:$name");
params.put("name", caseNode.getName());
if (StringUtils.isNotEmpty(caseNode.getRecordId())) {
cql.append(", recordId:$recordId");
params.put("recordId", caseNode.getRecordId());
}
if (StringUtils.isNotEmpty(caseNode.getRecordsId())) {
cql.append(", recordsId:$recordsId");
params.put("recordsId", caseNode.getRecordsId());
}
if (StringUtils.isNotEmpty(caseNode.getCaseId())) {
cql.append(", caseId:$caseId");
params.put("caseId", caseNode.getCaseId());
}
if (StringUtils.isNotEmpty(caseNode.getPicType())) {
cql.append(", picType:$picType");
params.put("picType", caseNode.getPicType());
}
cql.append("})").append(Neo4jUtils.NODE_RETURN);
Result run = session.run(cql.toString(), params);
res = Neo4jUtils.getOneNode(run);
} catch (Exception e) {
e.printStackTrace();
}
return R.ok(res);
}
@Override
public R<?> delNode(Long id) {
try {
Session session = driver.session();
StringBuffer cql = new StringBuffer();
cql.append("MATCH (n) where id(n) = ").append(id).append(" DELETE n");
Result run = session.run(cql.toString());
} catch (Exception e) {
e.printStackTrace();
}
return R.ok();
}
@Override
public CaseNode findById(Long id) {
CaseNode node = null;
try {
Session session = driver.session();
StringBuffer cql = new StringBuffer();
cql.append("MATCH (n) where id(n) = ").append(id).append(Neo4jUtils.NODE_RETURN);
Result run = session.run(cql.toString());
node = Neo4jUtils.getOneNode(run);
} catch (Exception e) {
e.printStackTrace();
}
return node;
}
@Override
public List<CaseNode> findByName(String caseId, String recordsId, String nodeType, String name, String picType) {
List<CaseNode> list = new ArrayList<>();
try {
Session session = driver.session();
StringBuffer cql = new StringBuffer();
cql.append("MATCH (n");
if (StringUtils.isNotEmpty(nodeType)) {
cql.append(":");
cql.append(nodeType);
}
cql.append(") where 1 = 1");
if (StringUtils.isNotEmpty(caseId)) {
cql.append(" and n.caseId = ");
cql.append(caseId);
}
if (StringUtils.isNotEmpty(recordsId)) {
cql.append(" and n.recordsId = ");
cql.append(recordsId);
}
if (StringUtils.isNotEmpty(name)) {
cql.append(" and n.name = '");
cql.append(name);
cql.append("'");
}
if (StringUtils.isNotEmpty(picType)) {
cql.append(" and n.picType = ");
cql.append(picType);
}
cql.append(Neo4jUtils.NODE_RETURN);
Result run = session.run(cql.toString());
list = Neo4jUtils.getNodeList(run);
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
@Override
public CaseNode findOneByName(String caseId, String recordsId, String nodeType, String name, String picType) {
CaseNode node = null;
try {
Session session = driver.session();
StringBuffer cql = new StringBuffer();
Map<String, Object> params = new HashMap<>();
cql.append("MATCH (n");
if (StringUtils.isNotEmpty(nodeType)) {
cql.append(":");
cql.append(nodeType);
}
cql.append(") where 1 = 1");
if (StringUtils.isNotEmpty(caseId)) {
cql.append(" and n.caseId = $caseId");
params.put("caseId", caseId);
}
if (StringUtils.isNotEmpty(recordsId)) {
cql.append(" and n.recordsId = $recordsId");
params.put("recordsId", recordsId);
}
if (StringUtils.isNotEmpty(name)) {
cql.append(" and n.name = $name");
params.put("name", name);
}
if (StringUtils.isNotEmpty(picType)) {
cql.append(" and n.picType = $picType");
params.put("picType", picType);
}
cql.append(Neo4jUtils.NODE_RETURN);
Result run = session.run(cql.toString(), params);
node = Neo4jUtils.getOneNode(run);
} catch (Exception e) {
e.printStackTrace();
}
return node;
}
@Override
public Rel findRelation(Rel rel) {
try {
Session session = driver.session();
StringBuffer cql = new StringBuffer();
Map<String, Object> params = new HashMap<>();
cql.append("MATCH (a)-[rel:").append(rel.getName()).append("]->(b) where id(a) = $sourceId and id(b) = $targetId")
.append(Neo4jUtils.REL_RETURN);
params.put("sourceId", rel.getSourceId());
params.put("targetId", rel.getTargetId());
Result run = session.run(cql.toString(), params);
rel = Neo4jUtils.getOneRel(run);
} catch (Exception e) {
e.printStackTrace();
}
if (rel != null && rel.getId() != null) {
return rel;
} else {
return null;
}
}
@Override
public R<?> saveRelation(Rel rel) {
Rel res = null;
try {
Session session = driver.session();
StringBuffer cql = new StringBuffer();
Map<String, Object> params = new HashMap<>();
cql.append("MATCH (a), (b) where id(a) = $sourceId and id(b) = $targetId CREATE(a)-[rel:").append(rel.getName())
.append("]->(b) ").append(Neo4jUtils.REL_RETURN);
params.put("sourceId", rel.getSourceId());
params.put("targetId", rel.getTargetId());
Result run = session.run(cql.toString(), params);
rel = Neo4jUtils.getOneRel(run);
} catch (Exception e) {
e.printStackTrace();
}
if (rel != null) {
return R.ok(rel);
} else {
return R.fail("保存失败");
}
}
@Override
public R<?> getNode(String picType, String caseId) {
Map<String, Object> map = new HashMap<>();
List<Rel> list = new ArrayList<>();
List<Map<String, String>> nodes = new ArrayList<>();
try {
Session session = driver.session();
Map<String, Object> params = new HashMap<>();
params.put("picType", picType);
params.put("caseId", caseId);
Result run = session.run("MATCH (n)-[rel]->(r) where n.picType = r.picType = $picType and n.caseId = r.caseId = $caseId" +
" RETURN id(rel) as id, n.name as source, id(n) as sourceId, type(rel) as name, r.name as target, id(r) as targetId", params);
while (run.hasNext()) {
Record record = run.next();
long id = record.get("id").asLong();
String source = record.get("source").asString();
long sourceId = record.get("sourceId").asLong();
String name = record.get("name").asString();
String target = record.get("target").asString();
long targetId = record.get("targetId").asLong();
list.add(new Rel(id, source, sourceId, name, target, targetId));
}
Result node = session.run("MATCH (n) where n.picType = $picType and n.caseId = $caseId RETURN id(n) as id, n.name as name", params);
while (node.hasNext()) {
Record record = node.next();
String name = record.get("name").asString();
long idlong = record.get("id").asLong();
Map<String, String> nodeMap = new HashMap<>();
nodeMap.put("name", name);
nodeMap.put("entityName", name);
// nodeMap.put("id", idlong + "");
nodes.add(nodeMap);
}
} catch (Exception e) {
e.printStackTrace();
}
map.put("list", list);
map.put("nodes", nodes);
return R.ok(map);
}
@Override
public R<?> test() {
Session session = driver.session();
Map<String, Object> params = new HashMap<>();
params.put("lawActor", "行为人");
params.put("lawParty", "aaaaaa");
Result run = session.run("MATCH (m:LawActor), (n:FictionalOrgan) where m.name=$lawActor OPTIONAL MATCH (m)-[r:`冒充`]->(n) RETURN id(m) as startId, id(n) as endId, id(r) as relId, m.recordId as recordId, m.recordsId as recordsId", params);
while (run.hasNext()) {
Record record = run.next();
String id = record.get("startId").asLong() + "";
String endId = record.get("endId").asLong() + "";
String relId = record.get("relId").asLong() + "";
System.out.println("************" + id);
System.out.println("************" + endId);
System.out.println("************" + relId);
}
return R.ok("222");
}
}

@ -0,0 +1,91 @@
package com.supervision.neo4j.utils;
import com.supervision.neo4j.domain.CaseNode;
import com.supervision.neo4j.domain.Rel;
import com.supervision.neo4j.dto.ResultDTO;
import org.neo4j.driver.Record;
import org.neo4j.driver.Result;
import java.util.ArrayList;
import java.util.List;
public class Neo4jUtils {
public static final String NODE_RETURN = " RETURN id(n) as id, n.name as name, n.nodeType as nodeType, n.recordId as recordId, n.caseId as caseId, n.picType as picType";
public static final String REL_RETURN = " RETURN id(rel) as id, a.name as source, id(a) as sourceId, type(rel) as name, b.name as target, id(b) as targetId";
public static CaseNode getOneNode(Result run) {
CaseNode node = null;
if (run.hasNext()) {
Record record = run.next();
long id = record.get("id").asLong();
String name = record.get("name").asString();
String nodeType = record.get("nodeType").asString();
String recordId = record.get("recordId").asString();
String caseId = record.get("caseId").asString();
String picType = record.get("picType").asString();
node = new CaseNode(id, name, nodeType, recordId, caseId, picType);
}
return node;
}
public static List<CaseNode> getNodeList(Result run) {
List<CaseNode> list = new ArrayList<>();
while (run.hasNext()) {
Record record = run.next();
long id = record.get("id").asLong();
String name = record.get("name").asString();
String nodeType = record.get("nodeType").asString();
String recordId = record.get("recordId").asString();
String caseId = record.get("caseId").asString();
String picType = record.get("picType").asString();
list.add(new CaseNode(id, name, nodeType, recordId, caseId, picType));
}
return list;
}
public static Rel getOneRel(Result run) {
Rel rel = null;
if (run.hasNext()) {
Record record = run.next();
long id = record.get("id").asLong();
String source = record.get("source").asString();
Long sourceId = record.get("sourceId").asLong();
String name = record.get("name").asString();
String target = record.get("target").asString();
Long targetId = record.get("targetId").asLong();
rel = new Rel(id, source, sourceId, name, target, targetId);
}
return rel;
}
public static List<Rel> getRelList(Result run) {
List<Rel> list = new ArrayList<>();
while (run.hasNext()) {
Record record = run.next();
long id = record.get("id").asLong();
String source = record.get("source").asString();
Long sourceId = record.get("sourceId").asLong();
String name = record.get("name").asString();
String target = record.get("target").asString();
Long targetId = record.get("targetId").asLong();
list.add(new Rel(id, source, sourceId, name, target, targetId));
}
return list;
}
public static List<ResultDTO> getResultDTOList(Result run) {
List<ResultDTO> list = new ArrayList<>();
while (run.hasNext()) {
Record record = run.next();
String startId = record.get("startId").asLong() + "";
String endId = record.get("endId").asLong() + "";
String relId = record.get("relId").asLong() + "";
String recordId = record.get("recordId").asString();
String recordsId = record.get("recordsId").asString();
list.add(new ResultDTO(startId, endId, relId, recordId, recordsId));
}
return list;
}
}

@ -0,0 +1,61 @@
package com.supervision.police.controller;
import com.supervision.common.domain.R;
import com.supervision.police.domain.ComDictionary;
import com.supervision.police.dto.DictionaryByTypeParam;
import com.supervision.police.service.ComDictionaryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
/**
* <p>
*
* </p>
*
* @author baomidou
* @since 2022-03-16
*/
@RestController
@RequestMapping("/comDictionary")
@Api(tags = "字典表接口")
public class ComDictionaryController {
@Autowired
private ComDictionaryService dictionaryService;
@GetMapping
@ApiOperation(value = "查询字典", httpMethod = "GET")
public R<?> findDictionary(ComDictionary dictionary,
@RequestParam(required = false, defaultValue = "1") Long page,
@RequestParam(required = false, defaultValue = "10") Long size) {
return dictionaryService.findDictionaryInfo(dictionary, page, size);
}
@PostMapping("/queryByType")
@ApiOperation(value = "通过type查询字典,可一次性查询多个", httpMethod = "POST")
public R<?> findDictionaryListByType(@RequestBody @Validated DictionaryByTypeParam dictionaryByTypeParam) {
return dictionaryService.findDictionaryListByType(dictionaryByTypeParam);
}
@PostMapping
@ApiOperation(value = "新增字典", httpMethod = "POST")
public R<?> insertDictionary(@RequestBody @Validated ComDictionary dictionary) {
return dictionaryService.insertDictionary(dictionary);
}
@PostMapping("/update")
@ApiOperation(value = "修改字典", httpMethod = "POST")
public R<?> updateDictionary(@RequestBody ComDictionary dictionary) {
return dictionaryService.updateDictionary(dictionary);
}
@PostMapping("/deleteByStatus/delete")
@ApiOperation(value = "逻辑删除字典", httpMethod = "POST")
public R<?> logicDeleteDictionary(@RequestParam Long id){
return dictionaryService.logicDeleteDictionary(id);
}
}

@ -0,0 +1,107 @@
package com.supervision.police.controller;
import com.supervision.common.domain.R;
import com.supervision.police.domain.CasePerson;
import com.supervision.police.domain.ModelCase;
import com.supervision.police.service.ModelCaseService;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
@Slf4j
@RequestMapping("modelCase")
public class ModelCaseController {
@Autowired
private ModelCaseService modelCaseService;
/**
*
* @param modelCase
* @param page
* @param size
* @return
*/
@PostMapping("/queryList")
public R<?> queryList(@RequestBody ModelCase modelCase,
@RequestParam(required = false, defaultValue = "1") Integer page,
@RequestParam(required = false, defaultValue = "20") Integer size) {
return modelCaseService.queryList(modelCase, page, size);
}
/**
*
* @param caseNo
* @return
*/
@GetMapping("/checkCaseNo")
public R<?> checkCaseNo(@RequestParam String caseNo) {
return modelCaseService.checkCaseNo(caseNo);
}
/**
*
* @param modelCase
* @return
*/
@PostMapping("/addOrUpd")
public R<?> addOrUpd(@RequestBody ModelCase modelCase) {
return modelCaseService.addOrUpd(modelCase);
}
/**
*
* @param id
* @return
*/
@PostMapping("/del")
public R<?> del(@RequestParam String id) {
return modelCaseService.del(id);
}
/**
*
* @param name
* @return
*/
@GetMapping("/getPerson")
@Operation(summary = "getPersion")
public R<?> getPerson(@RequestParam String caseId,
@RequestParam(required = false, defaultValue = "") String name) {
return modelCaseService.getPerson(caseId, name);
}
@PostMapping("/addPerson")
public R<?> addPerson(@RequestBody CasePerson person) {
return modelCaseService.addPersion(person);
}
/**
*
* @param file
* @return
*/
@PostMapping("/uploadCase")
public R<?> uploadCase(@RequestPart MultipartFile file) {
return modelCaseService.uploadCase(file);
}
/**
*
* @param caseId
* @param indexType
* @return
*/
@PostMapping("/getIndexDetail")
public R<?> getIndexDetail(@RequestParam String caseId,
@RequestParam String indexType,
@RequestParam(required = false, defaultValue = "1") Integer page,
@RequestParam(required = false, defaultValue = "20") Integer size) {
return modelCaseService.getIndexDetail(caseId, indexType, page, size);
}
}

@ -0,0 +1,26 @@
package com.supervision.police.controller;
import com.supervision.common.domain.R;
import com.supervision.police.dto.AnalyseCaseDTO;
import com.supervision.police.service.ModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("model")
public class ModelController {
@Autowired
private ModelService modelService;
/**
*
* @param analyseCaseDTO
* @return
*/
@PostMapping("/analyseCase")
public R<?> analyseCase(@RequestBody AnalyseCaseDTO analyseCaseDTO) {
return modelService.analyseCase(analyseCaseDTO);
}
}

@ -0,0 +1,102 @@
package com.supervision.police.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.supervision.common.domain.R;
import com.supervision.police.domain.ModelAtomicIndex;
import com.supervision.police.domain.ModelIndex;
import com.supervision.police.service.ModelIndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* (ModelIndex)
*
* @author qmy
* @since 2024-07-05 09:20:10
*/
@RestController
@RequestMapping("modelIndex")
public class ModelIndexController {
@Autowired
private ModelIndexService modelIndexService;
/**
*
*
* @param page
* @param modelIndex
* @return
*/
@PostMapping("/selectAll")
public R<?> selectAll(@RequestBody ModelIndex modelIndex,
@RequestParam(required = false, defaultValue = "1") Integer page,
@RequestParam(required = false, defaultValue = "20") Integer size) {
return modelIndexService.selectAll(modelIndex, page, size);
}
/**
* /
*
* @param modelIndex
* @return
*/
@PostMapping("/addOrUpd")
public R<?> addOrUpd(@RequestBody ModelIndex modelIndex) {
return modelIndexService.addOrUpd(modelIndex);
}
/**
*
*
* @param id
* @return
*/
@PostMapping("/del")
public R<?> del(@RequestParam String id) {
return modelIndexService.del(id);
}
/*****************************原子指标**************/
/**
*
*
* @param page
* @param modelAtomicIndex
* @return
*/
@PostMapping("/selectAllAtomic")
public R<?> selectAllAtomic(@RequestBody ModelAtomicIndex modelAtomicIndex,
@RequestParam(required = false, defaultValue = "1") Integer page,
@RequestParam(required = false, defaultValue = "20") Integer size) {
return modelIndexService.selectAllAtomic(modelAtomicIndex, page, size);
}
/**
* /
*
* @param modelAtomicIndex
* @return
*/
@PostMapping("/addOrUpdAtomic")
public R<?> addOrUpdAtomic(@RequestBody ModelAtomicIndex modelAtomicIndex) {
return modelIndexService.addOrUpdAtomic(modelAtomicIndex);
}
/**
*
*
* @param id
* @return
*/
@PostMapping("/delAtomic")
public R<?> delAtomic(@RequestParam String id) {
return modelIndexService.delAtomic(id);
}
}

@ -0,0 +1,122 @@
package com.supervision.police.controller;
import com.supervision.common.domain.R;
import com.supervision.police.domain.NotePrompt;
import com.supervision.police.domain.NoteRecords;
import com.supervision.police.dto.ListDTO;
import com.supervision.police.service.ModelRecordTypeService;
import com.supervision.police.service.RecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
@RestController
@Slf4j
@RequestMapping("record")
public class RecordController {
@Autowired
public ModelRecordTypeService modelRecordTypeService;
@Autowired
public RecordService recordService;
/**
*
* @param name
* @param page
* @param size
* @return
*/
@GetMapping("queryType")
public R<?> queryType(@RequestParam(required = false) String name,
@RequestParam(required = false, defaultValue = "1") Integer page,
@RequestParam(required = false, defaultValue = "20") Integer size) {
return modelRecordTypeService.queryType(name, page, size);
}
// @PostMapping("saveType")
// public R<?> saveType(@RequestBody ModelRecordType type) {
// return modelRecordTypeService.saveType(type);
// }
/**
*
* @param prompt
* @return
*/
@PostMapping("/addOrUpdPrompt")
public R<?> addOrUpdPrompt(@RequestBody NotePrompt prompt) {
return modelRecordTypeService.addOrUpdPrompt(prompt);
}
/**
*
* @param prompt
* @return
*/
@PostMapping("/delPrompt")
public R<?> delPrompt(@RequestBody NotePrompt prompt) {
return modelRecordTypeService.delPrompt(prompt);
}
/**
*
* @param caseId
* @param name
* @param recordId
* @return
*/
@GetMapping("/getThreeInfo")
public R<?> getThreeInfo(@RequestParam String caseId,
@RequestParam String name,
@RequestParam(required = false) String recordId) {
return modelRecordTypeService.getThreeInfo(caseId, name, recordId);
}
@PostMapping("/addNeo4j")
public R<?> addNeo4j(@RequestBody ListDTO list) {
return modelRecordTypeService.addNeo4j(list.getIds());
}
/**
*
* @param records
* @return
*/
@PostMapping("/addOrUpdRecords")
public R<?> uploadRecords(NoteRecords records,
@RequestPart("file") List<MultipartFile> fileList) throws IOException {
return recordService.uploadRecords(records, fileList);
}
/**
*
* @param noteRecords
* @param page
* @param size
* @return
*/
@PostMapping("/queryRecords")
public R<?> queryRecords(@RequestBody NoteRecords noteRecords,
@RequestParam(required = false, defaultValue = "1") Integer page,
@RequestParam(required = false, defaultValue = "20") Integer size) {
return recordService.queryRecords(noteRecords, page, size);
}
/**
*
* @param id
* @return
*/
@PostMapping("/delRecords")
public R<?> delRecords(@RequestParam String id) {
return recordService.delRecords(id);
}
}

@ -0,0 +1,49 @@
package com.supervision.police.domain;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
/**
* (CasePerson)
*
* @author qmy
* @since 2024-07-06 13:27:29
*/
@Data
@TableName("case_person")
public class CasePerson implements Serializable {
@TableId
private String id;
/**
* id
*/
private String caseId;
/**
*
*/
private String name;
/**
*
*/
private String idCard;
/**
*
*/
private String roleCode;
/**
*
*/
@TableField(exist=false)
private String roleName;
}

@ -0,0 +1,90 @@
package com.supervision.police.domain;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* <p>
*
* </p>
*
* @author baomidou
* @since 2022-03-16
*/
@TableName("com_dictionary")
@Data
public class ComDictionary implements Serializable {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* code
*/
@TableField(value = "code")
private String value;
/**
*
*/
@TableField(value = "name")
private String label;
/**
* id
*/
private Long pid;
/**
*
*/
private String type;
/**
* 01
*/
private String status;
/**
*
*/
private String dataStatus;
/**
*
*/
private String note;
/**
*
*/
private String creator;
/**
*
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date updateTime;
/**
*
*/
@TableField(fill = FieldFill.INSERT)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date createTime;
/**
*
*/
private String updater;
@TableField(exist = false)
private List<ComDictionary> child;
}

@ -0,0 +1,103 @@
package com.supervision.police.domain;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.io.Serializable;
/**
* (ModelAtomicIndex)
*
* @author qmy
* @since 2024-07-05 10:23:11
*/
@Data
@TableName("model_atomic_index")
public class ModelAtomicIndex implements Serializable {
@TableId
private String id;
/**
*
*/
private String name;
/**
*
*/
private String remark;
/**
*
*/
private String caseType;
@TableField(exist = false)
public String caseTypeName;
/**
*
*/
private String indexSource;
@TableField(exist = false)
public String indexSourceName;
/**
*
*/
private String connectStatus;
/**
*
*/
private String judgeResult;
/**
*
*/
private String queryLang;
/**
*
*/
private String recordType;
@TableField(exist = false)
public String recordTypeName;
/**
*
*/
private String prompt;
/**
*
*/
@TableField(fill = FieldFill.INSERT)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date createTime;
/**
*
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date updateTime;
@TableField(exist = false)
@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
private Date updateStartTime;
@TableField(exist = false)
@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
private Date updateEndTime;
/**
*
*/
private String dataStatus;
}

@ -0,0 +1,59 @@
package com.supervision.police.domain;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.io.Serializable;
/**
* (ModelAtomicResult)
*
* @author qmy
* @since 2024-07-09 17:21:20
*/
@Data
@TableName("model_atomic_result")
public class ModelAtomicResult implements Serializable {
@TableId
private String id;
/**
* id
*/
private String caseId;
/**
* id
*/
private String atomicId;
/**
* -1:, 0:, 1
*/
private String atomicResult;
/**
* id
*/
private String recordId;
/**
* id
*/
private String recordsId;
/**
*
*/
@TableField(fill = FieldFill.INSERT)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date createTime;
}

@ -0,0 +1,130 @@
package com.supervision.police.domain;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.io.Serializable;
/**
* (ModelCase)
*
* @author qmy
* @since 2024-07-02 14:37:15
*/
@Data
@TableName("model_case")
public class ModelCase implements Serializable {
/**
*
*/
@TableId
private String id;
/**
*
*/
private String caseName;
/**
*
*/
private String caseType;
@TableField(exist=false)
private String caseTypeName;
/**
*
*/
private String caseStatus;
@TableField(exist=false)
private String caseStatusName;
/**
*
*/
private String crimeMode;
@TableField(exist=false)
private String crimeModeName;
/**
*
*/
private String caseDetail;
/**
*
*/
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date registerTime;
/**
*
*/
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date acceptTime;
/**
*
*/
private String lawActor;
/**
*
*/
private String lawParty;
/**
*
*/
private String identifyResult;
@TableField(exist=false)
private String identifyResultName;
/**
*
*/
private Integer totalScore;
/**
*
*/
private Integer indexNum;
/**
*
*/
@TableField(fill = FieldFill.INSERT)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date createTime;
/**
*
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date updateTime;
@TableField(exist=false)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date updateStartTime;
@TableField(exist=false)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date updateEndTime;
/**
*
*/
private String dataStatus;
/**
*
*/
private String caseNo;
}

@ -0,0 +1,98 @@
package com.supervision.police.domain;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* (ModelIndex)
*
* @author qmy
* @since 2024-07-05 09:20:10
*/
@Data
@TableName("model_index")
public class ModelIndex implements Serializable {
@TableId
private String id;
/**
*
*/
private String name;
/**
*
*/
private String shortName;
/**
*
*/
private String remark;
/**
*
*/
private String indexType;
@TableField(exist = false)
private String indexTypeName;
/**
*
*/
private Integer indexScore;
/**
*
*/
private Integer atomicIndexNum;
@TableField(exist = false)
private List<ModelAtomicIndex> atomicIndexList;
/**
*
*/
private String caseType;
@TableField(exist = false)
private String caseTypeName;
/**
*
*/
private String judgeLogic;
/**
*
*/
@TableField(fill = FieldFill.INSERT)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date createTime;
/**
*
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date updateTime;
@TableField(exist = false)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date updateStartTime;
@TableField(exist = false)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date updateEndTime;
/**
*
*/
private String dataStatus;
}

@ -0,0 +1,54 @@
package com.supervision.police.domain;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.io.Serializable;
/**
* (ModelIndexResult)
*
* @author qmy
* @since 2024-07-09 18:09:24
*/
@Data
@TableName("model_index_result")
public class ModelIndexResult implements Serializable {
@TableId
private String id;
/**
* id
*/
private String caseId;
/**
* id
*/
private String indexId;
/**
* true/false
*/
private String indexResult;
/**
* ids
*/
private String atomicIds;
/**
*
*/
@TableField(fill = FieldFill.INSERT)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date createTime;
}

@ -0,0 +1,39 @@
package com.supervision.police.domain;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@TableName(value = "model_record_type")
@Data
public class ModelRecordType implements Serializable {
/**
* ID
*/
@TableId
private String id;
/**
* ()
*/
private String recordType;
/**
*
*/
@TableField(exist = false)
private List<NotePrompt> prompts;
/**
*
*/
@TableField(exist = false)
private List<NoteRecord> records;
}

@ -0,0 +1,29 @@
package com.supervision.police.domain;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
@TableName(value = "note_prompt")
@Data
public class NotePrompt implements Serializable {
/**
* ID
*/
@TableId
private String id;
/**
* id
*/
private String typeId;
/**
*
*/
private String prompt;
}

@ -0,0 +1,71 @@
package com.supervision.police.domain;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@TableName(value = "note_record")
@Data
public class NoteRecord implements Serializable {
/**
* ID
*/
@TableId
private String id;
/**
* id
*/
private String caseId;
/**
*
*/
private String personName;
/**
*
*/
private String noteName;
/**
*
*/
private String question;
/**
*
*/
private String answer;
/**
*
*/
@TableField(fill = FieldFill.INSERT)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date createTime;
/**
* ()
*/
private String recordType;
/**
* id
*/
@TableField(exist = false)
private String recordTypeId;
/**
* id
*/
private String noteRecordsId;
}

@ -0,0 +1,104 @@
package com.supervision.police.domain;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;
import java.io.Serializable;
import java.util.List;
/**
* (NoteRecords)
*
* @author qmy
* @since 2024-07-05 08:53:20
*/
@Data
@TableName("note_records")
public class NoteRecords implements Serializable {
@TableId
private String id;
/**
* id
*/
private String caseId;
/**
*
*/
private String recordName;
/**
* id
*/
private String fileIds;
/**
*
*/
private String name;
/**
*
*/
private String role;
/**
*
*/
private Integer confessionMaterial;
/**
*
*/
private String lawAsker;
/**
*
*/
// @JsonFormat(pattern="yyyy-MM-dd HH:mm",timezone = "GMT+8")
private String confessionStartTime;
/**
*
*/
// @JsonFormat(pattern="yyyy-MM-dd HH:mm",timezone = "GMT+8")
private String confessionEndTime;
/**
*
*/
private Integer indexNum;
/**
*
*/
@TableField(fill = FieldFill.INSERT)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date createTime;
/**
*
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date updateTime;
/**
*
*/
private String dataStatus;
@TableField(exist = false)
private List<NoteRecords> children;
}

@ -0,0 +1,88 @@
package com.supervision.police.domain;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@TableName(value = "triple_info")
@Data
public class TripleInfo implements Serializable {
/**
* ID
*/
@TableId
private String id;
/**
*
*/
private String startNode;
/**
*
*/
private String endNode;
/**
*
*/
private String relation;
/**
* id
*/
private String noteRecordId;
@TableField(exist = false)
private String noteRecordsId;
/**
* id
*/
@TableField(exist = false)
private String caseId;
/**
*
*/
@TableField(fill = FieldFill.INSERT)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date createTime;
/**
*
*/
private String addNeo4j;
/**
* (neo4j)
*/
private String startNodeType;
/**
* (neo4j)
*/
private String endNodeType;
public TripleInfo() {
}
// todo
public TripleInfo(String startNode, String endNode, String relation, String noteRecordId, Date createTime, String startNodeType, String endNodeType) {
this.startNode = startNode;
this.endNode = endNode;
this.relation = relation;
this.noteRecordId = noteRecordId;
this.createTime = createTime;
this.startNodeType = startNodeType;
this.endNodeType = endNodeType;
}
}

@ -0,0 +1,19 @@
package com.supervision.police.dto;
import com.supervision.police.domain.ModelAtomicIndex;
import lombok.Data;
import java.util.List;
@Data
public class AnalyseCaseDTO {
private String caseId;
private String lawActor;
private String lawParty;
List<ModelAtomicIndex> atomicIndexList;
}

@ -0,0 +1,21 @@
package com.supervision.police.dto;
import lombok.Data;
/**
*
*/
@Data
public class AtomicData {
/**
* id
*/
private String atomicIndex;
/**
*
*/
private String relationalSymbol;
}

@ -0,0 +1,28 @@
package com.supervision.police.dto;
import lombok.Data;
@Data
public class AtomicIndexDTO {
/**
*
*/
private String indexName;
/**
*
*/
private Integer score;
/**
*
*/
private String indexResult;
/**
*
*/
private String record;
}

@ -0,0 +1,23 @@
package com.supervision.police.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @author qmy
* @program
* @description
* @createTime 2021/11/29
*/
@Data
public class DictionaryByTypeParam implements Serializable {
@ApiModelProperty(value = "根据type类型查询树列表")
public List<String> list;
@ApiModelProperty(value = "是否返回树形结构, 1返回, 0不返回, 默认为1")
public Integer isTree = 1;
}

@ -0,0 +1,40 @@
package com.supervision.police.dto;
import lombok.Data;
import java.util.List;
@Data
public class IndexDetail {
/**
*
*/
private String indexName;
/**
*
*/
private Integer score;
/**
*
*/
private String indexResult;
/**
*
*/
private String record;
/**
* ids
*/
private String atomicIds;
/**
*
*/
private List<AtomicIndexDTO> children;
}

@ -0,0 +1,28 @@
package com.supervision.police.dto;
import lombok.Data;
import java.util.List;
/**
*
*/
@Data
public class JudgeLogic {
/**
*
*/
private String groupLogic;
/**
*
*/
private String rowLogic;
/**
*
*/
private List<AtomicData> atomicData;
}

@ -0,0 +1,12 @@
package com.supervision.police.dto;
import lombok.Data;
@Data
public class KeyAndNameObject {
private String code;
private String name;
}

@ -0,0 +1,12 @@
package com.supervision.police.dto;
import lombok.Data;
import java.util.List;
@Data
public class ListDTO {
public List<String> ids;
}

@ -0,0 +1,32 @@
package com.supervision.police.dto;
import lombok.Data;
/**
* @author qmy
* @since 2023-03-30
*/
@Data
public class SignParam {
private String year;
private String system;
private String signer;
private String approvalNumber;
private String issuelDate;
public SignParam() {
}
public SignParam(String year, String system, String signer, String approvalNumber, String issuelDate) {
this.year = year;
this.system = system;
this.signer = signer;
this.approvalNumber = approvalNumber;
this.issuelDate = issuelDate;
}
}

@ -0,0 +1,15 @@
package com.supervision.police.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.supervision.police.domain.CasePerson;
/**
* (CasePerson)访
*
* @author qmy
* @since 2024-07-06 13:27:29
*/
public interface CasePersonMapper extends BaseMapper<CasePerson> {
}

@ -0,0 +1,53 @@
package com.supervision.police.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.supervision.police.domain.ComDictionary;
import com.supervision.police.dto.KeyAndNameObject;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* <p>
* Mapper
* </p>
*
* @author dw
* @since 2021-11-17
*/
@Repository
public interface ComDictionaryMapper extends BaseMapper<ComDictionary> {
List<ComDictionary> queryAllChildrenInfoForPid(@Param("pid") Long id);
/**
* id, pid 0
*
* @param id id
*/
Long updateDataStatusByIdAndPid(@Param("id") Long id);
/**
* typecode
*
* @return
*/
ComDictionary queryDicByTypeAndCode(@Param("code") String code,
@Param("type") String type);
//根据type和name唯一确定一项
ComDictionary queryByTypeAndName(@Param("type") String type,
@Param("name") String name);
//根据type和name唯一确定一项
String queryDicByTypeAndName(@Param("type") String type,
@Param("name") String name);
/**
*
*/
List<String> queryAllType();
List<KeyAndNameObject> queryIndustry(@Param("type") String type);
}

@ -0,0 +1,23 @@
package com.supervision.police.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.supervision.police.domain.ModelAtomicIndex;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* (ModelAtomicIndex)访
*
* @author qmy
* @since 2024-07-05 10:23:11
*/
public interface ModelAtomicIndexMapper extends BaseMapper<ModelAtomicIndex> {
IPage<ModelAtomicIndex> selectAll(IPage<ModelAtomicIndex> iPage, @Param("index") ModelAtomicIndex index);
List<ModelAtomicIndex> selectByCaseType(@Param("caseType") String caseType);
}

@ -0,0 +1,19 @@
package com.supervision.police.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.supervision.police.domain.ModelAtomicResult;
import org.apache.ibatis.annotations.Param;
/**
* (ModelAtomicResult)访
*
* @author qmy
* @since 2024-07-09 17:21:20
*/
public interface ModelAtomicResultMapper extends BaseMapper<ModelAtomicResult> {
ModelAtomicResult selectByCaseIdAndAtomicId(@Param("caseId") String caseId,
@Param("atomicId") String atomicId);
}

@ -0,0 +1,33 @@
package com.supervision.police.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.supervision.police.domain.ModelCase;
import com.supervision.police.domain.ModelRecordType;
import com.supervision.police.dto.AtomicIndexDTO;
import com.supervision.police.dto.IndexDetail;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* (ModelCase)访
*
* @author qmy
* @since 2024-07-02 14:47:59
*/
public interface ModelCaseMapper extends BaseMapper<ModelCase> {
IPage<ModelCase> selectAll(IPage<ModelCase> iPage, ModelCase modelCase);
int selectMaxIndex();
IPage<IndexDetail> getIndexDetail(IPage<IndexDetail> iPage,
@Param("caseId") String caseId,
@Param("indexType") String indexType);
List<AtomicIndexDTO> getAtomicDetail(@Param("caseId") String caseId,
@Param("atomicIds") List<String> atomicIds);
}

@ -0,0 +1,20 @@
package com.supervision.police.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.supervision.police.domain.ModelIndex;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* (ModelIndex)访
*
* @author qmy
* @since 2024-07-05 09:20:10
*/
public interface ModelIndexMapper extends BaseMapper<ModelIndex> {
List<ModelIndex> selectByCaseType(@Param("caseType") String caseType);
}

@ -0,0 +1,19 @@
package com.supervision.police.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.supervision.police.domain.ModelIndexResult;
import org.apache.ibatis.annotations.Param;
/**
* (ModelIndexResult)访
*
* @author qmy
* @since 2024-07-09 18:09:24
*/
public interface ModelIndexResultMapper extends BaseMapper<ModelIndexResult> {
ModelIndexResult selectByCaseIdAndIndexId(@Param("caseId") String caseId,
@Param("indexId") String indexId);
}

@ -0,0 +1,19 @@
package com.supervision.police.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.supervision.police.domain.ModelRecordType;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface ModelRecordTypeMapper extends BaseMapper<ModelRecordType> {
IPage<ModelRecordType> selectByName(IPage<ModelRecordType> iPage, @Param("name") String name);
List<ModelRecordType> selectByName(@Param("name") String name);
ModelRecordType queryByName(@Param("name") String name);
List<String> getAllType();
}

@ -0,0 +1,18 @@
package com.supervision.police.mapper;
import com.supervision.springaidemo.domain.NoteCheckRecord;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* @author flevance
* @description note_check_record()Mapper
* @createDate 2024-05-11 15:47:02
* @Entity com.supervision.springaidemo.domain.NoteCheckRecord
*/
public interface NoteCheckRecordMapper extends BaseMapper<NoteCheckRecord> {
}

@ -0,0 +1,13 @@
package com.supervision.police.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.supervision.police.domain.NotePrompt;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface NotePromptMapper extends BaseMapper<NotePrompt> {
List<NotePrompt> queryPrompt(@Param("typeId") String typeId);
}

@ -0,0 +1,17 @@
package com.supervision.police.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.supervision.police.domain.NoteRecord;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface NoteRecordMapper extends BaseMapper<NoteRecord> {
List<NoteRecord> selectByRecordType(@Param("recordType") String recordType);
List<NoteRecord> selectRecord(@Param("caseId") String caseId,
@Param("name") String name,
@Param("recordId") String recordId);
}

@ -0,0 +1,15 @@
package com.supervision.police.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.supervision.police.domain.NoteRecords;
/**
* (NoteRecords)访
*
* @author qmy
* @since 2024-07-05 08:53:20
*/
public interface NoteRecordsMapper extends BaseMapper<NoteRecords> {
}

@ -0,0 +1,13 @@
package com.supervision.police.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.supervision.police.domain.TripleInfo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface TripleInfoMapper extends BaseMapper<TripleInfo> {
List<TripleInfo> selectByIds(@Param("ids") List<String> ids);
}

@ -0,0 +1,33 @@
package com.supervision.police.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.supervision.common.domain.R;
import com.supervision.police.domain.ComDictionary;
import com.supervision.police.dto.DictionaryByTypeParam;
import java.util.List;
/**
* <p>
*
* </p>
*
* @author baomidou
* @since 2022-03-16
*/
public interface ComDictionaryService extends IService<ComDictionary> {
R<?> findDictionaryInfo(ComDictionary dictionary, Long page, Long size);
R<?> findDictionaryListByType(DictionaryByTypeParam dictionaryByTypeParam);
R<?> insertDictionary(ComDictionary dictionary);
R<?> updateDictionary(ComDictionary dictionary);
R<?> logicDeleteDictionary(Long id);
String getName(List<ComDictionary> list, String type, String value);
String getValue(List<ComDictionary> list, String type, String name);
}

@ -0,0 +1,34 @@
package com.supervision.police.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.supervision.common.domain.R;
import com.supervision.police.domain.CasePerson;
import com.supervision.police.domain.ModelCase;
import org.springframework.web.multipart.MultipartFile;
/**
* (ModelCase)
*
* @author makejava
* @since 2024-07-02 14:14:43
*/
public interface ModelCaseService extends IService<ModelCase> {
R<?> queryList(ModelCase modelCase, Integer page, Integer size);
R<?> checkCaseNo(String caseNo);
R<?> addOrUpd(ModelCase modelCase);
R<?> del(String id);
R<?> getPerson(String caseId, String name);
R<?> addPersion(CasePerson person);
R<?> uploadCase(MultipartFile file);
R<?> getIndexDetail(String caseId, String indexType, Integer page, Integer size);
}

@ -0,0 +1,29 @@
package com.supervision.police.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.supervision.common.domain.R;
import com.supervision.police.domain.ModelAtomicIndex;
import com.supervision.police.domain.ModelIndex;
/**
* (ModelIndex)
*
* @author qmy
* @since 2024-07-05 09:20:10
*/
public interface ModelIndexService extends IService<ModelIndex> {
R<?> selectAll(ModelIndex modelIndex, Integer page, Integer size);
R<?> addOrUpd(ModelIndex modelIndex);
R<?> del(String id);
R<?> selectAllAtomic(ModelAtomicIndex modelAtomicIndex, Integer page, Integer size);
R<?> addOrUpdAtomic(ModelAtomicIndex modelAtomicIndex);
R<?> delAtomic(String id);
}

@ -0,0 +1,25 @@
package com.supervision.police.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.supervision.common.domain.R;
import com.supervision.police.domain.ModelRecordType;
import com.supervision.police.domain.NotePrompt;
import java.util.List;
public interface ModelRecordTypeService extends IService<ModelRecordType> {
R<?> queryType(String name, Integer page, Integer size);
ModelRecordType queryByName(String content);
R<?> saveType(ModelRecordType type);
R<?> addOrUpdPrompt(NotePrompt prompt);
R<?> delPrompt(NotePrompt prompt);
R<?> getThreeInfo(String caseId, String name, String recordId);
R<?> addNeo4j(List<String> ids);
}

@ -0,0 +1,10 @@
package com.supervision.police.service;
import com.supervision.common.domain.R;
import com.supervision.police.dto.AnalyseCaseDTO;
public interface ModelService {
R<?> analyseCase(AnalyseCaseDTO analyseCaseDTO);
}

@ -0,0 +1,13 @@
package com.supervision.police.service;
import com.supervision.springaidemo.domain.NoteCheckRecord;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* @author flevance
* @description note_check_record()Service
* @createDate 2024-05-11 15:47:02
*/
public interface NoteCheckRecordService extends IService<NoteCheckRecord> {
}

@ -0,0 +1,20 @@
package com.supervision.police.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.supervision.common.domain.R;
import com.supervision.police.domain.NoteRecord;
import com.supervision.police.domain.NoteRecords;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
public interface RecordService extends IService<NoteRecord> {
R<?> uploadRecords(NoteRecords records, List<MultipartFile> fileList) throws IOException;
R<?> queryRecords(NoteRecords noteRecords, Integer page, Integer size);
R<?> delRecords(String id);
}

@ -0,0 +1,192 @@
package com.supervision.police.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.supervision.common.domain.R;
import com.supervision.common.utils.IPages;
import com.supervision.common.utils.StringUtils;
import com.supervision.police.domain.ComDictionary;
import com.supervision.police.dto.DictionaryByTypeParam;
import com.supervision.police.mapper.ComDictionaryMapper;
import com.supervision.police.service.ComDictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
*
* </p>
*
* @author baomidou
* @since 2022-03-16
*/
@Service
public class ComDictionaryServiceImpl extends ServiceImpl<ComDictionaryMapper, ComDictionary> implements ComDictionaryService {
@Autowired
private ComDictionaryMapper comDictionaryMapper;
@Override
public R<?> findDictionaryInfo(ComDictionary dictionary, Long page, Long size) {
LambdaQueryWrapper<ComDictionary> lambdaQueryWrapper = Wrappers.lambdaQuery();
lambdaQueryWrapper
.eq(dictionary.getId() != null, ComDictionary::getId, dictionary.getId())
.eq(StringUtils.isNotBlank(dictionary.getValue()), ComDictionary::getValue, dictionary.getValue())
.eq(StringUtils.isNotBlank(dictionary.getType()), ComDictionary::getType, dictionary.getType())
.eq(dictionary.getPid() != null, ComDictionary::getPid, dictionary.getPid())
.eq(ComDictionary::getDataStatus, "1")
.isNotNull(ComDictionary::getValue);
IPage<ComDictionary> iPage = new Page<>(page, size);
iPage = comDictionaryMapper.selectPage(iPage, lambdaQueryWrapper);
return R.ok(IPages.buildDataMap(iPage.getRecords(), iPage.getRecords().size()));
}
/**
* type
* @param dictionaryByTypeParam
* @return
*/
@Override
public R<?> findDictionaryListByType(DictionaryByTypeParam dictionaryByTypeParam) {
Map<String, List<ComDictionary>> resultMap = queryDictionary(dictionaryByTypeParam);
return R.ok(resultMap);
}
/**
* ,.
* @param dictionaryByTypeParam
* @return
*/
private Map<String, List<ComDictionary>> queryDictionary(DictionaryByTypeParam dictionaryByTypeParam) {
Map<String,List<ComDictionary>> resultMap = new HashMap<>();
List<String> typeList = new ArrayList<>();
if (dictionaryByTypeParam.getList() == null || dictionaryByTypeParam.getList().size() <=0) {
typeList = comDictionaryMapper.queryAllType();
} else {
typeList = dictionaryByTypeParam.getList();
}
for (String dictType : typeList) {
List<ComDictionary> queryList = new ArrayList<>();
List<ComDictionary> otherList = new ArrayList<>();
ComDictionary comDictionary = new ComDictionary();
comDictionary.setType(dictType);
Wrapper<ComDictionary> wrapper = Wrappers.query(comDictionary);
queryList = this.comDictionaryMapper.selectList(wrapper);
changeTree(queryList,otherList);
if (otherList.size() > 1) {
if (dictionaryByTypeParam.getIsTree() != null && dictionaryByTypeParam.getIsTree() == 0) {
resultMap.put(dictType,queryList);
}else {
resultMap.put(dictType,otherList);
}
} else {
if (dictionaryByTypeParam.getIsTree() != null && dictionaryByTypeParam.getIsTree() == 0){
resultMap.put(dictType,otherList.get(0).getChild());
}else {
resultMap.put(dictType,otherList);
}
}
}
return resultMap;
}
@Override
public R<?> insertDictionary(ComDictionary dictionary) {
comDictionaryMapper.insert(dictionary);
return R.okMsg("新增成功");
}
@Override
public R<?> updateDictionary(ComDictionary dictionary) {
try{
comDictionaryMapper.updateById(dictionary);
return R.okMsg("更新成功");
}catch (Exception e) {
return R.fail("更新失败");
}
}
@Override
public R<?> logicDeleteDictionary(Long id) {
if (comDictionaryMapper.updateDataStatusByIdAndPid(id) > 0) {
return R.okMsg("更新成功");
} else {
return R.fail(700,"未找到该条数据的信息.");
}
}
private void changeTree(List<ComDictionary> queryList, List<ComDictionary> resultList) {
// 先找到所有的一级菜单
for (ComDictionary comDictionary : queryList) {
// 一级菜单没有parentId
if (comDictionary.getPid() == null || comDictionary.getPid() == 0l) {
resultList.add(comDictionary);
}
}
// 为一级菜单设置子菜单getChild是递归调用的
for (ComDictionary comDictionary : resultList) {
comDictionary.setPid(0L);
comDictionary.setChild(getChild(comDictionary.getId(), queryList));
}
}
/**
*
*
*
* @param id id
* @param dictionaryList
* @return
*/
private List<ComDictionary> getChild(Long id, List<ComDictionary> dictionaryList) {
// 子菜单
List<ComDictionary> childList = new ArrayList<>();
for (ComDictionary comDictionary : dictionaryList) {
if (comDictionary.getPid() != null && comDictionary.getPid().equals(id)) {
childList.add(comDictionary);
}
}
// 把子菜单的子菜单再循环一遍
for (ComDictionary comDictionary : childList) {
// 直接递归
comDictionary.setChild(getChild(comDictionary.getId(), dictionaryList));
} // 递归退出条件
if (childList.size() == 0) {
return null;
}
return childList;
}
@Override
public String getName(List<ComDictionary> list, String type, String value) {
for (ComDictionary comDictionary : list) {
// 父级字典项的value是null
if (comDictionary.getType().equals(type) && comDictionary.getValue() != null
&& comDictionary.getValue().equals(value)) {
return comDictionary.getLabel();
}
}
return "";
}
@Override
public String getValue(List<ComDictionary> list, String type, String label) {
for (ComDictionary comDictionary : list) {
if (comDictionary.getType().equals(type) && comDictionary.getLabel().equals(label)) {
return comDictionary.getValue();
}
}
return "";
}
}

@ -0,0 +1,222 @@
package com.supervision.police.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.supervision.common.domain.R;
import com.supervision.common.enums.ResultStatusEnum;
import com.supervision.common.exception.CustomException;
import com.supervision.common.utils.ExcelReader;
import com.supervision.common.utils.IPages;
import com.supervision.common.utils.StringUtils;
import com.supervision.police.domain.CasePerson;
import com.supervision.police.domain.ComDictionary;
import com.supervision.police.domain.ModelAtomicIndex;
import com.supervision.police.dto.AtomicIndexDTO;
import com.supervision.police.dto.IndexDetail;
import com.supervision.police.mapper.CasePersonMapper;
import com.supervision.police.mapper.ModelCaseMapper;
import com.supervision.police.domain.ModelCase;
import com.supervision.police.service.ComDictionaryService;
import com.supervision.police.service.ModelCaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.IOException;
import java.util.*;
/**
* (ModelCase)
*
* @author qmy
* @since 2024-07-02 14:51:27
*/
@Service
public class ModelCaseServiceImpl extends ServiceImpl<ModelCaseMapper, ModelCase> implements ModelCaseService {
@Autowired
private ComDictionaryService comDictionaryService;
@Autowired
private ModelCaseMapper modelCaseMapper;
@Autowired
private CasePersonMapper casePersonMapper;
/**
*
* @param modelCase
* @param page
* @param size
* @return
*/
@Override
public R<?> queryList(ModelCase modelCase, Integer page, Integer size) {
IPage<ModelCase> iPage = new Page<>(page, size);
iPage = modelCaseMapper.selectAll(iPage, modelCase);
List<ModelCase> records = iPage.getRecords();
List<ComDictionary> dicts = comDictionaryService.list();
for (ModelCase mc : records) {
String[] caseTypes = mc.getCaseType().split(",");
List<String> caseType = new ArrayList<>();
for (String type : caseTypes) {
caseType.add(comDictionaryService.getName(dicts, "case_type", type));
}
mc.setCaseTypeName(StringUtils.join(caseType, ","));
mc.setCaseStatusName(comDictionaryService.getName(dicts, "case_status", mc.getCaseStatus()));
mc.setCrimeModeName(comDictionaryService.getName(dicts, "crime_mode", mc.getCrimeMode()));
mc.setIdentifyResultName(comDictionaryService.getName(dicts, "identify_result", mc.getIdentifyResult()));
}
iPage.setRecords(records);
return R.ok(IPages.buildDataMap(iPage));
}
@Override
public R<?> checkCaseNo(String caseNo) {
LambdaQueryWrapper<ModelCase> wrapper = Wrappers.lambdaQuery();
wrapper.eq(ModelCase::getCaseNo, caseNo)
.eq(ModelCase::getDataStatus, "1");
ModelCase modelCase = modelCaseMapper.selectOne(wrapper);
if (modelCase == null) {
return R.ok(caseNo);
} else {
return R.okMsg("案件编号已存在,请勿重复添加");
}
}
@Override
public R<?> addOrUpd(ModelCase modelCase) {
int i = 0;
if (modelCase.getId() != null) {
i = modelCaseMapper.updateById(modelCase);
} else {
Long num = modelCaseMapper.selectCount(null);
modelCase.setIndexNum(Integer.parseInt(num.toString()) + 1);
i = modelCaseMapper.insert(modelCase);
}
if (i > 0) {
return R.okMsg("保存成功");
} else {
return R.fail("保存失败");
}
}
@Override
public R<?> del(String id) {
ModelCase modelCase = modelCaseMapper.selectById(id);
modelCase.setDataStatus(StringUtils.getUUID());
int i = modelCaseMapper.updateById(modelCase);
if (i > 0) {
return R.okMsg("删除成功");
} else {
return R.fail("删除失败");
}
}
@Override
public R<?> getPerson(String caseId, String name) {
LambdaQueryWrapper<CasePerson> wrapper = Wrappers.lambdaQuery();
wrapper.like(CasePerson::getCaseId, caseId)
.like(CasePerson::getName, name);
List<CasePerson> casePeople = casePersonMapper.selectList(wrapper);
List<ComDictionary> dicts = comDictionaryService.list();
for (CasePerson cp : casePeople) {
cp.setRoleName(comDictionaryService.getName(dicts, "case_role", cp.getRoleCode()));
}
return R.ok(casePeople);
}
@Override
public R<?> addPersion(CasePerson person) {
int i = casePersonMapper.insert(person);
if (i > 0) {
return R.okMsg("新增成功");
} else {
return R.fail("新增失败");
}
}
@Override
public R<?> uploadCase(MultipartFile file) {
/**
*
*/
String fileName = file.getOriginalFilename();
assert fileName != null;
// 截取文件的类型符
String substring = fileName.substring(fileName.lastIndexOf(".") + 1);
if (!("xls".equals(substring) || "xlsx".equals(substring))) {
throw new CustomException(ResultStatusEnum.INCORRECT_FILE_FORMAT);// 响应“文件格式不正确”异常
}
List<ModelCase> putList = new ArrayList<>();
try {
putList = ExcelReader.getCaseList(file.getInputStream(), substring, null);
} catch (IOException e) {
e.printStackTrace();
throw new CustomException(ResultStatusEnum.UPLOAD_EXCEPTION);// 响应“文件上传异常”错误
}
List<ComDictionary> dicts = comDictionaryService.list();
/**
* bean
*/
List<Map<String, Object>> errorList = new ArrayList<>();
int index = modelCaseMapper.selectMaxIndex() + 1;
int add = 0;
for (ModelCase modelCase : putList) {
if (StringUtils.isEmpty(modelCase.getCaseNo()) || StringUtils.isEmpty(modelCase.getCaseName())
|| StringUtils.isEmpty(modelCase.getCaseTypeName()) || StringUtils.isEmpty(modelCase.getCaseStatusName())
|| StringUtils.isEmpty(modelCase.getCrimeModeName())) {
errorList.add(errorMapBuilder(modelCase, "必填项为空"));
continue;
}
//替换字典项
String[] split = modelCase.getCaseTypeName().split(",");
List<String> caseTypes = new ArrayList<>();
for (String type : split) {
caseTypes.add(comDictionaryService.getValue(dicts, "case_type", type));
}
modelCase.setCaseType(StringUtils.join(caseTypes, ","));
modelCase.setCaseStatus(comDictionaryService.getValue(dicts, "case_status", modelCase.getCaseStatusName()));
modelCase.setCrimeMode(comDictionaryService.getValue(dicts, "crime_mode", modelCase.getCrimeModeName()));
modelCase.setIndexNum(index);
modelCaseMapper.insert(modelCase);
add++;
index++;
}
Map<String, Object> returnMap = new HashMap<>();
returnMap.put("errorList", errorList);
returnMap.put("add", add);
return R.ok(returnMap);
}
private Map<String, Object> errorMapBuilder(ModelCase modelCase, String errorText) {
return new HashMap<String, Object>(2) {{
put("caseNo", modelCase.getCaseNo());
put("caseName", modelCase.getCaseName());
put("errorText", errorText);
}};
}
@Override
public R<?> getIndexDetail(String caseId, String indexType, Integer page, Integer size) {
IPage<IndexDetail> iPage = new Page<>(page, size);
iPage = modelCaseMapper.getIndexDetail(iPage, caseId, indexType);
List<IndexDetail> records = iPage.getRecords();
for (IndexDetail record : records) {
String[] array = record.getAtomicIds().split(",");
List<String> atomicIds = Arrays.asList(array);
List<AtomicIndexDTO> atomics = modelCaseMapper.getAtomicDetail(caseId, atomicIds);
record.setChildren(atomics);
}
iPage.setRecords(records);
return R.ok(IPages.buildDataMap(iPage));
}
}

@ -0,0 +1,154 @@
package com.supervision.police.service.impl;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.supervision.common.domain.R;
import com.supervision.common.utils.IPages;
import com.supervision.common.utils.StringUtils;
import com.supervision.police.domain.ComDictionary;
import com.supervision.police.domain.ModelAtomicIndex;
import com.supervision.police.dto.AtomicData;
import com.supervision.police.dto.JudgeLogic;
import com.supervision.police.mapper.ModelAtomicIndexMapper;
import com.supervision.police.mapper.ModelIndexMapper;
import com.supervision.police.domain.ModelIndex;
import com.supervision.police.service.ComDictionaryService;
import com.supervision.police.service.ModelIndexService;
import com.supervision.springaidemo.dto.MetricResultDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* (ModelIndex)
*
* @author qmy
* @since 2024-07-05 09:20:10
*/
@Service
public class ModelIndexServiceImpl extends ServiceImpl<ModelIndexMapper, ModelIndex> implements ModelIndexService {
@Autowired
private ComDictionaryService comDictionaryService;
@Autowired
private ModelIndexMapper modelIndexMapper;
@Autowired
private ModelAtomicIndexMapper modelAtomicIndexMapper;
@Override
public R<?> selectAll(ModelIndex modelIndex, Integer page, Integer size) {
IPage<ModelIndex> iPage = new Page<>(page, size);
LambdaQueryWrapper<ModelIndex> wrapper = Wrappers.lambdaQuery();
wrapper.like(modelIndex.getName() != null, ModelIndex::getName, modelIndex.getName())
.like(modelIndex.getShortName() != null, ModelIndex::getShortName, modelIndex.getShortName())
.like(modelIndex.getRemark() != null, ModelIndex::getRemark, modelIndex.getRemark())
.eq(StringUtils.isNotEmpty(modelIndex.getIndexType()), ModelIndex::getIndexType, modelIndex.getIndexType())
.eq(StringUtils.isNotEmpty(modelIndex.getCaseType()), ModelIndex::getCaseType, modelIndex.getCaseType())
.eq(ModelIndex::getDataStatus, "1");
iPage = modelIndexMapper.selectPage(iPage, wrapper);
List<ModelIndex> records = iPage.getRecords();
List<ComDictionary> dicts = comDictionaryService.list();
for (ModelIndex index : records) {
index.setIndexTypeName(comDictionaryService.getName(dicts, "index_type", index.getIndexType()));
index.setCaseTypeName(comDictionaryService.getName(dicts, "case_type", index.getCaseType()));
//原子指标
String judgeLogic = index.getJudgeLogic();
List<String> ids = new ArrayList<>();
if (StringUtils.isNotEmpty(judgeLogic)) {
List<JudgeLogic> logic = JSONUtil.toList(judgeLogic, JudgeLogic.class);
for (JudgeLogic judge : logic) {
List<AtomicData> atomicData = judge.getAtomicData();
for (AtomicData atomic : atomicData) {
ids.add(atomic.getAtomicIndex());
}
}
List<ModelAtomicIndex> atomicIndexList = modelAtomicIndexMapper.selectBatchIds(ids);
index.setAtomicIndexList(atomicIndexList);
}
index.setAtomicIndexNum(ids.size());
}
iPage.setRecords(records);
return R.ok(IPages.buildDataMap(iPage));
}
@Override
public R<?> addOrUpd(ModelIndex modelIndex) {
int i = 0;
if (StringUtils.isEmpty(modelIndex.getId())) {
i = modelIndexMapper.insert(modelIndex);
} else {
i = modelIndexMapper.updateById(modelIndex);
}
if (i > 0) {
return R.okMsg("保存成功");
} else {
return R.fail("保存失败");
}
}
@Override
public R<?> del(String id) {
ModelIndex index = modelIndexMapper.selectById(id);
index.setDataStatus(StringUtils.getUUID());
int i = modelIndexMapper.updateById(index);
if (i > 0) {
return R.okMsg("删除成功");
} else {
return R.fail("删除失败");
}
}
@Override
public R<?> selectAllAtomic(ModelAtomicIndex modelAtomicIndex, Integer page, Integer size) {
IPage<ModelAtomicIndex> iPage = new Page<>(page, size);
iPage = modelAtomicIndexMapper.selectAll(iPage, modelAtomicIndex);
List<ModelAtomicIndex> records = iPage.getRecords();
List<ComDictionary> dicts = comDictionaryService.list();
for (ModelAtomicIndex index : records) {
index.setCaseTypeName(comDictionaryService.getName(dicts, "case_type", index.getCaseType()));
index.setIndexSourceName(comDictionaryService.getName(dicts, "index_source", index.getIndexSource()));
index.setRecordTypeName(comDictionaryService.getName(dicts, "record_type", index.getRecordType()));
}
iPage.setRecords(records);
return R.ok(IPages.buildDataMap(iPage));
}
@Override
public R<?> addOrUpdAtomic(ModelAtomicIndex modelAtomicIndex) {
int i = 0;
if (StringUtils.isEmpty(modelAtomicIndex.getId())) {
i = modelAtomicIndexMapper.insert(modelAtomicIndex);
} else {
i = modelAtomicIndexMapper.updateById(modelAtomicIndex);
}
if (i > 0) {
return R.okMsg("保存成功");
} else {
return R.fail("保存失败");
}
}
@Override
public R<?> delAtomic(String id) {
ModelAtomicIndex index = modelAtomicIndexMapper.selectById(id);
index.setDataStatus(StringUtils.getUUID());
int i = modelAtomicIndexMapper.updateById(index);
if (i > 0) {
return R.okMsg("删除成功");
} else {
return R.fail("删除失败");
}
}
}

@ -0,0 +1,218 @@
package com.supervision.police.service.impl;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.supervision.common.domain.R;
import com.supervision.neo4j.domain.CaseNode;
import com.supervision.neo4j.domain.Rel;
import com.supervision.neo4j.service.Neo4jService;
import com.supervision.police.domain.ModelRecordType;
import com.supervision.police.domain.NoteRecord;
import com.supervision.police.domain.NotePrompt;
import com.supervision.police.domain.TripleInfo;
import com.supervision.police.mapper.ModelRecordTypeMapper;
import com.supervision.police.mapper.NoteRecordMapper;
import com.supervision.police.mapper.NotePromptMapper;
import com.supervision.police.mapper.TripleInfoMapper;
import com.supervision.police.service.ModelRecordTypeService;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Slf4j
@Service
public class ModelRecordTypeServiceImpl extends ServiceImpl<ModelRecordTypeMapper, ModelRecordType> implements ModelRecordTypeService {
@Autowired
private ModelRecordTypeMapper modelRecordTypeMapper;
@Autowired
private NoteRecordMapper noteRecordMapper;
@Autowired
private NotePromptMapper notePromptMapper;
private final OllamaChatClient chatClient;
@Autowired
public ModelRecordTypeServiceImpl(OllamaChatClient chatClient) {
this.chatClient = chatClient;
}
@Autowired
private TripleInfoMapper tripleInfoMapper;
@Autowired
private Neo4jService neo4jService;
@Override
public R<?> queryType(String name, Integer page, Integer size) {
// IPage<ModelRecordType> iPage = new Page<>(page, size);
// iPage = modelRecordTypeMapper.selectByName(iPage, name);
// return R.ok(IPages.buildDataMap(iPage));
List<ModelRecordType> list = modelRecordTypeMapper.selectByName(name);
for (ModelRecordType modelRecordType : list) {
//笔录内容
List<NoteRecord> noteRecords = noteRecordMapper.selectByRecordType(modelRecordType.getRecordType());
modelRecordType.setRecords(noteRecords);
//提示词
List<NotePrompt> prompts = notePromptMapper.queryPrompt(modelRecordType.getId());
modelRecordType.setPrompts(prompts);
}
return R.ok(list);
// return R.ok(IPages.buildDataMap(iPage));
}
@Override
public ModelRecordType queryByName(String content) {
Wrapper<ModelRecordType> wrapper = new QueryWrapper<ModelRecordType>().eq("record_type", content);
return modelRecordTypeMapper.selectOne(wrapper);
}
@Override
public R<?> saveType(ModelRecordType type) {
String id = type.getId();
int i = 0;
if (StringUtils.isEmpty(id)) {
//新增
i = modelRecordTypeMapper.insert(type);
} else {
i = modelRecordTypeMapper.updateById(type);
}
if (i > 0) {
return R.ok("保存成功");
} else {
return R.fail("保存失败");
}
}
@Override
public R<?> addOrUpdPrompt(NotePrompt prompt) {
int i = 0;
if (StringUtils.isEmpty(prompt.getId())) {
i = notePromptMapper.insert(prompt);
} else {
i = notePromptMapper.updateById(prompt);
}
if (i > 0) {
return R.ok("保存成功");
} else {
return R.fail("保存失败");
}
}
@Override
public R<?> delPrompt(NotePrompt prompt) {
String id = prompt.getId();
int i = notePromptMapper.deleteById(id);
if (i > 0) {
return R.ok("删除成功");
} else {
return R.fail("删除失败");
}
}
@Override
public R<?> getThreeInfo(String caseId, String name, String recordId) {
List<NoteRecord> records = noteRecordMapper.selectRecord(caseId, name, recordId);
List<TripleInfo> tripleInfos = new ArrayList<>();
for (NoteRecord record : records) {
List<NotePrompt> prompts = notePromptMapper.queryPrompt(record.getRecordTypeId());
for (NotePrompt prompt : prompts) {
if (StringUtils.isEmpty(prompt.getPrompt())) {
continue;
}
try {
// 分析三元组
List<Message> messages = new ArrayList<>(List.of(new SystemMessage(prompt.getPrompt() + record.getQuestion() + record.getAnswer())));
Prompt ask = new Prompt(messages);
StopWatch stopWatch = new StopWatch();
stopWatch.start();
log.info("开始分析:");
ChatResponse call = chatClient.call(ask);
stopWatch.stop();
log.info("耗时:{}", stopWatch.getTotalTimeSeconds());
Generation result = call.getResult();
String content = result.getOutput().getContent();
log.info("分析的结果是:{}", content);
JSONObject jsonObject = new JSONObject(content);
JSONArray threeInfo = jsonObject.getJSONArray("result");
for (int i = 0; i < threeInfo.length(); i++) {
JSONObject object = threeInfo.getJSONObject(i);
String startNodeType = object.getString("startNodeType");
String entity = object.getString("entity");
String endNodeType = object.getString("endNodeType");
String property = object.getString("property");
String value = object.getString("value");
//去空
if (StringUtils.isEmpty(startNodeType) || StringUtils.isEmpty(entity) || StringUtils.isEmpty(endNodeType)
|| StringUtils.isEmpty(property) || StringUtils.isEmpty(value)) {
continue;
}
TripleInfo tripleInfo = new TripleInfo(entity, property, value, record.getId(), new Date(), startNodeType, endNodeType);
tripleInfoMapper.insert(tripleInfo);
tripleInfos.add(tripleInfo);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return R.ok(tripleInfos);
}
@Override
public R<?> addNeo4j(List<String> ids) {
List<TripleInfo> tripleInfos = tripleInfoMapper.selectByIds(ids);
int i = 0;
for (TripleInfo tripleInfo : tripleInfos) {
try {
//开始节点
String start = tripleInfo.getStartNode();
CaseNode startNode = neo4jService.findOneByName(tripleInfo.getCaseId(), tripleInfo.getNoteRecordsId(), tripleInfo.getStartNodeType(), start, "1");
if (startNode == null) {
startNode = new CaseNode(start, tripleInfo.getStartNodeType(), tripleInfo.getNoteRecordId(), tripleInfo.getNoteRecordsId(), tripleInfo.getCaseId(), "1");
CaseNode save = (CaseNode) neo4jService.save(startNode).getData();
startNode.setId(save.getId());
}
//结束节点
String end = tripleInfo.getEndNode();
CaseNode endNode = neo4jService.findOneByName(tripleInfo.getCaseId(), tripleInfo.getNoteRecordsId(), tripleInfo.getEndNodeType(), end, "1");
if (endNode == null) {
endNode = new CaseNode(end, tripleInfo.getEndNodeType(), tripleInfo.getNoteRecordId(), tripleInfo.getNoteRecordsId(), tripleInfo.getCaseId(), "1");
CaseNode save = (CaseNode) neo4jService.save(endNode).getData();
endNode.setId(save.getId());
}
//关系
Rel rel = new Rel(startNode.getId(), tripleInfo.getRelation(), endNode.getId());
Rel relation = neo4jService.findRelation(rel);
if (relation == null) {
R<?> r = neo4jService.saveRelation(rel);
}
tripleInfo.setAddNeo4j("1");
int j = tripleInfoMapper.updateById(tripleInfo);
if (j > 0) {
i++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return R.ok("成功插入" + i + "条信息");
}
}

@ -0,0 +1,185 @@
package com.supervision.police.service.impl;
import cn.hutool.json.JSONUtil;
import com.supervision.common.domain.R;
import com.supervision.common.utils.StringUtils;
import com.supervision.neo4j.dto.ResultDTO;
import com.supervision.neo4j.utils.Neo4jUtils;
import com.supervision.police.domain.*;
import com.supervision.police.dto.AnalyseCaseDTO;
import com.supervision.police.dto.AtomicData;
import com.supervision.police.dto.JudgeLogic;
import com.supervision.police.mapper.*;
import com.supervision.police.service.ModelService;
import org.neo4j.driver.Driver;
import org.neo4j.driver.Result;
import org.neo4j.driver.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
public class ModelServiceImpl implements ModelService {
@Autowired
private ModelCaseMapper modelCaseMapper;
@Autowired
private ModelAtomicIndexMapper modelAtomicIndexMapper;
private final Driver driver;
@Autowired
private ModelServiceImpl(Driver driver) {
this.driver = driver;
}
@Autowired
private ModelAtomicResultMapper modelAtomicResultMapper;
@Autowired
private ModelIndexMapper modelIndexMapper;
@Autowired
private ModelIndexResultMapper modelIndexResultMapper;
@Override
public R<?> analyseCase(AnalyseCaseDTO analyseCaseDTO) {
ModelCase modelCase = modelCaseMapper.selectById(analyseCaseDTO.getCaseId());
//原子指标
List<ModelAtomicIndex> atomicIndices = modelAtomicIndexMapper.selectByCaseType(modelCase.getCaseType());
Map<String, Boolean> atomic = new HashMap<>();
for (ModelAtomicIndex atomicIndex : atomicIndices) {
//原子指标结果
ModelAtomicResult result = new ModelAtomicResult();
result.setCaseId(analyseCaseDTO.getCaseId());
result.setAtomicId(atomicIndex.getId());
//查询语句
String ql = atomicIndex.getQueryLang();
Map<String, Object> params = new HashMap<>();
params.put("lawActor", analyseCaseDTO.getLawActor());
params.put("caseId", analyseCaseDTO.getCaseId());
//原子指标结果表
try {
// index_source==1
List<ModelAtomicIndex> list = analyseCaseDTO.getAtomicIndexList();
//index_source==3
Session session = driver.session();
//查询图谱 index_source: 1人工定义 2数据库查询 3图谱生成 4大模型
if ("1".endsWith(atomicIndex.getIndexSource())) {
// list
} else if ("2".endsWith(atomicIndex.getIndexSource()) && StringUtils.isNotEmpty(ql)) {
//
} else if ("3".endsWith(atomicIndex.getIndexSource()) && StringUtils.isNotEmpty(ql)) {
//图谱
int i = 1;
String lawPartys = analyseCaseDTO.getLawParty();
String[] split = StringUtils.isEmpty(lawPartys) ? new String[0] : lawPartys.split(",");
if (ql.contains("$lawParty") && split.length > 1) {
i = split.length;
}
for (int j = 0; j < i; j++) {
if (split.length > 0) {
params.put("lawParty", split[j]);
}
Result run = session.run(ql, params);
List<ResultDTO> res = Neo4jUtils.getResultDTOList(run);
if (res.isEmpty()) {
result.setAtomicResult("-1");
} else {
ResultDTO resultDTO = res.get(0);
if (StringUtils.isNotEmpty(resultDTO.getRelId())) {
//存在关系
result.setAtomicResult("1");
result.setRecordId(resultDTO.getRecordId());
result.setRecordsId(resultDTO.getRecordsId());
break;
} else {
result.setAtomicResult("0");
}
}
}
} else if ("4".endsWith(atomicIndex.getIndexSource())) {
//
}
} catch (Exception e) {
e.printStackTrace();
}
//保存原子指标结果表
ModelAtomicResult exist = modelAtomicResultMapper.selectByCaseIdAndAtomicId(analyseCaseDTO.getCaseId(), atomicIndex.getId());
if (exist == null) {
modelAtomicResultMapper.insert(result);
} else {
result.setId(exist.getId());
modelAtomicResultMapper.updateById(result);
}
// 所有原子指标id
atomic.put(result.getAtomicId(), "1".equals(result.getAtomicResult()));
}
// 计算指标结果
int score = 0;
List<ModelIndex> modelIndices = modelIndexMapper.selectByCaseType(modelCase.getCaseType());
for (ModelIndex modelIndex : modelIndices) {
ModelIndexResult result = new ModelIndexResult();
result.setCaseId(analyseCaseDTO.getCaseId());
result.setIndexId(modelIndex.getId());
Set<String> atomicIds = new HashSet<>();
if (StringUtils.isNotEmpty(modelIndex.getJudgeLogic())) {
List<JudgeLogic> judgeLogics = JSONUtil.toList(modelIndex.getJudgeLogic(), JudgeLogic.class);
boolean res = false;
for (int i = 0; i < judgeLogics.size(); i++) {
boolean group = false;
JudgeLogic logic = judgeLogics.get(i);
String rowLogic = logic.getRowLogic();
List<AtomicData> atomicData = logic.getAtomicData();
for (int j = 0; j < atomicData.size(); j++) {
AtomicData data = atomicData.get(j);
atomicIds.add(data.getAtomicIndex());
Boolean ato = atomic.get(data.getAtomicIndex());
String relationalSymbol = data.getRelationalSymbol();
if ("2".equals(relationalSymbol) || "4".equals(relationalSymbol) || "5".equals(relationalSymbol)) {
ato = !ato;
}
if (j == 0) {
group = ato;
} else {
if ("1".equals(rowLogic)) {
group = group && ato;
} else if ("2".equals(rowLogic)) {
group = group || ato;
}
}
}
String groupLogic = logic.getGroupLogic();
if (i == 0) {
res = group;
} else {
if ("1".equals(groupLogic)) {
res = res && group;
} else if ("2".equals(groupLogic)) {
res = res || group;
}
}
}
result.setIndexResult(res? "true" : "false");
result.setAtomicIds(StringUtils.join(atomicIds, ","));
}
ModelIndexResult exist = modelIndexResultMapper.selectByCaseIdAndIndexId(analyseCaseDTO.getCaseId(), modelIndex.getId());
if (exist == null) {
modelIndexResultMapper.insert(result);
} else {
result.setId(exist.getId());
modelIndexResultMapper.updateById(result);
}
if ("true".equals(result.getIndexResult())) {
score = score + modelIndex.getIndexScore();
}
}
modelCase.setTotalScore(score);
modelCaseMapper.updateById(modelCase);
return R.ok();
}
}

@ -0,0 +1,22 @@
package com.supervision.police.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.supervision.springaidemo.domain.NoteCheckRecord;
import com.supervision.police.service.NoteCheckRecordService;
import com.supervision.police.mapper.NoteCheckRecordMapper;
import org.springframework.stereotype.Service;
/**
* @author flevance
* @description note_check_record()Service
* @createDate 2024-05-11 15:47:02
*/
@Service
public class NoteCheckRecordServiceImpl extends ServiceImpl<NoteCheckRecordMapper, NoteCheckRecord>
implements NoteCheckRecordService{
}

@ -0,0 +1,228 @@
package com.supervision.police.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.supervision.common.domain.R;
import com.supervision.common.utils.IPages;
import com.supervision.common.utils.ListUtils;
import com.supervision.common.utils.StringUtils;
import com.supervision.minio.domain.MinioFile;
import com.supervision.minio.mapper.MinioFileMapper;
import com.supervision.minio.service.MinioService;
import com.supervision.police.domain.ModelCase;
import com.supervision.police.domain.ModelRecordType;
import com.supervision.police.domain.NoteRecord;
import com.supervision.police.domain.NoteRecords;
import com.supervision.police.mapper.ModelCaseMapper;
import com.supervision.police.mapper.ModelRecordTypeMapper;
import com.supervision.police.mapper.NoteRecordMapper;
import com.supervision.police.mapper.NoteRecordsMapper;
import com.supervision.police.service.RecordService;
import com.supervision.springaidemo.dto.QARecordNodeDTO;
import com.supervision.springaidemo.util.RecordRegexUtil;
import com.supervision.springaidemo.util.WordReadUtil;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StopWatch;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
@Service
public class RecordServiceImpl extends ServiceImpl<NoteRecordMapper, NoteRecord> implements RecordService {
@Autowired
private NoteRecordMapper noteRecordMapper;
@Autowired
private NoteRecordsMapper noteRecordsMapper;
@Autowired
private MinioService minioService;
@Autowired
private ModelCaseMapper modelCaseMapper;
@Autowired
private MinioFileMapper minioFileMapper;
private final OllamaChatClient chatClient;
@Autowired
public RecordServiceImpl(OllamaChatClient chatClient) {
this.chatClient = chatClient;
}
@Autowired
private ModelRecordTypeMapper modelRecordTypeMapper;
@Override
// @Transactional(rollbackFor = Exception.class)
public R<?> uploadRecords(NoteRecords records, List<MultipartFile> fileList) throws IOException {
//上传文件获取文件ids
List<String> fileIds = new ArrayList<>();
for (MultipartFile file : fileList) {
String fileId = minioService.uploadFile(file);
fileIds.add(fileId);
}
if (StringUtils.isNotEmpty(records.getFileIds())) {
records.setFileIds(records.getFileIds() + "," + StringUtils.join(fileIds, ","));
} else {
records.setFileIds(StringUtils.join(fileIds, ","));
}
//修改案件的行为人、当事人
if (StringUtils.isNotEmpty(records.getRole()) && !"嫌疑人".equals(records.getRole())) {
ModelCase modelCase = modelCaseMapper.selectById(records.getCaseId());
//行为人
if ("行为人".equals(records.getRole()) && StringUtils.isEmpty(modelCase.getLawActor())) {
modelCase.setLawActor(records.getName());
modelCaseMapper.updateById(modelCase);
} else if ("受害人".equals(records.getRole()) || "证人".equals(records.getRole())) {
if (StringUtils.isEmpty(modelCase.getLawParty())) {
modelCase.setLawParty(records.getName());
} else {
String[] split = modelCase.getLawParty().split(",");
if (!Arrays.asList(split).contains(records.getName())) {
modelCase.setLawParty(modelCase.getLawParty() + "," + records.getName());
}
}
modelCaseMapper.updateById(modelCase);
}
}
int i = 0;
if (StringUtils.isEmpty(records.getId())) {
i = noteRecordsMapper.insert(records);
} else {
i = noteRecordsMapper.updateById(records);
}
//所有对话类型
List<String> allTypes = modelRecordTypeMapper.getAllType();
if (i > 0) {
//拆分笔录
for (MultipartFile file : fileList) {
String context = WordReadUtil.readWord(file);
List<QARecordNodeDTO> qaList = RecordRegexUtil.recordRegex(context, records.getName());
for (QARecordNodeDTO qa : qaList) {
try {
NoteRecord noteRecord = new NoteRecord();
noteRecord.setCaseId(records.getCaseId());
noteRecord.setNoteRecordsId(records.getId());
noteRecord.setNoteName(file.getName());
noteRecord.setPersonName(records.getName());
noteRecord.setQuestion(qa.getQuestion());
noteRecord.setAnswer(qa.getAnswer());
noteRecord.setCreateTime(new Date());
String test = "分类任务: 对话笔记录文本分类。目标: 将给定的对话笔记录分配到预定义的类别中,这些类别包括但不限于: " + allTypes.toString() + "。";
String example = "说明: 提供一段对话笔记录文本,分类器应该识别出对话的主题,并将其归类到上述类别中的一个。" +
"示例输入: 文本: \"办案警官问你为了骗取更多的钱都做了哪些准备。裴金禄回答我刚开始我就是自己想了一些关于骗钱的点子后面为了更不容易让别人识破我为了更佳逼真我就从网上随便搜了一家租赁公司我就搜到了兰州胜利机械租赁有限公司我又想到了我管理的中铁北京局和中铁电气化局施工公司。我先是通过百度搜索了“办证”之后就在网页上面弹出了一个页面上面有一个QQ号我就加上了。加上之后我就将我的要求给他说了要求他给我刻两个假的公章一个是兰州胜利机械租赁有限公司合同专用章另一个是中铁北京局集团有限公司合同专用章。我还要求他给我伪造了一张兰州胜利机械租赁有限公司的营业执照\"" +
"预期输出: { type: '诈骗准备' }" +
"任务要求: " +
"1. 分类器应当准确地识别对话的主题。 " +
"2. 如果一段对话笔记录包含多个主题,请选择最相关的类别。" +
"3. 必须考虑上下文语境和专业术语来确定正确的分类。";
String end = "对话内容为:";
List<Message> messages = new ArrayList<>(List.of(new SystemMessage(test + example + end + qa.getQuestion() + qa.getAnswer())));
Prompt prompt = new Prompt(messages);
StopWatch stopWatch = new StopWatch();
stopWatch.start();
log.info("开始分析:");
ChatResponse call = chatClient.call(prompt);
stopWatch.stop();
log.info("耗时:{}", stopWatch.getTotalTimeSeconds());
Generation result = call.getResult();
String content = result.getOutput().getContent();
log.info("问:{}, 答:{}", qa.getQuestion(), qa.getAnswer());
log.info("分析的结果是:{}", content);
JSONObject jsonObject = new JSONObject(content);
String type = jsonObject.getString("type").trim();
System.out.println("问:" + qa.getQuestion() + "答:" + qa.getAnswer());
System.out.println("分析的结果是:" + type);
/* // todo 写死测试
String type = "";
if (qa.getQuestion().contains("你为了骗取更多的钱都做了哪些准备")) {
type = "诈骗准备";
} else {
continue;
}*/
//保存笔录
noteRecord.setRecordType(type);
noteRecordMapper.insert(noteRecord);
} catch (Exception e) {
e.printStackTrace();
}
// ModelRecordType exist = modelRecordTypeMapper.queryByName(type);
// if (exist == null) {
// ModelRecordType modelRecordType = new ModelRecordType();
// modelRecordType.setRecordType(type);
// modelRecordTypeMapper.insert(modelRecordType);
// }
}
}
return R.okMsg("保存成功");
} else {
return R.fail("保存笔录失败");
}
}
@Override
public R<?> queryRecords(NoteRecords noteRecords, Integer page, Integer size) {
LambdaQueryWrapper<NoteRecords> wrapper = Wrappers.lambdaQuery();
wrapper.like(StringUtils.isNotEmpty(noteRecords.getName()), NoteRecords::getName, noteRecords.getName())
.eq(NoteRecords::getCaseId, noteRecords.getCaseId())
.eq(NoteRecords::getDataStatus, "1");
List<NoteRecords> list = noteRecordsMapper.selectList(wrapper);
// LinkedHashMap 保障顺序
Map<String, List<NoteRecords>> nameMap = list.stream().filter(item -> StringUtils.isNotBlank(item.getName()))
.collect(Collectors.groupingBy(NoteRecords::getName, LinkedHashMap::new, Collectors.toList()));
List<NoteRecords> res = new ArrayList<>();
for (String name : nameMap.keySet()) {
NoteRecords noteRecord = new NoteRecords();
noteRecord.setName(name);
noteRecord.setChildren(nameMap.get(name));
res.add(noteRecord);
}
List<NoteRecords> pager = ListUtils.Pager(size, page, res);
for (NoteRecords person : pager) {
for (NoteRecords noteRecord : person.getChildren()) {
String fileIds = noteRecord.getFileIds();
if (StringUtils.isNotEmpty(fileIds)) {
noteRecord.setConfessionMaterial(fileIds.split(",").length);
}
}
}
return R.ok(IPages.buildDataMap(pager, res.size()));
}
@Override
public R<?> delRecords(String id) {
NoteRecords noteRecords = noteRecordsMapper.selectById(id);
noteRecords.setDataStatus(StringUtils.getUUID());
noteRecordsMapper.updateById(noteRecords);
String fileIds = noteRecords.getFileIds();
if (StringUtils.isNotEmpty(fileIds)) {
//删除文件
for (String fileId : fileIds.split(",")) {
MinioFile minioFile = minioFileMapper.selectById(fileId);
minioFile.setDataStatus(StringUtils.getUUID());
minioFileMapper.updateById(minioFile);
minioService.delFile(fileId);
}
}
return R.ok();
}
}

@ -0,0 +1,336 @@
package com.supervision.springaidemo.controller;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.supervision.springaidemo.domain.ModelMetric;
import com.supervision.springaidemo.domain.NoteCheckRecord;
import com.supervision.springaidemo.dto.MetricResultDTO;
import com.supervision.springaidemo.service.ModelMetricService;
import com.supervision.police.service.NoteCheckRecordService;
import com.supervision.springaidemo.thread.RunCheckThread;
import com.supervision.springaidemo.thread.RunCheckThreadPool;
import com.supervision.springaidemo.util.WordReadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.BufferedReader;
import java.io.File;
import java.util.*;
@RestController
@Slf4j
public class ChatController {
private final OllamaChatClient chatClient;
@Autowired
private ModelMetricService modelMetricService;
@Autowired
private NoteCheckRecordService noteCheckRecordService;
// 使用多线程进行提交
@Autowired
public ChatController(OllamaChatClient chatClient) {
this.chatClient = chatClient;
}
@GetMapping("/ai/chat")
public void generate() {
String template = """
["XXX给我转来的钱。","我收到过XXX给我转来的钱","我通过银行给XXX转了钱"]
,;10,10!
json:{"behavior":[""],"victim":[""]}
""";
Prompt prompt = new Prompt(List.of(new UserMessage(template)));
ChatResponse call = chatClient.call(prompt);
Generation result = call.getResult();
String content = result.getOutput().getContent();
log.info(content);
}
private Message buildMessage(Map<String, Object> param) {
String messageTemplate = """
---
---
:
---
198064222613519
202203233西85使33退22020诿3
403
2035122
20诿2022
西
84211
3707818J
178
20220116016
---
,,:,
1.:{metricName}
2.:true({metricTrueDesc})/false({metricFalseDesc}),true/false
3.:,()
4.:,,
json, JSONvalue,:
---
{"metricName":"指标名称", "result":"结论", "originalContext":"笔录对应原话","reason":"原因"}
---
""";
String format = StrUtil.format(messageTemplate, param);
return new UserMessage(format);
}
@GetMapping("/ai/run")
public void run() {
var list = modelMetricService.list();
for (ModelMetric modelMetric : list) {
Map<String, Object> param = new HashMap<>();
param.put("metricTrueDesc", modelMetric.getMetricTrueDesc());
param.put("metricFalseDesc", modelMetric.getMetricFalseDesc());
param.put("metricName", modelMetric.getMetricName());
Message message = buildMessage(param);
Prompt prompt = new Prompt(List.of(new SystemMessage("所有的回复以简体中文回答。请以step by step的方式进行。step1:理解笔录设计人员的身份信息;step2:根据笔录的内容分析案件之间的逻辑关系和关联;step3:判断给定的指标是否满足。step4:根据要求的给定格式进行回复"), message));
log.info("prompt:{}", prompt.toString());
ChatResponse call = chatClient.call(prompt);
Generation result = call.getResult();
String content = result.getOutput().getContent();
log.info(content);
}
}
private static final String template = """
step by step,
step1:;
---
:{actionUserNameList}
{suspectUserNameList}
{victimUserNameList}
{witnessNameList}
---
step2:;
,"问","答"{noteUserName}:
---
{context}
---
step3::
:{metricName}
:
({metricTrueDesc}),true;
({metricFalseDesc}),false;
,,empty
step4:,:
1.:true/false/empty
2.:,()true,!
3.:,,true/false,!
step5:json, JSONvalue,:
---
{"result":"结论", "originalContext":"笔录对应原话","reason":"原因"}
---
,!
""";
@GetMapping("runNoteCheck")
public void runNoteCheck() {
HashMap<String, String> map = new HashMap<>();
map.put("杨学明", "/Users/flevance/Desktop/宁夏审讯大模型/陈恩明合同诈骗/受害人杨学明询问笔录.docx");
map.put("朱文泽", "/Users/flevance/Desktop/宁夏审讯大模型/陈恩明合同诈骗/受害人朱文泽询问笔录.docx");
map.put("陈恩明", "/Users/flevance/Desktop/宁夏审讯大模型/陈恩明合同诈骗/嫌疑人陈恩明讯问笔录.docx");
map.put("武桂清1", "/Users/flevance/Desktop/宁夏审讯大模型/陈恩明合同诈骗/嫌疑人武桂清讯问笔录1.docx");
map.put("武桂清2", "/Users/flevance/Desktop/宁夏审讯大模型/陈恩明合同诈骗/嫌疑人武桂清讯问笔录2.docx");
for (Map.Entry<String, String> entry : map.entrySet()) {
String context = WordReadUtil.readWord(entry.getValue());
List<String> actionUserNameList = new ArrayList<>();
actionUserNameList.add("陈恩明");
actionUserNameList.add("武桂清");
List<String> victimUserNameList = new ArrayList<>();
victimUserNameList.add("漫旭昌");
victimUserNameList.add("杨学明");
victimUserNameList.add("朱文泽");
var list = modelMetricService.list();
for (ModelMetric modelMetric : list) {
// 没有跑过的,才继续跑
Long count = noteCheckRecordService.lambdaQuery().eq(NoteCheckRecord::getPersonName, entry.getKey()).eq(NoteCheckRecord::getMetricCode, modelMetric.getMetricCode()).count();
if (count < 1) {
Map<String, Object> param = new HashMap<>();
param.put("actionUserNameList", CollUtil.join(actionUserNameList, ";"));
param.put("victimUserNameList", CollUtil.join(victimUserNameList, ";"));
param.put("witnessNameList", "无");
param.put("noteUserName", entry.getKey());
param.put("context", context);
param.put("metricName", modelMetric.getMetricName());
param.put("metricTrueDesc", modelMetric.getMetricTrueDesc());
param.put("metricFalseDesc", modelMetric.getMetricFalseDesc());
String format = StrUtil.format(template, param);
Message message = new UserMessage(format);
Prompt prompt = new Prompt(List.of(new SystemMessage("所有的回复以简体中文回答。请以step by step的方式进行。step1:理解笔录设计人员的身份信息;step2:根据笔录的内容分析案件之间的逻辑关系和关联;step3:根据给定的指标,提取出来可能涉及的笔录内容文本;step4:根据该笔录内容判断给定的指标是否满足。step5:根据要求的给定格式进行回复"), message));
log.info("prompt:{}", prompt);
ChatResponse call = chatClient.call(prompt);
Generation result = call.getResult();
String content = result.getOutput().getContent();
log.info(content);
MetricResultDTO metricResultDTO = JSONUtil.toBean(content, MetricResultDTO.class);
NoteCheckRecord noteCheckRecord = new NoteCheckRecord();
noteCheckRecord.setPersonName(entry.getKey());
noteCheckRecord.setNoteName(FileUtil.getName(entry.getValue()));
noteCheckRecord.setType(entry.getKey().contains("询问") ? "询问" : "讯问");
noteCheckRecord.setMetricCode(modelMetric.getMetricCode());
noteCheckRecord.setMetricName(modelMetric.getMetricName());
noteCheckRecord.setResult(metricResultDTO.getResult());
noteCheckRecord.setOriginalContext(metricResultDTO.getOriginalContext());
noteCheckRecord.setReason(metricResultDTO.getReason());
noteCheckRecordService.save(noteCheckRecord);
}
}
}
}
/**
* word
*/
@GetMapping("runCheck")
public void runCheck() {
// List<String> metricCodeList = ListUtil.list(false, "RZ010", "RZ019", "RZ020", "RZ022");
// 行为人
List<String> actionUserNameList = ListUtil.list(false, "裴金禄");
// 犯罪嫌疑人
List<String> suspectUserNameList = ListUtil.list(false, "裴金禄", "景涛", "李世怀", "万学宝");
// 受害人
List<String> victimUserNameList = ListUtil.list(false, "董金才", "吕加国", "吕志仓");
// 证人
List<String> witnessNameList = ListUtil.list(false, "白鹏", "丁建华", "雷建贵", "雷建明", "李泽懿", "王存良", "王开阔", "吴尚军", "杨正福", "叶魁伍", "赵景宝");
// 获取目录下的所有笔录信息
List<File> files = FileUtil.loopFiles("/Users/flevance/Desktop/宁夏审讯大模型/裴金禄/行为人和受害人/");
for (File file : files) {
// 只跑裴金禄的笔录
log.info("开始分析:{}的笔录", file.getName());
String context = WordReadUtil.readWord(file.getPath());
// List<ModelMetric> list = modelMetricService.lambdaQuery().in(ModelMetric::getMetricCode, metricCodeList).list();
List<ModelMetric> list = modelMetricService.list();
for (ModelMetric modelMetric : list) {
Map<String, Object> param = new HashMap<>();
param.put("actionUserNameList", CollUtil.join(actionUserNameList, ";"));
param.put("suspectUserNameList", CollUtil.join(suspectUserNameList, ";"));
param.put("victimUserNameList", CollUtil.join(victimUserNameList, ";"));
param.put("witnessNameList", CollUtil.join(witnessNameList, ";"));
param.put("context", context);
param.put("metricName", modelMetric.getMetricName());
param.put("metricTrueDesc", modelMetric.getMetricTrueDesc());
param.put("metricFalseDesc", modelMetric.getMetricFalseDesc());
String format = StrUtil.format(template, param);
List<Message> userMessageList = new ArrayList<>();
log.info("开始提交分析,prompt长度为:{}", format.length());
// 如果超过8000字,就进行截断,每次以6000字进行提交
if (format.length() > 8000) {
log.info("分段提交");
for (String s : StrUtil.split(format, 6000)) {
userMessageList.add(new UserMessage(s));
userMessageList.add(new AssistantMessage("继续"));
}
userMessageList.remove(userMessageList.size() - 1);
} else {
userMessageList.add(new UserMessage(format));
}
String systemPrompt = """
,,,,,
""";
List<Message> messages = new ArrayList<>(List.of(new SystemMessage(systemPrompt)));
messages.addAll(userMessageList);
Prompt prompt = new Prompt(messages);
RunCheckThread runCheck = new RunCheckThread("裴金禄第五次",chatClient, noteCheckRecordService, prompt, file.getName(), format, systemPrompt, modelMetric, 0);
RunCheckThreadPool.chatExecutor.submit(runCheck);
}
}
}
@GetMapping("testLongText")
public void testLongText() {
StringBuilder stringBuilder = new StringBuilder();
BufferedReader utf8Reader = FileUtil.getUtf8Reader("/Users/flevance/Desktop/宁夏审讯大模型/了不起的盖茨比 .txt");
utf8Reader.lines().forEach(stringBuilder::append);
String template = """
,:
---
{context}
---
,8,..json
""";
String systemPrompt = """
,,.
""";
Map<String, Object> param = new HashMap<>();
log.info("大小是:{}", stringBuilder.length());
param.put("context", stringBuilder.toString());
String format = StrUtil.format(template, param);
List<Message> userMessageList = new ArrayList<>();
for (String s : StrUtil.split(format, 6000)) {
userMessageList.add(new UserMessage(s));
userMessageList.add(new AssistantMessage("继续"));
}
userMessageList.remove(userMessageList.size() - 1);
List<Message> messages = new ArrayList<>(List.of(new SystemMessage(systemPrompt)));
messages.addAll(userMessageList);
Prompt prompt = new Prompt(messages);
ChatResponse call = chatClient.call(prompt);
Generation result = call.getResult();
String content = result.getOutput().getContent();
log.info("分析的结果是:{}", content);
}
}

@ -0,0 +1,256 @@
package com.supervision.springaidemo.controller;
import cn.hutool.core.io.FileUtil;
import com.supervision.police.domain.ModelRecordType;
import com.supervision.police.domain.NoteRecord;
import com.supervision.springaidemo.dto.QARecordNodeDTO;
import com.supervision.police.mapper.ModelRecordTypeMapper;
import com.supervision.police.mapper.NoteRecordMapper;
import com.supervision.police.service.ModelRecordTypeService;
import com.supervision.springaidemo.service.ModelMetricService;
import com.supervision.police.service.RecordService;
import com.supervision.police.service.NoteCheckRecordService;
import com.supervision.springaidemo.util.RecordRegexUtil;
import com.supervision.springaidemo.util.WordReadUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.json.JSONObject;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
/**
* ,
*/
@RestController
@Slf4j
@RequestMapping("exampleChat")
public class ExampleChatController {
private final OllamaChatClient chatClient;
@Autowired
private ModelMetricService modelMetricService;
@Autowired
private NoteCheckRecordService noteCheckRecordService;
@Autowired
private ModelRecordTypeMapper modelRecordTypeMapper;
@Autowired
private NoteRecordMapper noteRecordMapper;
@Autowired
public ExampleChatController(OllamaChatClient chatClient) {
this.chatClient = chatClient;
}
@Autowired
private RecordService recordService;
@Autowired
private ModelRecordTypeService modelRecordTypeService;
private static final String exampleTemplate = """
step by step,
step1:;
:
---
{context}
---
step2::
:
:{metricName}
true:{example};
false;
,,,empty
step3:,:
1.:true/false/empty
2.:,()true,!
3.:,,true/false,!
step4:json, JSONvalue,:
---
{"result":"结论", "originalContext":"笔录对应原话","reason":"原因"}
---
,!
""";
@GetMapping("exampleChat")
public void exampleChat() {
File file = FileUtil.file("E:\\jc\\宁夏\\Fw_裴金禄\\裴金禄第一次.docx");
String context = WordReadUtil.readWord(file.getPath());
List<QARecordNodeDTO> qaList = RecordRegexUtil.recordRegex(context, "裴金禄");
for (QARecordNodeDTO qa : qaList) {
NoteRecord noteRecord = new NoteRecord();
noteRecord.setNoteName(file.getName());
noteRecord.setPersonName("裴金禄");
noteRecord.setQuestion(qa.getQuestion());
noteRecord.setAnswer(qa.getAnswer());
noteRecord.setCreateTime(new Date());
// if (qa.getAnswer().length() > 500) {
// continue;
// }
//根据提示词分析类型 并保存
// String test = "你现在是一个笔录分析人员,请用四个字描述一下下述内容属于哪种类型的对话?";
String test = "你是一个善于归纳分析问讯笔录的大模型,请用四个字描述下述内容属于哪种类型的对话?对话内容为:";
String tip = "你的回答必须严格控制为四个字。";
String example = "示例1办案警官问:我们是中卫市公安局沙坡头区分局经侦大队的民警(出示工作证件),现依法对你进行讯问,你应当如实回答我们的提问,对与案件无关的问题,你有拒绝回答的权利。你听明白了吗? 张某答:听明白了。回复:{\"type\":\"权利义务\"}。" +
"示例2办案警官问你的个人情况张某答我叫裴金禄1984年01月10日出生藏族大学文化户籍所在地陕西省西安市雁塔区丈八四路6号7号楼1单元 2304室现住陕西省西安市雁塔区丈八四路6号7号楼1单元 2304室无业居民身份证号码622326198401100090联系电话15829319393。回复{\"type\":\"个人情况\"}。" +
"示例3办案警官问你的家庭情况张某答我父亲叫裴国智今年67岁退休电话13519353723; 母亲李金芬今年61岁无业我弟弟裴金生今年 34岁在中石油运输公司上班。回复{\"type\":\"家庭情况\"}。";
List<Message> messages = new ArrayList<>(List.of(new SystemMessage(test + qa.getQuestion() + qa.getAnswer() + tip + example)));
Prompt prompt = new Prompt(messages);
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// log.info("开始分析:");
ChatResponse call = chatClient.call(prompt);
stopWatch.stop();
// log.info("耗时:{}", stopWatch.getTotalTimeSeconds());
Generation result = call.getResult();
String content = result.getOutput().getContent();
// log.info("问:{}, 答:{}", qa.getQuestion(), qa.getAnswer());
// log.info("分析的结果是:{}", content);
JSONObject jsonObject = new JSONObject(content);
String type = jsonObject.getString("type").trim();
System.out.println("问:"+qa.getQuestion()+"答:"+qa.getAnswer());
System.out.println("分析的结果是:"+ type);
//保存笔录
noteRecord.setRecordType(type);
recordService.save(noteRecord);
ModelRecordType exist = modelRecordTypeService.queryByName(type);
if (exist == null) {
ModelRecordType modelRecordType = new ModelRecordType();
modelRecordType.setRecordType(type);
modelRecordTypeService.save(modelRecordType);
}
}
// for (QARecordNodeDTO qaRecordNodeDTO : qaList) {
// // 只查入罪指标
// List<ModelMetric> list = modelMetricService.lambdaQuery().likeRight(ModelMetric::getMetricCode, "RZ").list();
// for (ModelMetric modelMetric : list) {
// String systemPrompt = """
// 你是一个善于分析办案笔录的模型,能够根据办案笔录的回答内容,结合给定的例子,实事求是的判断给定指标是否满足。注意,仅根据笔录进行分析,不要做笔录之外的推断。笔录内容可能比较长,可能分多次提交给你。Think step by step
// """;
// List<Message> messages = new ArrayList<>(List.of(new SystemMessage(systemPrompt)));
// Map<String, Object> param = new HashMap<>();
// param.put("context", qaRecordNodeDTO.toString());
// param.put("metricName", modelMetric.getMetricName());
// param.put("example", StrUtil.format(modelMetric.getExample(), MapUtil.of("action", "裴金禄")));
// String format = StrUtil.format(exampleTemplate, param);
// List<Message> userMessageList = new ArrayList<>();
// if (format.length() > 8000) {
// log.info("分段提交");
// for (String s : StrUtil.split(format, 6000)) {
// userMessageList.add(new UserMessage(s));
// userMessageList.add(new AssistantMessage("继续"));
// }
// userMessageList.remove(userMessageList.size() - 1);
// } else {
// userMessageList.add(new UserMessage(format));
// }
// messages.addAll(userMessageList);
//
// RunCheckThread runCheck = new RunCheckThread("裴金禄尝试正则来做", chatClient, noteCheckRecordService, new Prompt(messages), FileUtil.getName(file), format, systemPrompt, modelMetric, 0);
// RunCheckThreadPool.chatExecutor.submit(runCheck);
// }
// }
}
@GetMapping("test")
public List test(@Param("test") String test) {
List<Map> list = new ArrayList<>();
List<Message> messages = new ArrayList<>(List.of(new SystemMessage(test)));
Prompt prompt = new Prompt(messages);
StopWatch stopWatch = new StopWatch();
stopWatch.start();
log.info("开始分析:");
ChatResponse call = chatClient.call(prompt);
stopWatch.stop();
log.info("耗时:{}", stopWatch.getTotalTimeSeconds());
Generation result = call.getResult();
String content = result.getOutput().getContent();
log.info("分析的结果是:{}", content);
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("result", content);
list.add(resultMap);
return list;
}
@GetMapping("queryRecordType")
public List<NoteRecord> queryRecordType() {
List<ModelRecordType> types = modelRecordTypeMapper.selectList(null);
String allType = types.stream().map(ModelRecordType::getRecordType).collect(Collectors.joining("."));
List<NoteRecord> list = noteRecordMapper.selectList(null);
for (NoteRecord record : list) {
record.setRecordType("");
String test = "你是一个善于总结问讯内容的大模型,请判断以下对话属于【" + allType + "】哪个分类?对话内容为:";
String tip = "你的回答必须在所给范围内。";
String example = "示例办案警官问你的家庭情况裴金禄回答我父亲叫裴国智今年67岁退休电话13519353723;母亲李金芬今年61岁无业我弟弟裴金生今年34岁在中石油运输公司上班。回复{\"type\":\"家庭情况\"}。";
List<Message> messages = new ArrayList<>(List.of(new SystemMessage(test + record.getQuestion() + record.getAnswer() + tip + example)));
Prompt prompt = new Prompt(messages);
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// log.info("开始分析:");
ChatResponse call = chatClient.call(prompt);
stopWatch.stop();
// log.info("耗时:{}", stopWatch.getTotalTimeSeconds());
Generation result = call.getResult();
String content = result.getOutput().getContent();
// log.info("问:{}, 答:{}", qa.getQuestion(), qa.getAnswer());
// log.info("分析的结果是:{}", content);
System.out.println("问:"+record.getQuestion()+"答:"+record.getAnswer());
System.out.println("分析的结果是:"+ content);
record.setRecordType(content);
}
return list;
}
@GetMapping("test1")
public void test2(@Param("id") String id) {
NoteRecord noteRecord = recordService.getById(id);
String question = noteRecord.getQuestion();
String answer = noteRecord.getAnswer();
String test = "请从以下对话中提取所有关于" + noteRecord.getRecordType() + "的所有三元组";
// String test = "请从以下对话中提取所有三元组,对话内容为:";
String example = "。示例办案警官问你的家庭情况裴金禄回答我父亲叫裴国智今年67岁电话13519353723;母亲李金芬今年61岁我弟弟裴金生今年34岁。" +
"回复:{\"result\":[{\"主体\":\"裴金禄\",\"关系\":\"父子\",\"客体\":\"裴国智\"},{\"主体\":\"裴金禄\",\"关系\":\"母子\",\"客体\":\"李金芬\"},{\"主体\":\"裴金禄\",\"关系\":\"兄弟\",\"客体\":\"裴金生\"},{\"主体\":\"裴国智\",\"关系\":\"年龄\",\"客体\":67},{\"主体\":\"李金芬\",\"关系\":\"年龄\",\"客体\":61},{\"主体\":\"裴金生\",\"关系\":\"年龄\",\"客体\":34}]}。";
String a = "你是一个问讯笔录分析师,请分析以下内容中所有规定的三元组信息并补充完整,规定的三元组信息如下:[{startNodeType:'Person',entity:'',endNodeType:'Person',property:'',value:'' },{startNodeType:'Person',entity:'',endNodeType:'Organ',property:'',value:''}],要求返回格式{result:[三元组信息]}。";
List<Message> messages = new ArrayList<>(List.of(new SystemMessage(a + question+answer)));
// List<Message> messages = new ArrayList<>(List.of(new SystemMessage(test + question+answer+example)));
Prompt prompt = new Prompt(messages);
StopWatch stopWatch = new StopWatch();
stopWatch.start();
log.info("开始分析:");
ChatResponse call = chatClient.call(prompt);
stopWatch.stop();
log.info("耗时:{}", stopWatch.getTotalTimeSeconds());
Generation result = call.getResult();
String content = result.getOutput().getContent();
log.info("分析的结果是:{}", content);
}
}

@ -0,0 +1,106 @@
package com.supervision.springaidemo.controller;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.supervision.springaidemo.domain.ModelMetric;
import com.supervision.springaidemo.dto.QARecordNodeDTO;
import com.supervision.springaidemo.service.ModelMetricService;
import com.supervision.police.service.NoteCheckRecordService;
import com.supervision.springaidemo.thread.RunCheckThread;
import com.supervision.springaidemo.thread.RunCheckThreadPool;
import com.supervision.springaidemo.util.RecordRegexUtil;
import com.supervision.springaidemo.util.WordReadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* ,2
* ,,()
*
*/
@RestController
@Slf4j
@RequestMapping("newTestChat")
public class NewTestController {
private final OllamaChatClient chatClient;
@Autowired
private ModelMetricService modelMetricService;
@Autowired
private NoteCheckRecordService noteCheckRecordService;
@Autowired
public NewTestController(OllamaChatClient chatClient) {
this.chatClient = chatClient;
}
private static final String template = """
---
1:
---
---
{context}
---
,,
json
---
{"match":"true/false(相关回复true,不相关回复false)","summary":"如果有关联,则对该笔录进行总结"}
---
,!!
""";
@GetMapping("newTestChat")
public void newTestChat() {
// 只查入罪指标
ModelMetric modelMetric = modelMetricService.lambdaQuery().eq(ModelMetric::getMetricCode, "RZ007").one();
File file = FileUtil.file("/Users/flevance/Desktop/宁夏审讯大模型/裴金禄/行为人和受害人/裴金禄第一次.docx");
String context = WordReadUtil.readWord(file.getPath());
List<QARecordNodeDTO> qaList = RecordRegexUtil.recordRegex(context, "裴金禄");
for (QARecordNodeDTO qaRecordNodeDTO : qaList) {
String systemPrompt = """
,
""";
List<Message> messages = new ArrayList<>(List.of(new SystemMessage(systemPrompt)));
Map<String, Object> param = new HashMap<>();
param.put("context", qaRecordNodeDTO.toString());
String format = StrUtil.format(template, param);
List<Message> userMessageList = new ArrayList<>();
if (format.length() > 8000) {
log.info("分段提交");
for (String s : StrUtil.split(format, 6000)) {
userMessageList.add(new UserMessage(s));
userMessageList.add(new AssistantMessage("继续"));
}
userMessageList.remove(userMessageList.size() - 1);
} else {
userMessageList.add(new UserMessage(format));
}
messages.addAll(userMessageList);
RunCheckThread runCheck = new RunCheckThread("尝试分段提取-第一段找相似", chatClient, noteCheckRecordService, new Prompt(messages), FileUtil.getName(file), format, systemPrompt, modelMetric, 5);
RunCheckThreadPool.chatExecutor.submit(runCheck);
}
}
}

@ -0,0 +1,118 @@
package com.supervision.springaidemo.controller;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.supervision.springaidemo.domain.ModelMetric;
import com.supervision.springaidemo.service.ModelMetricService;
import com.supervision.police.service.NoteCheckRecordService;
import com.supervision.springaidemo.thread.RunCheckThread;
import com.supervision.springaidemo.thread.RunCheckThreadPool;
import com.supervision.springaidemo.util.WordReadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* controller
*/
@RestController
@Slf4j
@RequestMapping("rzChat")
public class RzChatController {
private static final String step1Template = """
step by step,
step1:;
,"问","答"{noteUserName}:
---
{context}
---
step2::
:
:{metricDetailTemplate},true;
::{metricDetailTemplate},false;
,,,empty
step3:,:
1.:true/false/empty
2.:,()true,!
3.:,,true/false,!
step4:json, JSONvalue,:
---
{"result":"结论", "originalContext":"笔录对应原话","reason":"原因"}
---
,!
""";
private final OllamaChatClient chatClient;
@Autowired
private ModelMetricService modelMetricService;
@Autowired
private NoteCheckRecordService noteCheckRecordService;
@Autowired
public RzChatController(OllamaChatClient chatClient) {
this.chatClient = chatClient;
}
@GetMapping("extract")
public void extract() throws InterruptedException {
List<File> files = FileUtil.loopFiles("/Users/flevance/Desktop/宁夏审讯大模型/裴金禄/行为人和受害人/");
for (File file : files) {
String context = WordReadUtil.readWord(file.getPath());
// 只查入罪指标
List<ModelMetric> list = modelMetricService.lambdaQuery().likeRight(ModelMetric::getMetricCode, "RZ").list();
for (ModelMetric modelMetric : list) {
String systemPrompt = """
,,,,,
""";
List<Message> messages = new ArrayList<>(List.of(new SystemMessage(systemPrompt)));
Map<String, Object> param = new HashMap<>();
param.put("metricDetailTemplate", StrUtil.format(modelMetric.getMetricDetailTemplate(), MapUtil.of("action", "裴金禄")));
param.put("noteUserName", "裴金禄");
param.put("context", context);
String format = StrUtil.format(step1Template, param);
List<Message> userMessageList = new ArrayList<>();
if (format.length() > 8000) {
log.info("分段提交");
for (String s : StrUtil.split(format, 6000)) {
userMessageList.add(new UserMessage(s));
userMessageList.add(new AssistantMessage("继续"));
}
userMessageList.remove(userMessageList.size() - 1);
} else {
userMessageList.add(new UserMessage(format));
}
messages.addAll(userMessageList);
RunCheckThread runCheck = new RunCheckThread("裴金禄尝试通过直接定义模板", chatClient, noteCheckRecordService, new Prompt(messages), FileUtil.getName(file), format, systemPrompt, modelMetric, 0);
RunCheckThreadPool.chatExecutor.submit(runCheck);
}
}
}
}

@ -0,0 +1,146 @@
package com.supervision.springaidemo.controller;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.supervision.springaidemo.domain.VpAskTemplateQuestionLibrary;
import com.supervision.springaidemo.domain.VpCommonDic;
import com.supervision.springaidemo.service.VpAskTemplateQuestionLibraryService;
import com.supervision.springaidemo.service.VpCommonDicService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.ai.ollama.OllamaEmbeddingClient;
import org.springframework.ai.ollama.api.OllamaOptions;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
@Slf4j
@RequestMapping("similarity")
@RestController
public class SimilarityController {
private final SimpleVectorStore store;
private final OllamaChatClient chatClient;
@Autowired
private VpCommonDicService vpCommonDicService;
@Autowired
private VpAskTemplateQuestionLibraryService libraryService;
@Autowired
public SimilarityController(OllamaEmbeddingClient ollamaEmbeddingClient, OllamaChatClient chatClient) {
store = new SimpleVectorStore(ollamaEmbeddingClient.withDefaultOptions(OllamaOptions.create().withModel("llama3-chinese:8b")));
this.chatClient = chatClient;
// File file = FileUtil.file("/Users/flevance/Java/spring-ai-demo/spring-ai-demo/data/storeData.json");
// if (FileUtil.isNotEmpty(file)) {
// store.load(file);
// }
}
@GetMapping("init")
public void init() {
// 从数据库中加载向量数据
List<VpAskTemplateQuestionLibrary> list = libraryService.lambdaQuery().list();
for (VpAskTemplateQuestionLibrary vpAskTemplateQuestionLibrary : list) {
String questionJsonStr = vpAskTemplateQuestionLibrary.getQuestion();
List<String> questionList = JSONUtil.toList(questionJsonStr, String.class);
questionList.add(vpAskTemplateQuestionLibrary.getDescription());
for (String question : questionList) {
Map<String, Object> meta = MapUtil.of("dictId", vpAskTemplateQuestionLibrary.getDictId());
meta.put("id", vpAskTemplateQuestionLibrary.getId());
Document document = new Document(question, meta);
store.add(ListUtil.of(document));
log.info("{}已添加到向量数据库", question);
}
}
log.info("向量化完成");
// 加载完成之后,保存到本地
store.save(FileUtil.newFile("/Users/flevance/Java/spring-ai-demo/spring-ai-demo/data/storeData.json"));
log.info("保存完成");
}
@GetMapping("similarity")
public void similarity(String userQuestion) {
List<Document> documents = store.similaritySearch(userQuestion);
for (Document document : documents) {
log.info("{}", document.getContent());
}
}
@GetMapping("itemCheck")
public void itemCheck() {
File file = FileUtil.file("/Users/flevance/Desktop/虚拟病人/副本副本医生临床问诊问题收集v1.xlsx");
ExcelReader reader = ExcelUtil.getReader(file, 1);
ExcelWriter writer = ExcelUtil.getWriter(file, "match");
List<VpCommonDic> list = vpCommonDicService.lambdaQuery().like(VpCommonDic::getNameZhPath, "/").eq(VpCommonDic::getGroupCode, "AQT").list();
Set<String> databaseExistSet = new HashSet<>();
for (VpCommonDic vpCommonDic : list) {
databaseExistSet.add(vpCommonDic.getNameZhPath());
}
List<List<Object>> objects = reader.read(1);
for (int i = 0; i < objects.size(); i++) {
List<Object> list1 = objects.get(i);
String s = (String) list1.get(0);
String s1 = (String) list1.get(1);
// 如果不存在,则记录
if (!databaseExistSet.contains(s + "/" + s1)) {
writer.writeCellValue(1, i + 1, "不存在");
} else {
writer.writeCellValue(1, i + 1, "存在");
}
}
writer.flush();
}
@GetMapping("similarityBatch")
public void similarityBatch() {
init();
Map<Long, VpCommonDic> dicMap = vpCommonDicService.list().stream().collect(Collectors.toMap(VpCommonDic::getId, Function.identity()));
// 从Excel中获取数据
File file = FileUtil.file("/Users/flevance/Desktop/虚拟病人/副本副本医生临床问诊问题收集v1.xlsx");
ExcelReader reader = ExcelUtil.getReader(file, 2);
ExcelWriter writer = ExcelUtil.getWriter(file, "result");
List<Object> objects = reader.readColumn(2, 1);
for (int i = 0; i < objects.size(); i++) {
int rowIndex = i + 1;
String question = objects.get(i).toString();
try {
List<Document> documents = store.similaritySearch(question);
Optional<Document> first = documents.stream().findFirst();
if (first.isPresent()) {
Map<String, Object> meta = first.get().getMetadata();
String dictId = meta.get("dictId").toString();
VpCommonDic vpCommonDic = dicMap.get(Long.parseLong(dictId));
writer.writeCellValue(8, rowIndex, question);
writer.writeCellValue(9, rowIndex, "");
writer.writeCellValue(10, rowIndex, vpCommonDic.getNameZhPath());
writer.writeCellValue(11, rowIndex, dictId);
}
} catch (Exception e) {
log.error("出现错误", e);
}
log.info("{}匹配完成.", question);
}
writer.flush();
}
}

@ -0,0 +1,44 @@
package com.supervision.springaidemo.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@Slf4j
@RequestMapping("question")
public class SimilarityQuestionController {
private static final String template = """
,,:
10,,
""";
private final OllamaChatClient chatClient;
@Autowired
public SimilarityQuestionController(OllamaChatClient chatClient) {
this.chatClient = chatClient;
}
@GetMapping("test")
public void test() {
Prompt prompt = new Prompt(List.of(new UserMessage(template)));
ChatResponse call = chatClient.call(prompt);
Generation result = call.getResult();
String content = result.getOutput().getContent();
log.info("结果是:{}", content);
}
}

@ -0,0 +1,83 @@
package com.supervision.springaidemo.controller;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.supervision.springaidemo.dto.AnswerDTO;
import com.supervision.springaidemo.dto.GlobalResult;
import com.supervision.springaidemo.util.TtsUtil;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
*
*/
@RequestMapping("vp-test")
@RestController
public class VPTestController {
private final OllamaChatClient chatClient;
// 使用多线程进行提交
@Autowired
public VPTestController(OllamaChatClient chatClient) {
this.chatClient = chatClient;
}
public static final String userPromptTemplate = """
,,
---
:{userQuestion}
---
1:{dataBaseQuestion1},ID:1761963909201268731
2:{dataBaseQuestion2},ID:1761963909201268732
3:{dataBaseQuestion3},ID:1761963909201268733
4:{dataBaseQuestion4},ID:1761963909201268734
5:{dataBaseQuestion5},ID:1761963909201268735
---
json:{"id":"对应的问题ID","question":"匹配到的预设问题"}
""";
// private static final String systemPrompt = """
// 你现在扮演一个医生,以医生的角度从预设问题列表中找到与给定问题最匹配的一项
// """;
@GetMapping("test")
public String test(String userQuestion) {
List<Message> messageHistoryList = new ArrayList<>();
// messageHistoryList.add(new SystemMessage(systemPrompt));
HashMap<String, String> map = new HashMap<>();
map.put("userQuestion", userQuestion);
map.put("dataBaseQuestion1", "您有什么症状?");
map.put("dataBaseQuestion2", "您有什么不舒服的?");
map.put("dataBaseQuestion3", "您是否有腹痛?");
map.put("dataBaseQuestion4", "您还有什么不舒服的?");
map.put("dataBaseQuestion5", "您还有其他什么症状吗?");
StrUtil.format(userPromptTemplate, map);
messageHistoryList.add(new UserMessage(StrUtil.format(userPromptTemplate, map)));
Prompt prompt = new Prompt(messageHistoryList);
ChatResponse call = chatClient.call(prompt);
Generation result = call.getResult();
return result.getOutput().getContent();
}
}

@ -0,0 +1,90 @@
package com.supervision.springaidemo.controller;
import cn.hutool.json.JSONUtil;
import com.supervision.springaidemo.dto.AnswerDTO;
import com.supervision.springaidemo.dto.GlobalResult;
import com.supervision.springaidemo.util.TtsUtil;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RequestMapping("virtual-patient")
@RestController
public class VirtualPatientTestController {
private final OllamaChatClient chatClient;
// 使用多线程进行提交
@Autowired
public VirtualPatientTestController(OllamaChatClient chatClient) {
this.chatClient = chatClient;
}
public static final String userPromptTemplate = """
---
:xxx
:xxx
:
:
:
:
:饿
便:便3便
:饿
---
json:{"answer":"根据病例情况回复的内容"}
""";
private static final String systemPrompt = """
(),
,
'//'",!
'',','!!!
""";
private static final List<Message> messageHistoryList = new ArrayList<>();
static {
messageHistoryList.add(new SystemMessage(systemPrompt));
messageHistoryList.add(new UserMessage(userPromptTemplate));
messageHistoryList.add(new AssistantMessage("好的,已了解我要扮演病人的基本情况。已准备好对话了。"));
}
@GetMapping("talk")
public String talk(String question) {
messageHistoryList.add(new UserMessage(question));
Prompt prompt = new Prompt(messageHistoryList);
ChatResponse call = chatClient.call(prompt);
Generation result = call.getResult();
String content = result.getOutput().getContent();
messageHistoryList.add(new AssistantMessage(content));
return content;
}
@GetMapping("chatVoice")
public GlobalResult<AnswerDTO> chatVoice(String question){
String talk = talk(question);
AnswerDTO answer = JSONUtil.toBean(talk, AnswerDTO.class);
String answerBase64 = TtsUtil.ttsTransform(answer.getAnswer());
answer.setAnswerBase64(answerBase64);
return GlobalResult.ok(answer);
}
}

@ -0,0 +1,76 @@
package com.supervision.springaidemo.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import lombok.Data;
/**
* @TableName model_metric
*/
@TableName(value = "model_metric")
@Data
public class ModelMetric implements Serializable {
/**
*
*/
@TableId
private String id;
/**
*
*/
private String metricCode;
/**
* ID
*/
private Integer metricId;
/**
*
*/
private String metricName;
/**
* ,
*/
private String metricDetailTemplate;
/**
* ,,
*/
private String example;
/**
*
*/
private String metricTrueDesc;
/**
*
*/
private String metricFalseDesc;
/**
*
*/
private String metricDesc;
/**
* 0 1 2
*/
private Integer metricType;
/**
*
*/
private String promptTemplate;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
}

@ -0,0 +1,35 @@
package com.supervision.springaidemo.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import lombok.Data;
/**
*
* @TableName model_metric_example
*/
@TableName(value ="model_metric_example")
@Data
public class ModelMetricExample implements Serializable {
/**
*
*/
@TableId
private String id;
/**
*
*/
private String metricCode;
/**
*
*/
private String example;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
}

@ -0,0 +1,83 @@
package com.supervision.springaidemo.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import lombok.Data;
/**
*
*
* @TableName note_check_record
*/
@TableName(value = "note_check_record")
@Data
public class NoteCheckRecord implements Serializable {
/**
* ID
*/
@TableId
private String id;
/**
*
*/
private String caseName;
/**
*
*/
private String personName;
/**
*
*/
private String noteName;
/**
* /
*/
private String type;
/**
*
*/
private String metricCode;
/**
*
*/
private String metricName;
/**
*
*/
private String systemPrompt;
/**
*
*/
private String prompt;
/**
*
*/
private String result;
/**
*
*/
private String originalContext;
/**
*
*/
private String reason;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
}

@ -0,0 +1,81 @@
package com.supervision.springaidemo.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
*
* @TableName vp_ask_template_question_library
*/
@TableName(value ="vp_ask_template_question_library")
@Data
public class VpAskTemplateQuestionLibrary implements Serializable {
/**
*
*/
@TableId
private String id;
/**
* ID(common_dictID)
*/
private Long dictId;
/**
*
*/
private String code;
/**
*
*/
private String description;
/**
*
*/
private String question;
/**
*
*/
private String defaultAnswerCode;
/**
*
*/
private String defaultAnswer;
/**
* id
*/
private String defaultAnswerResourceId;
/**
* ID
*/
private String createUserId;
/**
*
*/
private Date createTime;
/**
*
*/
private String updateUserId;
/**
*
*/
private Date updateTime;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
}

@ -0,0 +1,86 @@
package com.supervision.springaidemo.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
*
* @TableName vp_common_dic
*/
@TableName(value ="vp_common_dic")
@Data
public class VpCommonDic implements Serializable {
/**
*
*/
@TableId(type = IdType.AUTO)
private Long id;
/**
*
*/
private String code;
/**
*
*/
private String nameZh;
/**
*
*/
private String nameEn;
/**
* code
*/
private String groupCode;
/**
* id
*/
private Long parentId;
/**
* ,
*/
private Integer priority;
/**
*
*/
private String nameZhPath;
/**
*
*/
private String description;
/**
*
*/
private String createUserId;
/**
*
*/
private Date createTime;
/**
*
*/
private String updateUserId;
/**
*
*/
private Date updateTime;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
}

@ -0,0 +1,11 @@
package com.supervision.springaidemo.dto;
import lombok.Data;
@Data
public class AnswerDTO {
private String answer;
private String answerBase64;
}

@ -0,0 +1,45 @@
package com.supervision.springaidemo.dto;
import lombok.Data;
import org.springframework.http.HttpStatus;
@Data
public class GlobalResult<T> {
private int code = 200;
private String msg = "success";
private T data;
public static <T> GlobalResult<T> ok() {
return ok(null);
}
public static <T> GlobalResult<T> ok(T data) {
GlobalResult<T> globalResult = new GlobalResult<>();
globalResult.setData(data);
return globalResult;
}
public static <T> GlobalResult<T> ok(T data, String message) {
GlobalResult<T> globalResult = new GlobalResult<>();
globalResult.setMsg(message);
globalResult.setData(data);
return globalResult;
}
public static <T> GlobalResult<T> error(String msg) {
return error(HttpStatus.INTERNAL_SERVER_ERROR.value(), null, msg);
}
public static <T> GlobalResult<T> error(int code, T data, String msg) {
GlobalResult<T> globalResult = new GlobalResult<>();
globalResult.setCode(code);
globalResult.setData(data);
globalResult.setMsg(msg);
return globalResult;
}
}

@ -0,0 +1,13 @@
package com.supervision.springaidemo.dto;
import lombok.Data;
@Data
public class MetricResultDTO {
private String result;
private String originalContext;
private String reason;
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save